Repository navigation
filecache: add reserve granularity setting - #108369
Conversation
…ntion The filesystem cache `CacheStateGuard` (state lock) is taken on every space reservation. Profiling a saturated cache showed reservations are heavily fragmented (avg ~230 KiB per `tryReserve`, only ~1.75% of reservations trigger eviction), so the state lock is dominated by the sheer rate of tiny, mostly non-evicting reservations rather than by eviction work. Add a per-cache `reserve_granularity` setting (default 4Mi). When set, `FileSegment::reserve` reserves space ahead in coarser granules (capped at the file segment range for bounded segments; growing the range for unbound segments), so subsequent `reserve` calls for the same segment are served by the existing already-reserved short-circuit without taking the state lock. The extra reserved-but-not-downloaded space is reclaimed on file segment completion via `shrinkFileSegmentToDownloadedSize`. The setting is hot-reloadable: it is applied at runtime in `applySettingsIfPossible` without a server restart. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [d02fb59] Summary: ✅
AI ReviewSummaryThis PR adds a filesystem cache Final VerdictStatus: ✅ Approve |
`add-test` had picked 31146 off a stray untracked test file, leaving a large gap that the style check flags; renumber to the next free number 04409. Also stabilize the test: use uncompressed (`CODEC(NONE)`) deterministic data, drop the unstable `count() FROM system.filesystem_cache` segment count, and assert the reduction directly from per-query `query_log` ProfileEvents['FilesystemCacheReserveAttempts']. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Unbound (`FileSegmentKind::Ephemeral`) temporary-data segments need exact space accounting. Reserving a whole granule ahead for them would account cache quota in granule-sized chunks regardless of the real temporary file size, and on a small temporary-data cache the over-reservation could exceed the limit and fail the reservation — which `WriteBufferToFileSegment` turns into a write failure (`NOT_ENOUGH_SPACE`). Restrict reserve-ahead to bounded cache segments. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The style check requires `SYSTEM FLUSH LOGS` to name the table it flushes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tion With default buffers the cache-on-write flush already covers a whole file segment, so space is reserved once per segment regardless of reserve_granularity and the test's `granule_attempts < control_attempts` assertion would not hold (verified locally: 33 == 33). Use large file segments (8Mi) with tiny compress blocks (4096) and incompressible data so that without reserve-ahead each segment is reserved many times. Locally this now yields control = 9901 vs granule = 23 reservation attempts. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`cache.lib`'s `drop_filesystem_cache` reaches the server over HTTP via curl and relies on a `system.disks` lookup that can return empty, producing spurious errors. The cache here is freshly created with a per-database unique name, so just drop it directly with `SYSTEM DROP FILESYSTEM CACHE '<name>'` and remove the `cache.lib` dependency. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add reserve_granularity to the s3_cache disk and randomize it among 1Mi/4Mi/8Mi in install.sh (same RANDOM+sed pattern used for other config values), so the stateless test suite exercises the reserve-ahead path with different granules. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The cache is freshly created with a per-database unique name, so it already starts empty and the SYSTEM DROP was a no-op. Removing it avoids the style-check rule that requires a no-parallel tag for any test containing SYSTEM DROP (the check does not distinguish a targeted drop from a server-wide one), keeping the test parallel-safe without the tag. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… column `DESCRIBE FILESYSTEM CACHE` emits one column per cache setting, so the new `reserve_granularity` setting adds a column (after `boundary_alignment`) with the default value 4194304. Insert it into the reference row. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The new default reserve_granularity (4Mi) applies to all caches, including the intentionally tiny `dynamically_resize_filesystem_cache` (max_size=2124, max_file_segment_size=100). There, reserve-ahead holds a whole segment of reserved-but-not-yet-written space during each write, lowering steady-state occupancy (2076 -> 1576 bytes locally) below the `current_size > 2000` assertion in 03032_dynamically_resize_filesystem_cache_2. Set reserve_granularity=0 for that cache so the resize test stays independent of reserve-ahead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The randomization sed was unscoped and rewrote every <reserve_granularity> in storage_conf.xml, including the intentional <reserve_granularity>0</reserve_granularity> on dynamically_resize_filesystem_cache, which would re-break 03032_dynamically_resize_filesystem_cache_2 under EXPORT_S3_STORAGE_POLICIES=1. Restrict the substitution to the <s3_cache>...</s3_cache> range. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`test_caches_with_the_same_configuration_2` failed deterministically because the `cache1`/`cache2` disks have `max_size = 1Mi` but no `reserve_granularity`, so they used the default 4Mi. Reserve-ahead then tried to reserve a whole 4Mi granule, which exceeds `max_size` and fails every reservation, leaving the cache empty (`assert '' == 'cache1\t0\ncache2\t0'`). Set `reserve_granularity = 0` for these caches to disable reserve-ahead, matching what is already done for the tiny `dynamically_resize_filesystem_cache`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Reserve-ahead (`reserve_granularity`) rounds a reservation up to a coarser granule. The surplus was meant to be reclaimed on completion, but with `reserve_granularity == boundary_alignment` (the 4Mi defaults) a sub-granule read rounds `downloaded_size` back up to the whole range in `shrinkFileSegmentToDownloadedSize`, so `result_size == range().size()` and the reclaim was skipped. The segment then kept a full granule charged against the cache for bytes that were never written, shrinking effective cache capacity for sparse/random reads. Reclaim `reserved_size` down to `downloaded_size` (returning the surplus via `queue_iterator->decrementSize`, which also decrements the `FilesystemCacheSize` metric) before the `result_size == range().size()` early return. This matches the pre-reserve-ahead behaviour where `reserved_size` ends at `downloaded_size` for partially downloaded segments. Add an integration regression test that does a sub-granule read against a cache with `reserve_granularity == boundary_alignment` and background download disabled, and checks that after the read buffer is destroyed the charged cache size equals the actually downloaded bytes rather than the rounded-up range. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`reserved_size = downloaded_size;` tried to copy-assign one `std::atomic<size_t>` to another, selecting the deleted `atomic& operator=(const atomic&)`. Use `downloaded_size.load()`, matching the surrounding code. Co-Authored-By: Claude Fable 5 <[email protected]>
The reserve_granularity reserve-ahead reserved a full granule beyond the current download offset (capped only at the file segment range). For reads known to stop early -- bounded by read_until_position -- this reserved (and could evict useful cache data for) space the reader would never fill. Add a `reserve_hint` parameter to `FileSegment::reserve`: an upper bound, counted from the current download offset, on how many more bytes will be downloaded into the segment. The reserve-ahead is now capped at the hint, so it never reserves past what the read will actually consume. The hint is always >= the genuinely needed reservation, so it never drops below it. `CachedOnDiskReadBufferFromFile` passes `read_until_position - current download offset` as the hint at both the download and predownload reservation sites. Other callers omit the hint and keep their previous behaviour. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-contention # Conflicts: # tests/config/install.sh # tests/queries/0_stateless/02344_describe_cache.reference
…ion to zero The reserve-ahead hint cap in FileSegment::reserve assumed reserve_hint is always >= the needed reservation and computed size_to_reserve = reserve_hint - already_reserved_size unconditionally. Once a previous reserve call has already reserved a full granule ahead near read_until_position, already_reserved_size can equal (or exceed) reserve_hint, so this produced size_to_reserve == 0 (or an underflow). The zero then reached FileCache::tryReserve -> LRUFileCachePriority::LRUIterator::incrementSize and tripped chassert(size), aborting the server with Logical error: 'size'. Clamp the hint subtraction to avoid underflow and floor size_to_reserve at the genuine requirement: reserve-ahead is an optimization that only ever reserves more, never less than the current write needs. CI report: #108369 (comment) Server log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/108369/01e16fcbee8ae4a436c6a47648e7cc2260986367/stateless_tests_arm_asan_ubsan_targeted/clickhouse-server.log Co-Authored-By: Claude Opus 4.8 <[email protected]>
Tighten the verbose comments around the reserve-ahead path in FileSegment::reserve, the reserve_hint doc, and the surplus reclaim in shrinkFileSegmentToDownloadedSize. No behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…plus reclaim After the reserve-ahead surplus reclaim in shrinkFileSegmentToDownloadedSize, a partially downloaded segment no longer keeps its full reservation once its holder is released: the last-holder completion shrinks it and returns the reserved-but-not-downloaded surplus to the cache. The first segment therefore ends at 3 reserved bytes (its downloaded size) rather than 8, so the total used cache size is 11, not 16. The reserved size is still 8 while the holder is alive (before the shrink), which the test continues to assert. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
📊 Cloud Performance Report 🔴 AI verdict: This PR adds the filesystem-cache reserve_granularity setting (default 4Mi reserve-ahead), changing the cache reservation hot path used whenever queries read data through the cache on a miss. That path is genuinely exercised by these benchmarks, so movement in both directions is on-topic: the improvements (ClickBench Q4/Q23/Q24/Q26, TPC-H Q16, up to -74%) line up with fewer cache-state lock acquisitions during cache population, while the regressions (ClickBench Q30/Q31, TPC-H Q4/Q7/Q8) fit reserve-ahead temporarily holding extra reserved space and raising eviction pressure. The very large TPC-H Q4 (+201%) and Q7 (+780%) deltas are confirmed by both tests and stand, but their size plus several noisy source runs mean reviewers should confirm the benchmark's cache-warmth state, since warm reads never hit the changed reservation path. clickbench🔴 2 regressed · 🟢 4 improved Flagged queries (6 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🔴 3 regressed · 🟢 1 improved Flagged queries (4 of 22)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
|
|
||
| size_to_reserve = size_to_reserve - already_reserved_size; | ||
|
|
||
| /// Reserve ahead in coarser granules to cut the rate of cache state lock acquisitions on the |
There was a problem hiding this comment.
A really obscure situation, but if we can reserve the required_size but we cannot reserve with read ahead (granule) added?
There was a problem hiding this comment.
Yes, the bot was pointing it out as well, but IMO with production cache sizes it is highly unlikely that we cannot evict 4 mb. With default file segment size of 32 mb, the best case is that for both 1mb and 4mb we evict only 1 file segment, of course in reality we sometimes handle many small files so the difference between 1mb and 4mb can be several file segments, but we also have boundary_alignment which can force us already to read up to several mega bytes more than we actually need, so it is actually the same situation - whether we should ignore boundary_alignment = 4mb if reserve fails because of that.
So my opinion is that if this situation really happens - it means the cache size is actually quite small, which means that user can adjust reserve_granularity setting for such deployments specifically.
fd13639 to
1feca1d
Compare
1feca1d to
8bcac5f
Compare
…l.sh The upgrade and bugfix-validation checks run a previous-release server against the new build's configs. `reserve_granularity` is new in 26.7, so older servers reject storage_conf.xml with `Unknown setting 'reserve_granularity'` (UNKNOWN_SETTING) and fail to start. Mirror the existing version-gating used for allow_dynamic_cache_resize and keep_free_space_eviction_threads: apply the randomized value only for servers >= 26.7, and strip the setting entirely for older ones. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108369&sha=8bcac5f59a5ddafa266f543bb9326b0c383e8fa2&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 Co-Authored-By: Claude Opus 4.8 <[email protected]>
…-contention # Conflicts: # tests/queries/0_stateless/02344_describe_cache.reference
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 84/90 (93.33%) · Uncovered code |
Pull Request is not mergeable
…ion to zero The reserve-ahead hint cap in FileSegment::reserve assumed reserve_hint is always >= the needed reservation and computed size_to_reserve = reserve_hint - already_reserved_size unconditionally. Once a previous reserve call has already reserved a full granule ahead near read_until_position, already_reserved_size can equal (or exceed) reserve_hint, so this produced size_to_reserve == 0 (or an underflow). The zero then reached FileCache::tryReserve -> LRUFileCachePriority::LRUIterator::incrementSize and tripped chassert(size), aborting the server with Logical error: 'size'. Clamp the hint subtraction to avoid underflow and floor size_to_reserve at the genuine requirement: reserve-ahead is an optimization that only ever reserves more, never less than the current write needs. CI report: ClickHouse#108369 (comment) Server log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/108369/01e16fcbee8ae4a436c6a47648e7cc2260986367/stateless_tests_arm_asan_ubsan_targeted/clickhouse-server.log Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ock-contention filecache: add reserve granularity setting
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
New filesystem cache setting reserve_granularity (default 4 MiB) reserves space ahead in coarser granules, reducing filesystem cache state-lock contention on the reservation hot path.
Version info
26.7.1.395(included in26.7and later)