Repository navigation
Optimize userspace page cache hot path: precompute hash, avoid per-block string copies - #100300
Conversation
…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]>
|
Workflow [PR], commit [5f48170] Summary: ✅ AI ReviewSummaryThis 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: PR Metadata
Findings
ClickHouse Rules
Final Verdict
|
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(); } |
There was a problem hiding this comment.
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]>
62111e2 to
b3db878
Compare
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; |
There was a problem hiding this comment.
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).
…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]>
`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]>
| size_t range_size = range_end - range_start; | ||
|
|
||
| /// Fetch the entire miss range in one request. | ||
| PODArray<char> buf(range_size); |
There was a problem hiding this comment.
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.
…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()); |
There was a problem hiding this comment.
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).
- 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
|
@alexey-milovidov — both 1. Cause: the kazoo client created before Fixed by PR #103767 — merged 2026-05-01T09:15:17Z (commit 2. Cause: after the lagging node restarts, the 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 — |
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) |
There was a problem hiding this comment.
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.
|
@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); |
There was a problem hiding this comment.
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).
|
@alexey-milovidov — STID 3344-4a3c root-caused and fixed in #104171. Bug class: Type-inference asymmetry in Minimal repro: Same root cause covers PR #100035 (the earlier hit, same family — 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. |
LLVM Coverage Report
Changed lines: 49.41% (126/255) · Uncovered code |
…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]>
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]>
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]>
|
Hello! Performance tests missing? |
In
CachedInMemoryReadBufferFromFile::readBigAt, every 1 MB block required constructing a fullPageCacheKey(two string copies for path and file_version) and computingSipHashover ~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::hashso path+version are hashed first and offset+size last, enabling incremental hashing via a copyableSipHashstate. AddbaseHash(returns partial state) andhashForBlock(finalizes with offset+size). AddPageCacheoverloads ofgetOrSet,get, andcontainsthat accept a precomputedUInt128hash, 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.nextImpllookahead loop: replacePageCacheKeycopy +containswithhashForBlock+ hash-basedcontains.isContentCached: use hash-basedget.https://github.com/ClickHouse/ClickBench/pull/818/changes
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Slightly optimize userspace page cache.
Version info
26.5.1.323