Skip to content

[Do not review] Bound JSON shared data path reads to the path end in Wide parts - #121092

Closed
Avogar wants to merge 14 commits into
masterfrom
json-shared-data-read-until-path-bound
Closed

Avogar wants to merge 14 commits into
masterfrom
json-shared-data-read-until-path-bound

Conversation

@Avogar

@Avogar Avogar commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Reading a single path from the ADVANCED JSON shared data serialization seeks to the path's mark in the ObjectSharedDataData stream and reads it, but the read was bounded only by the granule mark, so the read buffer read ahead across all the following paths in the granule. For a small path stored next to large ones (for example a small String path among large arrays) this over-reads by a large factor — in both decompressed bytes and bytes read from object storage.

Now the serialization owns the Data stream in Wide parts: it seeks to each path's mark and bounds the read to the path's end — the next path that is not read together with it — so a read no longer runs into the following paths. A run of consecutive requested paths is read in one go, and subcolumn reads are bounded the same way. The Data stream is no longer prefetched (it is read by seeking to marks), and the reader no longer applies its range-wide seek and read-until to it.

The behavior is guarded by the new setting merge_tree_bound_json_shared_data_path_reads (enabled by default). When disabled, the previous behavior is restored, including prefetch of the Data stream controlled by merge_tree_prefetch_json_shared_data_substreams.

Changelog category (leave one):

  • Performance Improvement

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

Reduce over-reading of JSON shared data when selecting individual paths from Wide parts: a path's read is now bounded to its end instead of the whole granule, cutting decompressed and object-storage read bytes for small paths stored next to large ones. Controlled by the new setting merge_tree_bound_json_shared_data_path_reads (enabled by default).


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

Reading a single path from the ADVANCED JSON shared data serialization
seeks to the path's mark in the ObjectSharedDataData stream and reads it,
but the read was bounded only by the granule mark, so the read buffer
could read ahead across all following paths in the granule. For a small
path stored next to large ones this over-reads by a large factor, in both
decompressed bytes and bytes read from object storage.

Now the serialization owns the Data stream in Wide parts: it seeks to each
path's mark and bounds the read to the path's end - the next path that is
not read together with it - so a read no longer runs into the following
paths. A run of consecutive requested paths is read in one go. The Data
stream is no longer prefetched (it is read by seeking to marks), and the
reader no longer applies its range-wide seek and read-until to it.

The behavior is guarded by the new setting
merge_tree_bound_json_shared_data_path_reads (enabled by default). When it
is disabled the previous behavior is restored, including prefetch of the
Data stream controlled by merge_tree_prefetch_json_shared_data_substreams.

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

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7a7caba]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
AddressSanitizer: heap-use-after-free (STID: 2240-2a7d) FAIL cidb
Stress test (arm_asan_ubsan, s3) FAIL
AddressSanitizer: heap-use-after-free (STID: 2240-2a7d) FAIL cidb
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
topk #6 FAIL dashboard
topk #2 FAIL dashboard

AI Review

Summary

This PR moves bounded JSON shared-data path reads for Wide parts into SerializationObjectSharedData, adds merge_tree_bound_json_shared_data_path_reads, and stops prefetching the shared-data Data stream when that mode is enabled. The direction is sound, but the current head still has one compatibility break, one mixed whole-path/subcolumn regression, and several user-facing strings that promise a stronger contract than the implementation actually provides, so this should not merge yet.

PR Metadata
  • Changelog category: Performance Improvement matches the change.
  • Changelog entry: required and user-readable, but it overstates the behavior by saying a path is bounded "to its end instead of the whole granule". The implementation still stops only at the first later compressed block it can prove has no requested data, so it can still read into a following path that shares blocks with the requested one.
  • Exact replacement: Reduce over-reading of JSON shared data when selecting individual paths from Wide parts: reads now stop at the first later compressed block known to contain no requested data, which usually avoids pulling the rest of the granule for small paths stored next to large ones. Controlled by the new setting merge_tree_bound_json_shared_data_path_reads (enabled by default).
Findings

❌ Blockers

  • [src/Core/Settings.cpp:1894] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/121092#discussion_r4055229634] The new default-on behavior is still registered as {"26.10", true, true, ...}, so SET compatibility = '26.9' will keep merge_tree_bound_json_shared_data_path_reads = 1 instead of restoring the pre-26.10 granule-bound reads. That breaks the compatibility contract for a new default change, and it also contradicts the PR text that says disabling the setting restores the previous behavior. Suggested fix: make the history entry {"26.10", false, true, ...} unless old-compatibility mode is intentionally unsupported, in which case the PR text and setting docs need to say that explicitly.

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationObjectSharedData.cpp:1258] Paths requested only as subcolumns are still treated as fully requested when boundary marks are built. If a query reads whole path p1 and only subcolumn p2.size0, p1 is now bounded after p2 instead of before it, so the PR reintroduces the "small path next to large path" over-read for mixed whole-path/subcolumn queries. Suggested fix: exclude requested_paths_subcolumns from the requested state here, or carry a third "boundary-only" state so whole-path reads can stop at subcolumn-only paths while those subcolumns still deserialize from their own marks.
  • [src/DataTypes/Serializations/SerializationObjectSharedData.cpp:1215] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/121092#discussion_r4057700691] The implementation still cannot stop at the actual next path boundary when an unrequested path starts in the requested path's last compressed block and then continues into later blocks. In that layout there is no persisted mark for the first later block, so the reader still runs through the whole following path (and, in the empty-chunk trade-off, sometimes through the rest of the next empty chunk) even with the new setting enabled. That means the real contract is "stop at the first later mark-aligned block known to have no requested data", not "stop at the path end". Suggested fix: either persist enough boundary information to find that first later block, or weaken the documented/PR/changelog contract to the mark-aligned behavior and measure that weaker win directly.
  • [src/DataTypes/Serializations/SerializationObjectSharedData.cpp:1184] and [src/Core/Settings.cpp:1888], [src/Core/Settings.cpp:1892] The code comment and user-visible setting descriptions still promise exact path-end / "disable these prefetches" behavior that the implementation does not provide. merge_tree_bound_json_shared_data_path_reads can still read into a following path that shares blocks, and merge_tree_prefetch_json_shared_data_substreams = 0 only suppresses prefetch for ObjectSharedDataData, not for the other seeked shared-data streams. Suggested fix: narrow these strings to the actual mark-aligned bound and to the specific substreams affected.
Tests
  • ⚠️ This is a Performance Improvement PR, but the current evidence still does not show the intended win on a JSON-heavy workload. The cloud perf report only found unrelated clickbench noise and explicitly said it neither confirms nor rules out the claimed I/O savings. Please add a focused before/after measurement on a Wide part with a small requested path next to large unrequested paths, reporting at least decompressed bytes and, if relevant, remote/object-storage read bytes.
  • ⚠️ Add a focused regression test for mixed whole-path/subcolumn reads with merge_tree_bound_json_shared_data_path_reads = 1; once the boundary handling is fixed, that case needs coverage so the regression does not come back.
Final Verdict

Status: ⚠️ Request changes

  • Minimum required actions: fix the compatibility history entry for merge_tree_bound_json_shared_data_path_reads; fix the mixed whole-path/subcolumn boundary handling so subcolumn-only paths do not keep earlier whole-path reads open; and weaken the setting/comment/changelog contract to the actual behavior unless the implementation is extended to stop at true path ends, with a focused measurement proving the claimed win.

LLVM Coverage Report

Measured on commit 7a7caba.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 128/134 (95.52%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Sep 19, 2026
…read-until-path-bound

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReaderWide.cpp
@Avogar
Avogar force-pushed the json-shared-data-read-until-path-bound branch from 23f5cea to e658755 Compare September 19, 2026 22:47
@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 19, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
…ut requested data

A path's read in the ObjectSharedDataData stream was bounded to the first
following path not read together with it, moved past a shared compressed block
when that path started mid-block. That stops the read at the moved boundary even
when a requested path follows in the next block, splitting what could be one
read into several, and it was computed per chunk, so it could not see the paths
of the following chunks.

Compute the bound globally instead: while reading paths marks of all chunks,
collect the compressed blocks that contain no requested data - a block contains
requested data if a requested path starts in it, or if the previous path is
requested and continues into it. A path's read is then bounded to the first such
block after it, which is the tightest safe stop: nothing requested starts in it
and nothing requested continues into it, so the whole block can be dropped from
the read. Blocks holding requested data are read in one go, across chunks too,
since chunk data in the stream is contiguous.

Chunks with no requested paths are represented by their data mark alone, without
reading their paths marks.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

/// The compressed block contains requested data if a requested path starts in it, or if the previous
/// path is requested and continues into it - which is the case when this mark is not at a block start.
if (requested || (previous_path_requested && mark.offset_in_decompressed_block != 0))

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.

add_mark still only sees chunk starts and path starts, so this misses the common case where an unrequested path begins in the same compressed block as the preceding requested path and then continues into later blocks.

Concrete trace: requested p1 ends in block 100, unrequested p2 starts at [100, 50] and spills into blocks 200 / 300, and the next requested path starts at 400. This code correctly marks block 100 as requested, but it never sees block 200, so compressed_blocks_without_requested_data has no safe stop for p1 even though block 200 already contains only p2.

The empty-chunk case from the existing thread is one manifestation of the same gap, but it is not the only one. We need some persisted boundary inside every mid-block unrequested region (or an equivalent way to recover the first later block) before the “first compressed block without requested data” invariant actually holds.

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.

The trace is correct, and it is a limit of what the format records, not of this computation. A mark's offset_in_compressed_file is the only thing that tells us where a compressed block starts; a block's extent is in its own header, which we can only learn by reading the block - that is, by performing the read we are trying to bound. In your trace, blocks 200 and 300 are interior blocks of a single unrequested path, so no mark in ObjectSharedDataPathsMarks points at them, and no other stream does either: ObjectSharedDataSubstreamsMarks only adds positions for paths that have several substreams, and reading it for unrequested paths means reading the substreams metadata and marks of every path on every query - an unconditional cost to remove a bounded one, and still nothing for a single-substream path.

So the invariant this implements is "the first compressed block that a mark points at and that contains no requested data", and I will fix the comment to say exactly that rather than the stronger claim.

What that bounds the over-read to is the data of the one unrequested path that shares the last compressed block with the requested path, instead of everything up to the end of the granule as before. Making it exact requires the writer to record block boundaries or to flush at path boundaries, which is a format change and would defeat the min_compress_block_size batching that keeps many small paths cheap - a separate change behind a new serialization version, not something this PR can do.

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 still is not fixed in the current code. src/DataTypes/Serializations/SerializationObjectSharedData.cpp:1184 still says the bound "does not read forward into the following paths", but the shared-compressed-block case from the original trace remains deliberately possible, so the stronger contract is still in-tree.

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7a7caba4c with master e8d154996 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5dbe50912; 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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +1714.3 s (+10%) in total before that adjustment.

Job report

@Avogar
Avogar marked this pull request as ready for review September 21, 2026 13:13
@Avogar Avogar changed the title Bound JSON shared data path reads to the path end in Wide parts [Do not review] Bound JSON shared data path reads to the path end in Wide parts Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 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: 44fd134f-b45b-489b-8c0a-a81c5164e4d0
  • MIRAI run: 26dafcf7-9e6b-456a-8038-3ffd1c510b93
  • PR check IDs:
    • clickbench_1999480_1790463822
    • clickbench_1999488_1790463822
    • clickbench_1999497_1790463822
    • tpch_adapted_1_official_1999504_1790463822
    • tpch_adapted_1_official_1999511_1790463822
    • tpch_adapted_1_official_1999552_1790463822

Comment thread src/Core/Settings.cpp
Enables prefetching of JSON shared data substreams in Wide parts that are read by seeking to a mark. Such a prefetch reads from the beginning of the granule, which is usually not the position the substream is read from, so it can be wasted. Disable to skip these prefetches. Has no effect on the shared data Data substream when `merge_tree_bound_json_shared_data_path_reads` is enabled (it is not prefetched then).
)", 0) \
DECLARE(Bool, merge_tree_bound_json_shared_data_path_reads, true, R"(
Bounds the read of each JSON shared data path in Wide parts to the end of its data, so reading a path does not read ahead into the following paths. When disabled, a path's read is bounded only by the granule, which over-reads for small paths stored next to large ones.

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 setting description still promises a stronger contract than the implementation provides. The new reader can still read into a following path that shares the last compressed block (and, in the empty-chunk trade-off discussed on the existing thread, can extend farther), so "to the end of its data" / "does not read ahead into the following paths" is not accurate.

Because this string is user-visible in generated settings docs and system.settings, it should describe the weaker "first compressed block without requested data" behavior instead of an exact path-end bound.

readBinaryLittleEndian(path_info.data_mark.offset_in_compressed_file, *paths_marks_stream);
readBinaryLittleEndian(path_info.data_mark.offset_in_decompressed_block, *paths_marks_stream);
}
bool requested = path_it != chunk_structure.position_to_requested_path.end();

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.

Subcolumn-only paths should still be boundaries for earlier whole-path reads, but this now treats them as fully requested.

Concrete trace: the query asks for whole path p1 and only subcolumn p2.size0; p1 ends in block 100, p2 starts in block 200 and spans a large payload, and the next truly unrequested path starts at 1000. deserializePathsData later handles p2 via the subcolumn branch, not as a whole path, so p1 could stop at the first safe block after p2 starts. After this change add_mark(mark, true) keeps p2 in the requested set, so p1's data_end_mark moves to 1000 and we over-read the whole p2 payload again.

The first version of this patch kept requested_paths_subcolumns in boundary_marks; this regression brings back the exact "small path next to large path" over-read for mixed whole-path/subcolumn queries. requested needs to exclude subcolumn-only paths here, or add_mark needs a third state that distinguishes "read whole path" from "read one substream later".

Avogar and others added 8 commits September 25, 2026 17:44
…with requested data

The previous bound stopped a path's read at the first compressed block that a
mark points at and that contains no requested data. A path's interior blocks
carry no marks, so when a not-requested path shares a requested path's last
block and spans several mark-less blocks, the bound could only land past all of
them, dragging that whole not-requested path into the read.

Bound each sequence of consecutive requested paths at the compressed block where
the first not-requested path after it begins. When that path starts a fresh
block, the read ends before it; when it shares the sequence's last block, the
read stops right after that block. The block's end is not recorded anywhere, so
it is found by reading only the block header (checksum + 9 bytes), with the
underlying buffer bounded to the header so the block body is not fetched.

Add CompressedReadBufferBase::getCompressedBlockEnd (overridden in the file and
cached buffers) exposed through MergeTreeReaderStream and a new
get_compressed_block_end_callback in DeserializeBinaryBulkSettings, wired in
MergeTreeReaderWide only in Wide parts under
merge_tree_bound_json_shared_data_path_reads.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…th-bound' into json-shared-data-read-until-path-bound
getCompressedBlockEnd peeked a block header on the shared data stream's own
reader, which may already have read ahead of that block (a previous granule's
read-until can be bumped to a block end that spills into the next granule). It
set the header read-until before seeking, so on an AsynchronousBoundedReadBuffer
the bound landed behind already-read data and aborted with a logical error
("Attempt to set read until position before already read data"). This showed up
in Stateless tests over s3/packed storage, where that buffer is used.

Clear the bound before seeking to the block start, then set the header bound
(now ahead of the read position); after reading the header, rewind the reader
and drop the bound so the following data read, which bounds to an earlier
position, is not left behind already-read data. Reset the stream's grow-only
read-until guard too, since the peek cleared the bound behind its back.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Bounding a shared data path read needs the end of the compressed block where the
next path begins, which is found by reading only that block's header. Doing this
on the stream's own read buffer is unsafe: re-seeking and re-bounding it for the
peek is rejected by AsynchronousBoundedReadBuffer when the new bound is behind
already-read data, and returns an empty read on a ReadBufferFromFileView that
sits at its end - both happen for packed parts on object storage, so a selective
read of a JSON shared data path aborted with CANNOT_READ_ALL_DATA there.

Read the header from a separate buffer opened for the same stream instead, so
the main read buffer is untouched. It uses the same read settings, so it goes
through the filesystem cache the same way. The block-header parsing moves into
CompressedReadBufferBase::getCompressedBlockEnd, so the reader stream only opens
the buffer and delegates.

The existing test now forces full part storage so it covers packed parts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
countBytesInFilter's helpers took a 64-byte vector by value. Passing a vector
wider than the target's enabled features by value changes the ABI, which clang
reports as -Wpsabi (an error under -Werror) when building without AVX-512. The
helpers are always inlined, so a const reference is free and avoids the warning.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The header-reading approach determined a path's read bound by opening a separate
buffer and reading the next block's header. On object storage that adds an S3
request per bound, which is too many for a selective read.

Go back to computing the bound from the paths marks alone: a path's read ends at
the first compressed block that contains no requested data, found from the marks
that are read anyway. No extra read, and it avoids the packed-part header peek
that aborted with CANNOT_READ_ALL_DATA.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…hared-data-read-until-path-bound

# Conflicts:
#	src/Core/Settings.cpp
#	src/Core/SettingsChangesHistory.cpp
Comment thread src/Core/Settings.cpp
{"25.2", true, true, "A new setting controlling the usage of the thread pool for parallel prefixes deserialization in MergeTree"}) \
DECLARE(Bool, merge_tree_prefetch_json_shared_data_substreams, true, R"(
Enables prefetching of JSON shared data substreams in Wide parts that are read by seeking to a mark. Such a prefetch reads from the beginning of the granule, which is usually not the position the substream is read from, so it can be wasted. Disable to skip these prefetches.
Enables prefetching of JSON shared data substreams in Wide parts that are read by seeking to a mark. Such a prefetch reads from the beginning of the granule, which is usually not the position the substream is read from, so it can be wasted. Disable to skip these prefetches. Has no effect on the shared data Data substream when `merge_tree_bound_json_shared_data_path_reads` is enabled (it is not prefetched then).

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 description still reads as if merge_tree_prefetch_json_shared_data_substreams = 0 disables the seek-based JSON shared-data prefetches in general, but ISerialization::isPrefetchNeededForSubstream only consults the setting for ObjectSharedDataData.

ObjectSharedDataPathsMarks, ObjectSharedDataSubstreams, ObjectSharedDataSubstreamsMarks, and ObjectSharedDataPathsSubstreamsMetadata are still always prefetched. Either narrow the contract here to the Data substream specifically, or thread the setting through the other seek-based shared-data streams too.

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 submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants