Skip to content

filecache: add reserve granularity setting - #108369

Merged
kssenii merged 23 commits into
masterfrom
fs-cache-state-lock-contention
Jul 1, 2026
Merged

kssenii merged 23 commits into
masterfrom
fs-cache-state-lock-contention

Conversation

@kssenii

@kssenii kssenii commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

  • Merged into: 26.7.1.395 (included in 26.7 and later)

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d02fb59]

Summary: ✅


AI Review

Summary

This PR adds a filesystem cache reserve_granularity setting and wires it through reservation, completion-time accounting, configuration, and focused regression coverage. I did not find unresolved correctness, safety, compatibility, or test-evidence issues in the current diff; the earlier review concerns around unbound temporary segments, reserve/write byte mismatches, config compatibility, scoped config randomization, and reserve-ahead surplus reclamation are addressed in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 24, 2026
kssenii and others added 3 commits June 24, 2026 14:08
`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]>
kssenii and others added 3 commits June 24, 2026 14:38
…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]>
Comment thread tests/config/install.sh Resolved
kssenii and others added 3 commits June 24, 2026 17:55
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]>
Comment thread tests/config/install.sh Resolved
kssenii and others added 2 commits June 25, 2026 11:33
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]>
kssenii and others added 2 commits June 25, 2026 17:56
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]>
@kssenii
kssenii marked this pull request as draft June 26, 2026 09:48
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]>
@kssenii
kssenii marked this pull request as ready for review June 26, 2026 11:22
kssenii and others added 4 commits June 28, 2026 11:35
…-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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 5 regressed, 5 improved out of 38 analysed

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 30 regression 239 278 +16.5% <0.0001 cache: regression fits reserve-ahead holding extra reserved space, raising eviction pressure; source runs were noisy
🔴 31 regression 305 350 +14.8% <0.0001 cache: same reserve-ahead eviction-pressure story as Q30; noisy source measurements
🟢 4 improvement 260 217 -16.5% <0.0001 cache: fs-cache reserve-ahead cuts reservation lock overhead on cache-miss reads; improvement plausible
🟢 23 improvement 181 147 -18.8% <0.0001 cache: same reservation-path change; fewer lock acquisitions on cache-miss reads
🟢 24 improvement 209 55 -73.7% <0.0001 cache: -74% aligns with cheaper cache-population reservations; large but consistent across both tests
🟢 26 improvement 210 56 -73.3% <0.0001 cache: mirrors Q24 at -73%; cache-population reservation path got cheaper

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 4 regression 324 976 +201.2% <0.0001 cache: large delta stands (hard trust); join latency can move via reserve-ahead eviction pressure
🔴 7 regression 71 624 +779.6% <0.0001 cache: 779% delta stands; consistent with cache thrash from reserve-ahead over-reservation on this join
🔴 8 regression 167 208 +24.6% <0.0001 cache: reserve-ahead eviction pressure plausible on this join; moderate regression
🟢 16 improvement 101 50 -50.5% <0.0001 cache: -50% fits cheaper reservations on the cache-miss read path

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
  • StressHouse run: a302c508-6903-4164-a64f-7d5f1a2c6a06
  • MIRAI run: 01be77a2-62d9-4e0c-bbc9-6d0e2088872f
  • PR check IDs:
    • clickbench_622300_1782913041
    • clickbench_622306_1782913041
    • clickbench_622317_1782913041
    • tpch_adapted_1_official_622329_1782913041
    • tpch_adapted_1_official_622337_1782913041
    • tpch_adapted_1_official_622346_1782913041


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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A really obscure situation, but if we can reserve the required_size but we cannot reserve with read ahead (granule) added?

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.

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.

@kssenii
kssenii marked this pull request as draft June 29, 2026 14:10
@kssenii
kssenii force-pushed the fs-cache-state-lock-contention branch from fd13639 to 1feca1d Compare June 29, 2026 14:30
@kssenii
kssenii force-pushed the fs-cache-state-lock-contention branch from 1feca1d to 8bcac5f Compare June 29, 2026 14:55
@kssenii
kssenii marked this pull request as ready for review June 29, 2026 14:56
kssenii and others added 3 commits June 30, 2026 11:32
…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
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.50% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 84/90 (93.33%) · Uncovered code

Full report · Diff report

@kssenii
kssenii enabled auto-merge July 1, 2026 12:45
@kssenii
kssenii added this pull request to the merge queue Jul 1, 2026
auto-merge was automatically disabled July 1, 2026 22:03

Pull Request is not mergeable

Merged via the queue into master with commit 98ca33e Jul 1, 2026
343 of 344 checks passed
@kssenii
kssenii deleted the fs-cache-state-lock-contention branch July 1, 2026 22:45
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ock-contention

filecache: add reserve granularity setting
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

3 participants