Skip to content

SLRU filesystem cache: let the probationary queue use the protected queue's unused capacity - #133195

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:slru-probationary-borrows-unused-protected
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:slru-probationary-borrows-unused-protected

Conversation

@groeneai

@groeneai groeneai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #132906

Changelog category (leave one):

  • Performance Improvement

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

The SLRU filesystem cache policy (the default) now lets new file segments use the part of the cache that the protected queue does not use yet. Before, a working set larger than the probationary queue (40% of max_size by default) evicted itself before it was read again, even when the cache was mostly empty.

Description

New file segments only go to the probationary queue, and it evicts against its own share even while the protected queue is empty, so a working set between 40% and 100% of the cache is read from the remote storage on every repetition (ClickBench's datalake entries use cache_policy: LRU for this reason). Analysis and original patch: @ snelheidai, #132906.

Probationary now borrows protected's unused limit under the cache state lock, so the two limits still add up to the shares and the per-queue limits stay enforced. A promotion takes the borrowed capacity back and downgrades only the rest; a partially downloaded segment that grows in protected takes it back too (probationary makes room in the same reservation, which also reserves the capacity against concurrent take-backs). Dynamic resize keeps the borrowed capacity, and the queue shares (and the data/system parts of a split cache) now add up to the total. A full protected queue lends nothing, so it keeps today's protection; a scan read twice now stays cached and competes for protected (reporter: two more runs of an 8 GB scan re-read 2 MB of a 371 MB hot set once). SLRU_OVERCOMMIT keeps the fixed split: its per-client copies share sizes but not limits.

Reporter's ClickBench over S3 Parquet, 8 GB cache: Q31 -80%, Q21 -72%, Q22 -30%, controls within 3%. Locally (debug builds, 600 MB scan over a 1 GiB cache, 20 ms per object read): hot reads 12.2 s -> 0.18 s, 600 MB -> 0 bytes from storage.

Tests: gtests for each part, 05832_filesystem_cache_slru_working_set_above_probationary (fails on master); 05234 encoded the old behaviour. No performance test: the performance job removes the local disks and both of its servers share one cache directory.


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

groeneai and others added 8 commits November 20, 2026 00:28
…acity

Patch from the analysis in ClickHouse#132906 (@snelheidai), applied verbatim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…motion

On top of the borrowing from ClickHouse#132906:

- Lending is opt-in per priority: only the plain SLRU policy enables it.
  Copies (`copy()`, used by the per-client SLRU_OVERCOMMIT priorities)
  share the queue sizes but not the limits, so moving limits in one copy
  would break the size invariant of another.
- Dynamic resize keeps the capacity which probationary borrows instead of
  resetting both queues to their shares: growing the cache no longer
  evicts borrowed data, and restoring the previous limits after a failed
  eviction always succeeds.
- A promoted partially downloaded segment which grows in protected takes
  lent capacity back: probationary makes room for it in the same
  reservation, a hold on the SLRU reserves that capacity against
  concurrent take-backs, and the limit moves in `incrementSize`, where
  the reservation's holds are released and its evicted entries are
  invalidated.
- A promotion takes back min(size, lent) and downgrades only the rest.
- The two queue shares (and the data and system parts of a split cache)
  add up to the total: probationary = total - protected, so a filled
  cache never exceeds its total limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
05832 reads 6.4 MB through a 10 MiB SLRU cache with a 4 MiB probationary
queue twice: the first read evicts nothing and the second one reads
everything from the cache. 05234 encoded the old behaviour (an entry
bigger than the probationary queue was not stored); it is stored and
served now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… check; docs for borrowing

05832: `prewarm_mark_cache` and `prewarm_primary_key_cache` are randomized
MergeTree settings. With prewarm on, the INSERT puts the part's marks into
the server mark cache, so read 1 never reads the marks files through the
filesystem cache; if the marks leave the mark cache before read 2 (a parallel
`SYSTEM CLEAR MARK CACHE`), read 2 reads them from the source. Measured on the
fix server: with prewarm on and a mark cache clear between the reads, read 2
reads 538 bytes from the source; with prewarm off, 0.

05234: keep the "not stored, leaves no file segments behind" check for an
SLRU cache, now with an entry bigger than the whole cache.

Docs: `slru_size_ratio` notes that new data can use the unused part of the
protected share.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ratio_of_defaults_for_sparse_serialization` is randomized and is 0 in about 30% of
runs. Both columns then become Sparse, the first read re-reads segments within the
same query, the re-read promotes them to the protected queue, and master passes the
test without the fix. Pin the setting to 1 so the columns stay Full.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`static_cast<double>(total)` rounds up for about half of the limits above
2^53, so at a ratio of 1 the rounded share was `total + 1` and its
complement `total - share` wrapped around to an unbounded queue; clamping
the share to `total` keeps such a config rejected, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tion

`std::lround` overflows `long` for limits above 2^63 and `static_cast<double>`
rounds limits above 2^53 both ways, so the share is rounded and bounded in
`double` before the conversion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove comments that restate the code next to them, shorten the ones about lending and take-back to one line each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit cc0a0d0.

Approve preview

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 5 findings over 5 rounds) plus my own review (4 findings; one of them also raised by the model).

# Sev Finding Verdict Evidence / action
1 ❌ Complementary share rounding rejects a previously accepted config (max_size 5, slru_size_ratio 0.5, max_file_segment_size 3) (FileCacheSettings.cpp:328) DISAGREE Such a config was accepted, not valid: both shares rounded up, so the limits summed to max_size + 1 (Cache limits violated. total size 6/5). Only for an exact half share; every SLRU config in the repo keeps its shares.
2 ⚠️ 05832 depends on prewarm_mark_cache, which is randomized: marks prewarmed at INSERT bypass the filesystem cache, and a parallel SYSTEM CLEAR MARK CACHE makes the second read hit the source AGREE, fixed @ 57d3075 table pins prewarm_mark_cache = 0, prewarm_primary_key_cache = 0
3 ⚠️ 05832 leaves ratio_of_defaults_for_sparse_serialization randomized: at 0 the columns are sparse, the first read re-reads and promotes segments, and master passes the test (4 of 20 runs) AGREE, fixed @ f319f1d table pins ratio_of_defaults_for_sparse_serialization = 1: master fails 40/40, the fix passes 30/30
4 💡 05234 lost its only check that a non-fitting entry leaves no file segments behind AGREE, fixed @ 57d3075 section for an entry bigger than the whole SLRU cache
5 💡 Docs for slru_size_ratio describe a fixed split AGREE, fixed @ 57d3075 one clause in storing-data.mdx
6 ⚠️ The complementary share total - getRatio(total, ratio) underflows when a limit above 2^53 rounds up in double and the ratio is 1 (SLRUFileCachePriority.cpp:50, SplitFileCachePriority.cpp:49, FileCacheSettings.cpp:328) AGREE, fixed @ 09eee3d one FileCacheUtils::getRatio for all three, bounded by total (as SLRUCachePolicy::calculateMaxProtectedValue); boundary asserts in SLRUSharesAddUpToTotal
7 ⚠️ Bounding after std::lround is too late: it overflows long for limits above 2^63 (getRatio(SIZE_MAX, 1.0) = 2^63), and limits above 2^53 also round down (2^53 + 1 at ratio 1 left 1 for probationary) AGREE, fixed @ 09eee3d the share is rounded and compared in double before the conversion; FileCacheUtils.GetRatio covers 2^53 + 1, 2^53 + 3 and SIZE_MAX
8 💡 A split cache with LRU parts, max_elements 1 and split_cache_ratio 0.5 now gets a zero data part, which LRU reads as unlimited (master: 1 + 1) (SplitFileCachePriority.cpp:44) AGREE, not changed (raised as ❌) Only at an exact half-unit tie with a total of at most 500: 11 of 100M checked configs. With 1 element, master already has an unlimited part at every other ratio (the default 0.1 included). A zero SLRU share is rejected at startup.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261120-095301

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: 05832_filesystem_cache_slru_working_set_above_probationary fails 20/20 randomized runs on master (the first read evicts, the second reads from storage). Local scan of 600 MB through a 1 GiB SLRU cache re-reads all 600 MB from storage on every hot try.
b Root cause explained? Yes: every new segment goes to the probationary queue, which evicts against its own share (40% by default) while the protected queue fills only by promotions, so a working set above that share evicts itself before its second read.
c Fix matches root cause? Yes: the probationary queue borrows the protected queue's unused limit where it would evict; the limits still add up to the shares and each queue stays within its limit.
d Test intent preserved / new tests added? Yes: 6 new gtests (opt-in, shares, partial take-back on promotion, growth take-back, concurrent take-back, resize) and the reporter's gtest; new stateless 05832; 05234 asserted the old behaviour and asserts the new one.
e Both directions demonstrated? Yes: 05832 fails on master 20/20 and passes 50/50 on the fix; 05234 shows the exact inverse diff on master; every new gtest fails when the part it covers is removed (e.g. Cache limits violated. total size 6/5 without the share rounding).
f Fix is general across code paths? Yes: every SLRU path that adds, grows, promotes, downgrades, restores or resizes entries handles the borrowed capacity; lending is off for SLRU_OVERCOMMIT copies, which share sizes but not limits; the split cache rounding is fixed too.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: ratios 0.5 and 0.6, a 5-byte cache with exact-half rounding, the elements limit, split parts, partially downloaded segments; all SLRU configs in the repo keep their shares.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, no format, nothing persisted, startup loading unchanged; only the intended behaviour changes.
i Invariants and contracts preserved? Yes: each sub-queue stays within its limit, the limits add up to the shares, protected never exceeds its share, limits move only under the cache state lock, and a pending take-back is released on success and on every failure; concurrency gtests 200/200, integration test_filesystem_cache and test_filesystem_split_cache 30 passed.

Session id: cron:clickhouse-impl-slot-40:20261120-002700

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cc0a0d0]

Summary: ✅


AI Review

Summary

The PR lets the SLRU probationary queue borrow unused protected capacity and reclaim it during promotion or protected-entry growth. It also preserves borrowed capacity during resizing and makes queue shares sum to the configured totals. The focused regression tests and reported before/after measurements support the change. No actionable findings at cc0a0d0c390e7a70936ffb48520afaf6e1f16ab6.

Missing context / blind spots
  • ⚠️ Tests were not rerun locally because this workspace has no ClickHouse binary or build directory. Available CI reports show no failures, but most full-suite jobs have not produced results yet; completed CI runs of the affected cache tests would provide independent runtime confirmation.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors labels Nov 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Nov 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cc0a0d0c3 with master eb7319d04 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

12 translation units recompiled, 29 s compile time in total, 12 of them have a recent master baseline.

Job report

@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=13 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 31e0a765-1dea-48e0-8f34-b500d39dfef1
  • MIRAI run: 34bfdd35-93f7-4b3f-8400-50d24ee975ad
  • PR check IDs:
    • clickbench_468349_1795176671
    • clickbench_468368_1795176671
    • tpch_adapted_1_official_468391_1795176671
    • tpch_adapted_1_official_468412_1795176671

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

can be tested Allows running workflows for external contributors comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SLRU filesystem cache: a working set above 40% of max_size is never cached, even when the cache is mostly empty

1 participant