Skip to content

Reduce peak memory during JSON advanced shared data merges - #109636

Merged
Avogar merged 26 commits into
masterfrom
fix-json-shared-data-merge-memory
Sep 16, 2026
Merged

Avogar merged 26 commits into
masterfrom
fix-json-shared-data-merge-memory

Conversation

@Avogar

@Avogar Avogar commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Reduce peak memory during merges of JSON columns with many unique paths in advanced shared data by materializing columns per-bucket instead of all at once, and by introducing a new advanced_chunked shared data serialization that splits row ranges into smaller chunks so only one flattened chunk needs to be in memory at a time. The chunk size is controlled by the new object_shared_data_target_chunk_rows MergeTree setting. Closes #108992


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

Avogar and others added 4 commits July 3, 2026 15:07
… materialization

During ADVANCED serialization of JSON shared data, `flattenAndBucketSharedDataPaths`
materialized ColumnDynamic columns for ALL paths across ALL buckets simultaneously.
With `Array(JSON)` containing many unique paths, this caused 53-75 GiB peak memory
on merges of small parts (454 rows, ~28 MiB).

Replace with `flattenSharedDataPathsForBucket` which processes one bucket at a time:
only one bucket's ColumnDynamic columns are alive at any point, reducing peak memory
by ~num_buckets. Path names are saved separately (as lightweight strings) for the
copy section. Remove now-unused `flattenAndBucketSharedDataPaths`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tting

Introduce a new `advanced_chunked` serialization version (v3) for JSON shared
data that splits large row ranges into smaller chunks during serialization.
This bounds peak memory during merges of JSON columns with many unique paths,
as only one chunk of data needs to be materialized at a time.

Key changes:
- New `ADVANCED_CHUNKED` serialization version with separate Compact
  (stream-then-chunks) and Wide (chunk-then-streams) layouts
- New `object_shared_data_target_chunk_rows` MergeTree setting (default 8192)
  controlling chunk size, with small-last-chunk merging
- New `SerializationArray::serializeOffsetsBinaryBulk` overload taking a raw
  `WriteBuffer &` to avoid extra mark writes in Compact parts
- `string_view` optimization in serialization helpers to avoid copying path
  strings
- `scanPathNamesForBucket` for lightweight path enumeration without column
  materialization
- `advanced_chunked` set as default serialization version for 26.7
- Test randomization: `advanced_chunked` added to random choices, generic
  `dependent_settings` mechanism for `object_shared_data_target_chunk_rows`
  derived from randomized `index_granularity`
- 15 new test files covering chunked serialization across compact/wide parts,
  various query patterns, path indexes, and regression scenarios
- Documentation updates in `newjson.md` and setting doc strings

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ata-merge-memory

# Conflicts:
#	src/DataTypes/Serializations/SerializationObjectHelpers.h
#	src/Storages/MergeTree/MergeTreeSettings.cpp
@mintlify

mintlify Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 15, 2026, 2:47 PM

@Avogar

Avogar commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Don't look at the number of ilnes, most of them are tests

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75357d3]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

Adds a new advanced_chunked JSON shared-data serialization, threads a new object_shared_data_target_chunk_rows setting through MergeTree writers, and restructures the ADVANCED/ADVANCED_CHUNKED shared-data readers and writers around per-bucket/per-chunk processing. The general layout looks coherent, but one chunk-sizing contract bug is still in the implementation and the current tests still miss two important compatibility/coverage boundaries, so this is not ready to merge.

Missing context / blind spots
  • ⚠️ The PR body and changelog promise lower peak memory during merges, but there is still no before/after measurement or focused stress test that demonstrates the claimed memory reduction. The current correctness tests prove that chunked reads and writes work on small fixtures; they do not prove the peak-RSS improvement. A reproducible multi-part Array(JSON) merge benchmark that records peak memory would close this gap.
Findings

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationObjectSharedData.cpp:740] The chunk-splitting rule rounds target_chunk_rows / 2 down, so odd targets violate the documented “merge the trailing chunk if it is smaller than half the target” contract. With object_shared_data_target_chunk_rows = 3 and 4 rows, this still emits 3,1 instead of a single 4-row chunk, which creates smaller-than-advertised chunks and extra per-chunk metadata/mark overhead. Compare against the real half (last_chunk_remainder * 2 >= target_chunk_rows) instead of floor-dividing the target.
  • [tests/queries/0_stateless/04410_json_shared_data_advanced_chunked_serialization_1.sql:65, tests/queries/0_stateless/04415_json_shared_data_advanced_chunked_serialization_compact_part_big.sql:64] The compact-part regression case labeled json.arr[].arr99, json.arr[].arr1 still executes json.arr[].arr4, json.arr[].arr1, so the compact suite never covers the “missing subcolumn first, existing subcolumn second” read order. A compact-only regression in that branch would still pass. Change both queries to actually select json.arr[].arr99, json.arr[].arr1.
  • [tests/queries/0_stateless/04409_json_shared_data_advanced_chunked_serialization.sql:48] [dismissed by author -- https://github.com/Reduce peak memory during JSON advanced shared data merges #109636#discussion_r3778876856] The real opt-in compatibility boundary is still untested. object_shared_data_serialization_version_for_zero_level_parts still defaults to map_with_buckets, but every merge case in this file forces zero-level parts to advanced_chunked too, so the suite never exercises the normal upgrade path where inserts create map_with_buckets parts and merges rewrite them into advanced_chunked. I still consider this real because that mixed-version merge path is what users hit when they enable only the main table setting.
  • [tests/queries/0_stateless/04419_json_shared_data_advanced_chunked_paths_indexes_1.sql:10, tests/queries/0_stateless/04420_json_shared_data_advanced_chunked_paths_indexes_2.sql:10] [dismissed by author -- https://github.com/Reduce peak memory during JSON advanced shared data merges #109636#discussion_r3959801330] Both boundary tests still use 255/256, which stay in the UInt8 branch of getSmallestIndexesType, so the new advanced_chunked CopyPathsIndexes path still has no coverage for the UInt16 or UInt32 index-width branches. I still consider this real because there is no replacement stateless or unit test elsewhere in the PR that reaches those branches.
Final Verdict

Needs changes before merge.

LLVM Coverage Report

Measured on commit 75357d3.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.50% 80.50% +0.00%

Changed lines: Changed C/C++ lines covered: 838/874 (95.88%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 7, 2026
@antonio2368 antonio2368 self-assigned this Jul 10, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{
addSettingsChanges(merge_tree_settings_changes_history, "26.7",
{
{"object_shared_data_serialization_version", "advanced", "advanced_chunked", "Enable advanced_chunked shared data serialization version by default to reduce peak memory during merges of JSON columns with many unique paths"},

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I am not sure I will enable it by default in this PR, most likely I will do it later in a separate PR, so this might be removed.

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.

can enabling it mess up rolling restarts?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, but with compatibility setting this won't be a problem. But anyway I think I will enable new chunked serialization later in a separate PR.

for (size_t bucket = 0; bucket != buckets; ++bucket)
{
const auto & flattened_paths = flattened_paths_buckets[bucket];
auto flattened_paths = flattenSharedDataPathsForBucket(

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.

So we hash all paths for every bucket?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, that's the tradeoff here. But I believe it should not lead to any noticeable slowdown, because hashing is much faster than flattening hundreds of paths into separate columns.

else if (serialization_version.value == SerializationVersion::ADVANCED_CHUNKED)
{
size_t end = limit && offset + limit < column.size() ? offset + limit : column.size();
size_t total_rows = end - offset;

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.

Can this be 0? Because it can mess up reads AFAIS.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes it can, for example if we have empty Array(JSON). But how it can mess up reads? We could have 0 rows in granules before with the same empty Array(JSON).

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.

Basically this #109636 (comment)

@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 28.60% 85.90% +57.30%
Functions 39.40% 92.70% +53.30%
Branches 20.60% 78.00% +57.40%

Changed lines: Changed C/C++ lines covered: 860/899 (95.66%) · Uncovered code

Full report · Diff report

@antonio2368 antonio2368 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.

Otherwise LGTM

Avogar and others added 2 commits August 6, 2026 22:47
…:ClickHouse/ClickHouse into fix-json-shared-data-merge-memory
In Compact parts the writer always emits at least one chunk per granule,
and an empty (0-row) granule still writes one empty chunk. The reader's
`while (total_chunk_rows < rows_offset + limit)` loops read zero chunks when
`rows_offset + limit == 0`, leaving that empty chunk's structure bytes
unconsumed. Without substream marks (`write_marks_for_substreams_in_compact_parts = 0`)
the column is read sequentially, so a trailing substream in the same column
(e.g. a Tuple element after a nested `Array(JSON)`) then reads from a
misaligned position and returns wrong data.

Read at least one chunk (`do`/`while`) so the empty chunk is always consumed,
matching the writer. Affects `advanced` and `advanced_chunked` shared-data
serializations when a nested JSON column has a fully empty granule followed
by more data in the same column.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `object_shared_data_serialization_version` default change and the new
`object_shared_data_target_chunk_rows` setting were recorded under the `26.7`
block, but this change targets `26.8`. Move both entries to the current
`26.8` MergeTree block so the settings history check passes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
/// 10001 rows → 10001 (1 < 5000, single chunk)
size_t num_chunks = total_rows / target_chunk_rows;
size_t last_chunk_remainder = total_rows % target_chunk_rows;
if (last_chunk_remainder > 0 && last_chunk_remainder >= target_chunk_rows / 2)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

object_shared_data_target_chunk_rows is a NonZeroUInt64, so odd targets are legal here, but this threshold rounds target / 2 down. With target_chunk_rows = 3 and total_rows = 4, last_chunk_remainder == 1 still satisfies >= 1, so we emit chunks 3, 1 even though the code comment and the new setting docs promise that a trailing chunk smaller than half the target is merged into the previous chunk. That makes the last chunk smaller than the advertised minimum and increases chunk count for odd targets. Comparing against the real half (last_chunk_remainder * 2 >= target_chunk_rows or >= (target_chunk_rows + 1) / 2) would keep the documented behavior.

select 'select json.arr[].arr1, json.arr[].arr99';
select json.arr[].arr1, json.arr[].arr99 from test_compact_advanced;
select 'select json.arr[].arr99, json.arr[].arr1';
select json.arr[].arr4, json.arr[].arr1 from test_compact_advanced;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This line still executes json.arr[].arr4, json.arr[].arr1, even though the label above says this case is supposed to cover json.arr[].arr99, json.arr[].arr1. That means the compact-part suite never actually exercises the “missing subcolumn first, existing subcolumn second” order that the wide tests cover, so a compact-only regression in that branch would still pass here. The same copy-paste typo is duplicated in 04415_json_shared_data_advanced_chunked_serialization_compact_part_big.sql:64.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Dear @antonio2368, 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.

@clickhouse-gh clickhouse-gh Bot added the comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... label Sep 4, 2026
Avogar and others added 2 commits September 4, 2026 18:20
Inserting a row with 65535/65536 paths cost ~1.4s and the merge that
rewrites it ~1.6s, which is the entire runtime of these tests. That is
fine in a normal job (7.1s) but the flaky check runs ~nproc-1 concurrent
copies of each new test against one server, inflating a run ~78x, so
both tests sat at 511-600s and hit the 600s per-test timeout.

Keep the UInt8/UInt16 path-index widths (255 and 256 paths); the
UInt16->UInt32 switch at 65536 is dropped - it was verified working and
was the whole cost. Both tests now run in ~0.2s.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109636&sha=d8a692ddd76d09682442c1841160ac9572975bda&name_0=PR&name_1=Stateless+tests+%28amd_debug%2C+flaky+check%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Avogar and others added 2 commits September 15, 2026 13:58
`serializeChunkBucketData` takes `WriteBuffer & data_stream`, but two
`next` calls were left as pointer dereferences, so `dbms` did not
compile and every build job failed or was dropped.

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

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Conflict in `SerializationObjectSharedData.cpp`: master sized compressed
blocks in the advanced JSON shared data writer by `min_compress_block_size`
(#86c03889b45), in the inline ADVANCED block that this branch moved into
`serializeChunkBucketData`. Kept the helper and ported the feature into it,
so both `advanced` and `advanced_chunked` inherit the setting and only start
a new block at a substream or path boundary once the current block reached
`min_compress_block_size`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Sep 16, 2026
Merged via the queue into master with commit 6780851 Sep 16, 2026
175 of 177 checks passed
@Avogar
Avogar deleted the fix-json-shared-data-merge-memory branch September 16, 2026 13:06
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 16, 2026
@darkleaf

Copy link
Copy Markdown
Contributor

@Avogar is it possible to backport it into 26.8lts?

@krsoninikhil

Copy link
Copy Markdown

Hey @Avogar, is this going to be backported to v26.8 LTS?

This branch was successfully deployed

1 active deployment
staging - docs — 75357d3c Deployed Sep 15, 2026 by mintlify[bot]
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-improvement Pull request with some product 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.

Reduce high memory usage in advanced shared data serialization with huge number of unque and sparse paths, especially for JSON inside Arrays

5 participants