Skip to content

Query level cache for ranges of patch parts - #115297

Draft
CurtizJ wants to merge 4 commits into
ClickHouse:masterfrom
CurtizJ:patch-parts-cache
Draft

CurtizJ wants to merge 4 commits into
ClickHouse:masterfrom
CurtizJ:patch-parts-cache

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

TODO...


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

CurtizJ and others added 2 commits August 18, 2026 13:23
…ge for final-mark-only ranges

For a mark range that contains only the final mark (which has no rows),
`end - begin` underflowed after clamping `end` to `num_marks_without_final - 1`,
and the function returned a garbage row count instead of 0. Such ranges are
produced by `RangesInPatchParts` for patch parts in `MergeOnKey` mode.

Co-Authored-By: Claude Fable 5 <[email protected]>
With `MergeOnKey` patch parts, one patch part typically covers many original
parts, and readers for different original parts (running in different threads)
re-read and re-postprocess the same ranges of the patch part.

Add `PatchRangesCache`: a query-level LRU cache of post-processed patch-part
blocks, living in `MergeTreeReadPoolBase` (like `PatchJoinCache`) and used by
`MergeTreePatchReaderMergeOnKey`. A request is served from the cache only when
cached entries fully cover the requested range (zero-copy for an exact match,
a cut for a containing entry, or a concatenation of adjacent entries);
a partially covered range is re-read whole and stored zero-copy: entries
reference slices of the whole read block, so both the miss path and the
insertion path perform no extra copies. Stitching around partially covering
pieces was measured to cost more in copies and page faults than re-reading.

The cache size is limited by the new setting
`apply_patch_parts_ranges_cache_max_bytes` (default 1 GiB, 0 disables it).
New profile events: `PatchRangesCacheHits`, `PatchRangesCachePartialHits`,
`PatchRangesCacheMisses`, `PatchRangesCacheEvictedBytes`.

On a table with several original parts covering the same range of the sorting
key, patch rows read drop by up to 89% and queries reading patched columns get
up to 15-18% faster, with no regression when there is nothing to reuse.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4a6e200]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
03826_calculate_subcolumn_size_during_merge_tree_read FAIL cidb
03312_squashing_with_low_card_mem_usage FAIL cidb
04647_no_blocks_marshalling_for_local_shard_plan FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Segmentation fault (STID: 2561-3810) FAIL cidb

AI Review

Summary

This PR adds a cache for ranges read from patch parts in MergeOnKey mode, wires it through MergeTree read pools, and adds coverage for the new behavior. The cache shape is reasonable, but the implementation still falls short of the PR's query-level contract, and two of the new system.events counters describe behavior that the code does not actually report.

PR Metadata

Changelog category: Performance Improvement matches the change.

Changelog entry: required, but the current TODO... placeholder does not satisfy the template or the changelog quality bar. Exact replacement text:

Added a cache for ranges read from patch parts in `MergeOnKey` lightweight updates to avoid repeated patch-part reads when several parts in one table scan need the same patch ranges.
Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeReadPoolBase.cpp:43-53] The new cache is budgeted per MergeTreeReadPoolBase, not per query. Any query that instantiates several MergeTree read pools (for example multiple patched tables, split parallel-replica streams, or other sibling readers) gets several independent query_limit / 4 caches, so this optional optimization can still consume the whole max_memory_usage budget and fail the query with MEMORY_LIMIT_EXCEEDED. Suggested fix: create one query-scoped limiter/cache and share it across all read pools instead of constructing a fresh cache in each pool.

💡 Nits

  • [src/Common/ProfileEvents.cpp:302] PatchRangesCachePartialHits is described as a request "partially served from the patch ranges cache", but PatchRangesCache::getOrRead explicitly discards partial coverage and re-reads the whole range. Suggested fix: rename or reword it to "partial coverage found in the cache" (or similar).
  • [src/Common/ProfileEvents.cpp:304; src/Storages/MergeTree/PatchParts/PatchRangesCache.cpp:197-198,267-268] PatchRangesCacheEvictedBytes overstates what was really freed. Each cache gap is charged with the full read_block size, so evicting several entries that share one read_block can report multiple times the actual reclaimed memory. Suggested fix: either track unique block ownership for the metric or rename/reword it so it clearly reports charged/accounted bytes rather than physical bytes released.
Final Verdict

Changes requested: the cache still is not query-scoped, and the new cache metrics currently over-promise what they measure.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 234/246 (95.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 18, 2026
Blocks in `PatchRangesCache` are retained for the lifetime of the reading
pipeline and are accounted in the memory tracker of the query. With the default
budget of 1 GiB it could take a large part of the memory budget of the query:
`03100_lwu_31_merge_memory_usage` (a patch that covers all rows of the only
original part, `max_memory_usage = '100M'`) started to fail with
`MEMORY_LIMIT_EXCEEDED`, because the peak memory grew from 54 MiB to ~190 MiB.

The cache is only an optimization, so limit its size additionally by a quarter
of the memory limit of the query. Queries with large or absent memory limits are
not affected, and for queries with small limits the cache degrades gracefully,
because a miss is zero-copy: on the shape of the test the peak memory is 57 MiB
now, and on a shape where the cache wins (a sparse patch, several read tasks
requesting the same merged patch ranges) it still serves 69 of 118 requests
from the cache with a limit of 100 MiB, and all of them without a limit.

Note that the number of original parts is not a usable signal for enabling the
cache: reuse comes from the sparsity of a patch part (many read tasks of one
original part are mapped to the same merged range of the patch part), so a
single original part with a sparse patch part still gets 105 hits per query and
reads 71% fewer patch rows.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115297&sha=309f912e5009f3922a0091090b7452c7fd01dda0&name_0=PR&name_1=Fast%20test
Pull request: ClickHouse#115297

Co-Authored-By: Claude Opus 5 <[email protected]>
{
UInt64 max_bytes = context->getSettingsRef()[Setting::apply_patch_parts_ranges_cache_max_bytes];

if (auto memory_limit = getCurrentQueryHardLimit())

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.

createPatchRangesCache runs once per MergeTreeReadPoolBase, not once per query. Clamping each instance to query_limit / 4 therefore does not bound the query-wide cache footprint: a plan that reads several patched tables (or otherwise creates several read pools) can still spend the whole max_memory_usage on this optional cache alone and fail with MEMORY_LIMIT_EXCEEDED. Since the cache is only an optimization, its budget needs to be coordinated at query scope (shared limiter / shared cache), not applied independently per pool.

M(PatchesReadUncompressedBytes, "Total number of uncompressed bytes read from patch parts", ValueType::Number) \
M(PatchesJoinRowsAddedToHashTable, "Total number of rows added to hash tables when applying patch parts with Join mode", ValueType::Number) \
M(PatchRangesCacheHits, "Number of range read requests to patch parts (MergeOnKey mode) fully served from the patch ranges cache", ValueType::Number) \
M(PatchRangesCachePartialHits, "Number of range read requests to patch parts (MergeOnKey mode) partially served from the patch ranges cache", ValueType::Number) \

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.

PatchRangesCachePartialHits is not actually a request that was "partially served from the cache". PatchRangesCache::getOrRead explicitly discards partial coverage and re-reads the whole range; this flag only changes which counter is incremented. The counter is still useful, but the current description will mislead anyone reading system.events or dashboards into thinking some rows came from cache. Please rename or reword it to "partial coverage found in the cache" (or similar).

Four findings in `PatchRangesCache`:
- `cppcoreguidelines-pro-type-member-init` for `LRUItem::begin_mark`,
  `Entry::range` and `Piece::covered`. `MarkRange` has a defaulted default
  constructor over two raw `size_t`, so such members are indeterminate until
  they are assigned.
- `clang-analyzer-deadcode.DeadStores` for `has_cached_pieces` in the branch
  that re-reads the whole range on partial coverage: nothing reads the variable
  after that branch, because the code downstream uses `missing_ranges` and
  `had_partial_coverage`. Drop the store and move the variable into the scope
  of the lock, where it is used.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115297&sha=71d2a5a215c1ed52d88ad6719da524d15fa7923c&name_0=PR&name_1=Build%20%28arm_tidy%29
Pull request: ClickHouse#115297

Co-Authored-By: Claude Opus 5 <[email protected]>
M(PatchRangesCacheHits, "Number of range read requests to patch parts (MergeOnKey mode) fully served from the patch ranges cache", ValueType::Number) \
M(PatchRangesCachePartialHits, "Number of range read requests to patch parts (MergeOnKey mode) partially served from the patch ranges cache", ValueType::Number) \
M(PatchRangesCacheMisses, "Number of range read requests to patch parts (MergeOnKey mode) not served from the patch ranges cache", ValueType::Number) \
M(PatchRangesCacheEvictedBytes, "Bytes evicted from the patch ranges cache", ValueType::Bytes) \

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.

PatchRangesCacheEvictedBytes is not measuring physical bytes reclaimed from the cache. Each gap entry stores a reference to the whole read_block, and insertPieces charges every one of those entries with the full read_block.allocatedBytes(), so evicting N entries from one read can report N times the actual freed memory (or report bytes even while sibling entries still keep the block alive). Please either track unique block ownership for this metric or rename/reword the event so system.events makes it clear that this is "charged bytes evicted", not real memory released.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4a6e20090 with master 5a8f6e70a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of fbf131e38; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 701.98 MiB 698.99 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

17 object files changed (+182.21 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/PatchRangesCache.cpp.o new 141.21 KiB +141.21 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/MergeTreePatchReader.cpp.o 252.38 KiB 280.36 KiB +27.98 KiB (+11.09%)

737 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

131 translation units recompiled, 1380 s compile time in total, 130 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@xoelop

xoelop commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

A production data point for this, in case it helps prioritise it. On Cloud 26.8.1.654, an ORDER BY … LIMIT 25 read over ~50 wide columns of a ~234M-row table with 16 active patch parts (MergeOnKey and Join) spends ~27 s in ReadPatchesMicroseconds with apply_patch_parts = 1, against ~2 s applying them (ApplyPatchesMicroseconds + BuildPatchesJoinMicroseconds + AnalyzePatchRangesMicroseconds), out of ~125 s CPU in total. The rest is the eager materialization covered in #116120. Full numbers there.

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-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants