Skip to content

Optimize userspace page cache hot path: precompute hash, avoid per-block string copies - #100300

Merged
alexey-milovidov merged 53 commits into
masterfrom
page-cache-optimizations
May 6, 2026
Merged

alexey-milovidov merged 53 commits into
masterfrom
page-cache-optimizations

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 21, 2026 •

Copy link
Copy Markdown
Member

In CachedInMemoryReadBufferFromFile::readBigAt, every 1 MB block required constructing a full PageCacheKey (two string copies for path and file_version) and computing SipHash over ~100 bytes of string data. For a 14.7 GB file this means ~30,000 string allocations and ~15,000 full-string hash computations per scan.

Reorder PageCacheKey::hash so path+version are hashed first and offset+size last, enabling incremental hashing via a copyable SipHash state. Add baseHash (returns partial state) and hashForBlock (finalizes with offset+size). Add PageCache overloads of getOrSet, get, and contains that accept a precomputed UInt128 hash, deferring key construction to a lazy factory that only runs on cache miss.

Three hot paths updated:

  • readBigAt: precompute base hash once, zero string allocations per block on cache hits.
  • nextImpl lookahead loop: replace PageCacheKey copy + contains with hashForBlock + hash-based contains.
  • isContentCached: use hash-based get.

https://github.com/ClickHouse/ClickBench/pull/818/changes

Changelog category (leave one):

  • Performance Improvement

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

Slightly optimize userspace page cache.

Version info

  • Merged into: 26.5.1.323

…ock string copies

In `CachedInMemoryReadBufferFromFile::readBigAt`, every 1 MB block
required constructing a full `PageCacheKey` (two string copies for path
and file_version) and computing `SipHash` over ~100 bytes of string
data. For a 14.7 GB file this means ~30,000 string allocations and
~15,000 full-string hash computations per scan.

Reorder `PageCacheKey::hash` so path+version are hashed first and
offset+size last, enabling incremental hashing via a copyable `SipHash`
state. Add `baseHash` (returns partial state) and `hashForBlock`
(finalizes with offset+size). Add `PageCache` overloads of `getOrSet`,
`get`, and `contains` that accept a precomputed `UInt128` hash,
deferring key construction to a lazy factory that only runs on cache
miss.

Three hot paths updated:
- `readBigAt`: precompute base hash once, zero string allocations per
  block on cache hits.
- `nextImpl` lookahead loop: replace `PageCacheKey` copy + `contains`
  with `hashForBlock` + hash-based `contains`.
- `isContentCached`: use hash-based `get`.

https://github.com/ClickHouse/ClickBench/pull/818/changes

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5f48170]

Summary: ✅


AI Review

Summary

This PR refactors userspace page-cache keying and adds a zero-copy fast path for Parquet prefetch reads by retaining cache-cell handles. I found one substantive issue: populateBlockRange now retains all block MappedPtrs, which can create large transient RSS growth in bypass-cache mode on cold large reads; additionally, the Changelog entry is too vague.

PR Metadata
  • ⚠️ Changelog category is correct (Performance Improvement), but the Changelog entry is too generic and does not describe concrete user-visible impact.
  • Suggested replacement:
    • Improved userspace page cache read path by reusing precomputed cache-key hash state and enabling zero-copy Parquet prefetch when data is served from a single cached block, reducing allocations and memcpy overhead on cache-heavy reads.
Findings
  • ⚠️ Majors
    • [src/IO/CachedInMemoryReadBufferFromFile.cpp:238] populateBlockRange keeps all block MappedPtrs alive until return. In read_from_page_cache_if_exists_otherwise_bypass_cache mode, cache misses create temporary detached cells, so large cold reads can retain all fetched blocks simultaneously (multi-GB transient memory amplification) instead of releasing per block.
    • Suggested fix: in bypass-cache mode, process blocks in a streaming loop (no retained vector), or explicitly std::move consumed cells out of cells in the callback path so temporary miss cells can be released immediately.
  • 💡 Nits
    • PR metadata Changelog entry should be specific and user-facing; current text (Slightly optimize userspace page cache.) is too vague.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ⚠️ Changelog entry is too vague for changelog standards
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Avoid retaining all detached miss cache cells in populateBlockRange for large bypass-cache reads.
    • Replace the Changelog entry with a specific user-facing description of the performance change.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 21, 2026
When the Parquet Prefetcher reads from a reader backed by the userspace
page cache (`CachedInMemoryReadBufferFromFile`), retain the cache cells
directly instead of copying data into the Prefetcher's own buffer.

Add `SeekableReadBuffer::readBigAtRetainCells` — a zero-copy alternative
to `readBigAt` that returns a vector of `CachedRegion` (type-erased
handle + data pointer + size). The handle is a `shared_ptr<void>` that
keeps the underlying `PageCacheCell` alive.

`CachedInMemoryReadBufferFromFile` implements this by iterating through
page-cache blocks and returning retained `MappedPtr` references. No
memcpy from cache cell to output buffer.

In the Parquet `Prefetcher::runTask`, when the reader supports
`readBigAtRetainCells`, store the cached regions in the task instead
of allocating and filling `task->buf`.

In `Prefetcher::getRangeData`, when a request fits within a single
cached region (the common case — most Parquet page reads are smaller
than the 1 MB cache block), return a span pointing directly into the
cache cell. For the rare case where a request spans multiple regions,
fall back to assembling into `task->buf`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
bool supportsReadAt() override;

std::vector<CachedRegion> readBigAtRetainCells(size_t n, size_t offset) const override;
bool supportsReadAtRetainCells() const override { return in->supportsReadAt(); }

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.

supportsReadAtRetainCells currently delegates to in->supportsReadAt, but Prefetcher::runTask may call this on multiple threads while other threads are already doing readBigAt on the same underlying buffer.

SeekableReadBuffer explicitly documents that readBigAt must not run in parallel with other methods such as supportsReadAt. Calling supportsReadAt here can therefore introduce a data race / undefined behavior in concurrent prefetch.

Since determineReadModeAndFileSize already proved random-read capability up front, this override should be a cheap constant (return true) or use a precomputed immutable flag captured at construction time, not call through to in on every task.

`MemoryWorker` was only started in `clickhouse-server` but not in
`clickhouse-local`. This caused three problems:

1. The userspace page cache stayed stuck at `page_cache_min_size`
   (100 MiB by default) and never grew to `page_cache_max_size`,
   because `PageCache::autoResize` — which adjusts the cache size
   based on available memory — was never called. The result was severe
   cache thrashing: blocks evicted immediately after fetching, turning
   every "hot" run into a cold run with full S3 re-downloads.

2. RSS was never reported to the global `MemoryTracker`, so memory
   tracking in `clickhouse-local` was less accurate.

3. Jemalloc dirty pages were never purged under memory pressure.

Start `MemoryWorker` unconditionally (not only when page cache is
enabled), matching `clickhouse-server` behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov force-pushed the page-cache-optimizations branch from 62111e2 to b3db878 Compare March 21, 2026 23:13
Previously, `CachedInMemoryReadBufferFromFile::readBigAt` issued one
HTTP request per 1 MB cache block on a cold read. For a 14.7 GB file
this meant ~15,000 separate S3 GET requests on the first scan — each
with its own TCP round-trip and TLS overhead.

Restructure the read into two phases:

1. Probe the cache for all blocks in the requested range.
2. Group consecutive misses into contiguous ranges and fetch each group
   with a single `in->readBigAt` call, then distribute the response
   into individual cache cells.

This reduces the number of S3 requests from one-per-block to
one-per-contiguous-miss-run (typically one per `readBigAt` call on a
cold cache). On a hot cache the probe finds all hits and no fetches
are made.

Measured cold-run improvement (14.7 GB S3 Parquet):

  Q02: 0.904s → 0.719s (1.3x faster)
  Q20: 4.249s → 2.873s (1.5x faster)
  Q33: 4.627s → 3.074s (1.5x faster)

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

while (offset + bytes_copied < end_offset)
size_t first_block_start = offset / block_size * block_size;
size_t num_blocks = (end_offset - first_block_start + block_size - 1) / block_size;

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.

populateBlockRange now computes num_blocks as (end_offset - first_block_start + block_size - 1) / block_size without guarding offset >= file_size. For readBigAt, callers are allowed to pass offset past EOF (the contract says it may return 0), and in that case first_block_start > end_offset, so the subtraction underflows and can try to allocate a huge cells vector.

Please add an early return before computing block geometry, e.g. if (n == 0 || offset >= file_size.value()) return {}; in populateBlockRange (and let readBigAt/readBigAtRetainCells handle empty result as 0/empty).

alexey-milovidov and others added 2 commits March 22, 2026 10:30
…eadAtRetainCells`

- Add early return in `populateBlockRange` when `n == 0` or `offset >= file_size`
  to prevent unsigned underflow in block count computation that could cause
  a huge allocation attempt.

- Precompute `in->supportsReadAt()` in the constructor to avoid calling it
  from multiple threads concurrently with `readBigAt`.

#100300 (comment)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits March 22, 2026 19:30
`getRangeData` could be called concurrently by multiple consumer threads
for different requests pointing to the same task. When a request spanned
multiple cache blocks, the lazy initialization of `task->buf` (resize +
memcpy) was racy — multiple threads could observe `task->buf.empty()`
simultaneously and write concurrently.

Fix: pre-assemble `task->buf` in `runTask` (single-threaded producer)
when `cached_regions` has more than one element. The consumer side now
only reads from the already-populated buffer.

#100300 (comment)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review March 24, 2026 20:33
size_t range_size = range_end - range_start;

/// Fetch the entire miss range in one request.
PODArray<char> buf(range_size);

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.

⚠️ populateBlockRange allocates a temporary PODArray<char> buf(range_size) for each miss run and then copies that buffer again into cache cells. On cold scans, range_size can become very large (up to the full requested range), so this introduces a large transient allocation plus double memcpy and can create memory spikes under parallel reads.

Please stream directly into target cache cells (or chunk the miss run) instead of materializing the whole miss range in one temporary buffer.

alexey-milovidov and others added 3 commits March 26, 2026 22:47
…in `populateBlockRange`

For isolated cache misses (the common case), read directly into the
cache cell instead of allocating a `PODArray` temporary buffer and
copying. This eliminates one allocation and one memcpy per single-block
miss. Multi-block coalesced misses still use the temporary buffer to
preserve the benefit of a single coalesced read request.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
return {};

size_t block_size = settings.page_cache_block_size;
size_t end_offset = std::min(offset + n, file_size.value());

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.

end_offset is computed as std::min(offset + n, file_size.value()), but offset + n can overflow size_t. If that happens, end_offset may wrap below first_block_start, and num_blocks underflows to a huge value, leading to a massive allocation attempt in cells.

Please compute the end offset without overflowing, e.g.:

size_t end_offset = file_size.value();
if (n < file_size.value() - offset)
    end_offset = offset + n;

(or equivalent saturating arithmetic).

alexey-milovidov and others added 8 commits March 28, 2026 22:37
- Make `supportsReadAtRetainCells` return constant `true` instead of
  delegating to `in->supportsReadAt`, which is not thread-safe for
  concurrent access from `Prefetcher` tasks.

- Add early return in `populateBlockRange`, `readBigAt`, and
  `readBigAtRetainCells` for n == 0 or offset >= file_size to prevent
  underflow in block geometry computation.

- Fix `offset + n` overflow: use `offset + std::min(n, file_size - offset)`
  instead of `std::min(offset + n, file_size)` which can wrap size_t.

- Eliminate temporary `PODArray` buffer in `populateBlockRange`: read
  directly into cache cells via `readBigAt` instead of allocating a
  potentially huge intermediate buffer and double-copying. This avoids
  transient memory spikes under parallel reads on cold scans.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…kHouse into page-cache-optimizations

# Conflicts:
#	src/IO/CachedInMemoryReadBufferFromFile.cpp
#	src/IO/CachedInMemoryReadBufferFromFile.h
@groeneai

groeneai commented May 2, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — both test_keeper_snapshot_chunked_transfer failures here are already addressed by separate PRs. (CI flakes on this PR are unrelated to the userspace page cache changes.)

1. test_recover_from_snapshot_with_chunked_transfer[remote_disk] — kazoo.exceptions.ConnectionClosedError

Cause: the kazoo client created before stop_clickhouse(kill=True) has its session expire while the server is down (default kazoo session timeout < kill+restart window under CI load); kazoo cannot resume an expired session, so the next op throws ConnectionClosedError.

Fixed by PR #103767 — merged 2026-05-01T09:15:17Z (commit 1ffba8f9). Re-creates the kazoo client after restart, matching the pattern used by the other test methods. Just needs a rebase of #100300 onto current master to pick this up.

2. test_recover_after_interrupted_transfer[remote_disk] — tmp_snapshot objects not removed from S3 on startup

Cause: after the lagging node restarts, the snapshots_queue (background serializeSnapshotToDisk) writes new tmp_snapshot_*.bin.zstd markers concurrently with the assertion. The old assertion checked all tmp_snapshot_* objects in S3, racing with these benign background flushes. The local-disk variant correctly checked only the specific interrupted file, which is why only [remote_disk] was flaky.

Fix in PR #102899 — created 2026-04-16, OPEN, mergeable, awaiting review. Records the specific interrupted tmp filenames at kill time, then polls (15 s) for those specific objects to disappear. New transient markers from background ops are ignored.

I just rebased #102899 onto current master (it predated #103767 and would have reverted that fix without a rebase) and force-pushed.

CIDB confirms #2 still hits ~30 unrelated PRs and ~6 master runs in 30 days; it's the chronic remote_disk flake. Could you nudge @kssenii on #102899? The PR has been waiting 16 days with no reviewer attached — can be tested label is set, CI is green, no review requests on the PR despite my Phase 5 comment.

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request May 4, 2026
PR ClickHouse#98377 (`Forbid Tuple element name `null` to prevent subcolumn
ambiguity`) makes the new server reject attaching any pre-existing
table whose schema contains `Tuple(null ...)`. The stress test
`01872_functions_to_subcolumns_analyzer.sql` historically created
such a table (`t_tuple_null` with `Tuple(null UInt32)`); after
upgrade, the new server logs a `BAD_ARGUMENTS` error from
`AsyncLoader::worker` while attempting to attach it. This is the
new validation working as intended, not a regression — the
table is left detached, but the error surfaces in the upgrade
check as `Error message in clickhouse-server.log (see upgrade_error_messages.txt)`.

Add the message to the upgrade-check error allowlist so that this
expected post-upgrade rejection does not fail the check.

Example failing run (as reproduced on PR ClickHouse#100300):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100300&sha=a93523dfa84eebfb7bd5b2f25596f01e2e18ab2e&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
auto cached_regions = reader->readBigAtRetainCells(task->length, task->offset);
chassert(!cached_regions.empty());

if (cached_regions.size() == 1)

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.

runTask now has two materially different execution paths (cached_regions.size() == 1 zero-copy vs > 1 copy-assemble), but this PR does not add coverage for either branch. Please add targeted tests for both cases (single-block and multi-block reads through Parquet::Prefetcher) to lock in correctness and prevent regressions in bounds/lifetime handling.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, fix "Logical error: Unexpected return type from A. Expected B. Got C (STID: 3344-4a3c)" and send a PR with the fix.

bool inject_eviction = settings.page_cache_inject_eviction;

/// Phase 1: probe cache for all blocks, record hits.
std::vector<PageCache::MappedPtr> cells(num_blocks);

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.

populateBlockRange now pre-allocates cells(num_blocks) and keeps every MappedPtr alive until the function returns. In read_from_page_cache_if_exists_otherwise_bypass_cache mode, misses are returned as temporary detached cells (temporary=true), so for a large cold read this can retain all fetched blocks at once (e.g. multi-GB extra RSS) instead of releasing each block after it is copied out.

This reintroduces a high memory-amplification path on cache misses. Please avoid retaining all detached miss cells simultaneously (for example: process blocks in a streaming loop for detached mode, or std::move consumed cells out of cells from the callback so temporary cells can be freed immediately).

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — STID 3344-4a3c root-caused and fixed in #104171.

Bug class: Type-inference asymmetry in FunctionComparison::getReturnTypeImpl. The per-element recursion that computes nullable propagation through tuple comparison is only enabled when both sides are tuples. For tuple <= string (and the symmetric form), the loop inspects only the immediate element type, so a Tuple(Nullable(...)) outer element is not detected as nullable-producing. Result type was inferred as plain UInt8 while runtime (which parses the string into a tuple value and compares element-wise) produced Nullable(UInt8), tripping the analyzer's constant-folding type-match assertion at src/Analyzer/Resolve/resolveFunction.cpp.

Minimal repro: SELECT tuple(tuple(toNullable('x'))) <= '((NULL))'; — deterministic abort.

Same root cause covers PR #100035 (the earlier hit, same family — equals(intDiv(-2, number), 255) inside a fuzzed query that constructed the same nested-tuple-vs-string shape).

Cross-PR data: the STID has hit only 2 PRs in 60 days (#100300 today, #100035 on 2026-04-20) — chronic trunk type-inference bug, not PR-caused. PR #100300's hot-path-cache change is unrelated to the assertion.

@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.70% 76.60% -0.10%

Changed lines: 49.41% (126/255) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 6, 2026
Merged via the queue into master with commit 10da751 May 6, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the page-cache-optimizations branch May 6, 2026 09:13
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 6, 2026
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request May 6, 2026
…elements

When type-inferring a comparison like `Tuple(Tuple(Nullable(String))) <= String`,
the loop in `FunctionComparison::getReturnTypeImpl` only recurses for the both-
tuples case. For `tuple <= string` (and the symmetric form), it inspects only
the immediate element type, so a `Tuple(Nullable(...))` outer element is not
detected as nullable-producing. The result type is inferred as plain `UInt8`,
but the runtime — which parses the string as a tuple value and compares
element-wise — produces `Nullable(UInt8)`. The mismatch then trips the analyzer's
constant-folding type-match assertion at `src/Analyzer/Resolve/resolveFunction.cpp`,
manifesting as STID 3344-4a3c:

    Logical error: Unexpected return type from lessOrEquals.
    Expected UInt8. Got Const(Nullable(UInt8))

Fix: when one side is `String`/`FixedString`, recursively call `func->build`
with `(element_type, string_side_type)` to compute the per-element comparison
type. This mirrors the runtime semantics and correctly propagates `Nullable`
(as well as `Dynamic`/`Variant`/`Nothing`) through arbitrarily-nested tuples.
The fix is symmetric for both `tuple <= string` and `string <= tuple`.

Minimal reproducer (crashes the unfixed server):

    SELECT tuple(tuple(toNullable('x'))) <= '((NULL))';

Same root-cause class as #1d24a248c32f (tuple comparison Nothing-type) and the
existing constant-folding fix in #c4b3d5221acf (Variant + LowCardinality NULL).

Source PR where the assertion was first caught:
ClickHouse#100300

Regression test: 04206_tuple_string_compare_nested_nullable_inference

Co-Authored-By: Claude Opus 4.7 <[email protected]>
CheSema added a commit that referenced this pull request May 11, 2026
Resolve conflicts with:
- page-cache-optimizations (#100300): PageCacheKey -> PageCacheFile,
  CachedInMemoryReadBufferFromFile constructor takes ReadSettings,
  added page_cache_max_coalesced_bytes to PageCacheSettings.
- blob-storage-log-read-operations: readObject wrappers with logging
  in Azure, HDFS, Local object storages.
- StorageObjectStorageSource: keep pipeline approach, drop master's
  imperative buffer wrapping (already handled by ReadPipeline).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
CheSema added a commit that referenced this pull request May 11, 2026
The page-cache-optimizations PR (#100300) renamed PageCacheKey to
PageCacheFile and changed CachedInMemoryReadBufferFromFile to take
ReadSettings instead of PageCacheSettings. Update ReadPipeline to
match.

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

Copy link
Copy Markdown
Member

Hello! Performance tests missing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance 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.

5 participants