Repository navigation
Query cache on disk, backed by the filesystem cache - #115382
Conversation
Entries of the query cache can additionally be stored in a preconfigured filesystem cache: this gives them more space than in memory, makes them survive server restarts, and (with a distributed filesystem cache) provides a way to share them between servers. The entries are ordinary filesystem cache entries: they are not held from deletion, they are evicted by the same rules, and there are no specific limits on their total size or number other than the limits of the filesystem cache. All metadata needed to validate an entry (TTL, access control) is serialized into the entry itself, no in-memory state is kept. New settings: `query_cache_on_disk_cache_name`, `query_cache_on_disk_codec` (default `ZSTD(3)`), `enable_writes_to_query_cache_on_disk`, `enable_reads_from_query_cache_on_disk`. Closes: #115361 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [d98ed01] Summary: ✅
AI ReviewSummaryThis PR adds an on-disk backend for the query cache, backed by a configured filesystem cache, and it now covers most of the tricky invalidation / restart / isolation cases well. I found one remaining read-path issue: a cache hit that fails for a transient resource reason can evict a valid on-disk entry, so I would not approve it yet. Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit d98ed01.
Changed lines: Changed C/C++ lines covered: 606/654 (92.66%) · Uncovered code |
`Build (arm_tidy)` reported five errors: - `max_entry_size_in_bytes_copy` and `max_entry_size_in_rows_copy` in `QueryResultCache::createWriter` were declared without an initializer (`cppcoreguidelines-init-variables`). - Three calls of `reset` on a `FileSegmentsHolderPtr` in `QueryResultCacheOnDisk` were ambiguous, because `FileSegmentsHolder` has a `reset` method of its own (`readability-ambiguous-smartptr-reset-call`). Assign `nullptr` instead, which is the idiom used elsewhere in the codebase. This is equivalent: `FileSegmentsHolder::~FileSegmentsHolder` only calls `FileSegmentsHolder::reset`. `Docs check (Mintlify)` reported five broken links in the new section of `docs/concepts/features/performance/caches/query-cache.mdx`: - The link to the filesystem cache pointed at a page that does not exist; point it at the "Using local cache" section of the storing-data page instead. - Four links pointed at anchors of the new settings on the session settings pages. Those pages are generated from `src/Core/Settings.cpp` by the documentation autogeneration workflow, so the anchors do not exist yet. Refer to the settings as inline code instead.
…red entries Two findings of the automated review of #115382. The maximum entry size was not enforced for the on-disk cache. Settings `query_cache_max_size_in_bytes` and `query_cache_max_entries` were only checked after the on-disk write, and the disk-only path returned before reaching the check, so a query result explicitly too large to be cached was still persisted on disk. Check the size and the number of rows before the on-disk write as well. The in-memory backend keeps its own check, which runs after the columnar compression and therefore accepts an entry which compression brings back under the limit. The key of an on-disk entry covered the query only, so a non-shared entry of one user occupied the slot of every other user: `containsFreshEntry` reported it as fresh, no other user could write their own entry, and the entry was then rejected on read as inaccessible - a permanent miss until the entry expired or was evicted. This mirrors the in-memory cache, whose `Key::operator==` also ignores the access context, but on disk the effect outlives a restart and, with a distributed filesystem cache, extends to every server. Include the access context (`user_id` and the current roles) in the key of a non-shared entry. A shared entry keeps a key which depends on the query only, so that every user can find it, and a reader - which cannot know whether a writer marked its entry shared - probes the key of the current user first and the shared key second. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ery cache on disk Regression tests for the two findings addressed in the previous commit, both requested by the automated review of #115382. `05021_query_cache_on_disk_size_limit` configures `query_cache.max_entry_size_in_bytes` to one byte and runs a query with `enable_writes_to_query_cache = false`, so that the query cache on disk is the only backend: nothing must be written and a second process must not find an entry. It then raises the limit to check that a result within the limit is still stored and served. `05022_query_cache_on_disk_users` has user A write a non-shared entry and checks that user B does not get it served, that user B can store its own entry, and that user B is served from that entry on the next run. It also checks that an entry written with `query_cache_share_between_users` is served to user B. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…use-local` The check of the maximum entry size added in the previous commit treated a limit of 0 as "nothing may be stored". `clickhouse-local` disables the in-memory query result cache exactly that way - `LocalServer` calls `setQueryResultCache(0, 0, 0, 0)` - while the query result cache on disk is meant to be usable there, so no entry was written on disk at all. This broke `05019_query_cache_on_disk_local`, whose first process no longer reported `QueryCacheOnDiskWrittenBytes`. Treat a limit of 0 as no limit. Report: #115382 `05021_query_cache_on_disk_size_limit` could not have caught this and could not work at all: it configured `query_cache.max_entry_size_in_bytes` for `clickhouse-local`, which never reads it, because the limit is applied from the server configuration by `updateQueryResultCacheConfiguration` only. Replace it with the integration test `test_query_cache_on_disk_size_limit`, which sets the limit in the configuration of a real server. Also restrict the `system.query_log` lookups of `05022_query_cache_on_disk_users` to the current database, as required by the `various` style check, and run both users with the test database as their current database so that the restriction holds. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…_users`
`${CLICKHOUSE_CLIENT}` already passes `--database=${CLICKHOUSE_DATABASE}`
(see `tests/queries/shell_config.sh`), so passing it again failed every
invocation with `Bad arguments: option '--database' cannot be specified more
than once`. It was also unnecessary: because the client already selects the
test database, both users run with it as their current database, which is
what the `system.query_log` lookups filter on.
Grant `SELECT` on the whole test database rather than on the single table,
so that using it as the current database cannot fail for either user.
Report: #115382
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/Cache/QueryResultCacheOnDisk.cpp.o |
new | 257.52 KiB | +257.52 KiB |
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
48 translation units recompiled, 339 s compile time in total, 47 of them have a recent master baseline.
Translation units without a recent master baseline:
src/Interpreters/Cache/QueryResultCacheOnDisk.cpp: 5.3 s
Symbol sizes
| Binary | Symbol | Master | PR | Δ |
|---|---|---|---|---|
programs/clickhouse |
ProfileEvents::global_counters_storage |
12.75 MiB | 12.81 MiB | +64.00 KiB (+0.49%) |
programs/clickhouse-keeper |
ProfileEvents::global_counters_storage |
12.75 MiB | 12.81 MiB | +64.00 KiB (+0.49%) |
…ackend `checkCanWriteQueryResultCache` treated setting `enable_writes_to_query_cache_on_disk` plus a non-empty `query_cache_on_disk_cache_name` as proof that a write backend exists. But `QueryResultCacheOnDisk::getFromSettings` can still return nullptr when the named filesystem cache exists and is not initialized yet, so in the disk-only configuration the non-deterministic function / system table `Throw` checks could fire even though no writer would ever be attached. Pass the resolved backend into the check instead of re-deriving it from the raw settings.
…tries as cheap misses Bump the on-disk entry format of the query result cache to version 2, which serializes each result chunk column by column: Sparse columns are kept by the custom serialization of the Native format, Const columns are written as an explicit flag plus their single-row data column. This removes the in-place materialization of the buffered result before the disk write, which changed what the in-memory query result cache stored (a Const result was expanded to a full column and could trip the entry size limit or consume more memory only because disk caching was enabled). Also harden reading against corrupt entries: the serialized role count is validated against the entry size and the chunk count pre-allocation is capped, so absurd counters in a malformed entry cannot force huge allocations. Since the write path probes only the fixed header, an entry with a healthy header but an unreadable body would never have been replaced until it expired - the reader now drops such entries so that the next write stores a fresh one.
… materialized before the disk write
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115382&sha=f387297c7a67440011d34dbf7fa74bb876b29a4f&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. The server cannot restart because test |
|
The fix is already in progress: #112805. What happened in this run (
Unlike the MongoDB case of #123636, the URL engine already registers the dependency ( CREATE NAMED COLLECTION nc1 AS url = 'http://localhost:1/x.csv', format = 'CSV';
CREATE TABLE t (c String) ENGINE = URL(nc1);
DETACH TABLE t;
DROP NAMED COLLECTION nc1; -- succeeds, the next start fails with Code: 669This is the first case of |
- Fix the links to the query cache page in the descriptions of the four new settings: `../query-cache.md` does not exist, the other query cache settings use `/concepts/features/performance/caches/query-cache`. - Say in the description of `query_cache_on_disk_cache_name` that `SYSTEM CLEAR QUERY CACHE` also removes the on-disk entries from the named filesystem cache, recommend a dedicated filesystem cache, and do not call a manual `SYSTEM CLEAR FILESYSTEM CACHE` an eviction rule. - Drop the claim that the entries can be shared between servers with a distributed filesystem cache: no such filesystem cache exists in the open-source server. - Say that `SYSTEM CLEAR QUERY CACHE TAG` also removes corrupt entries and entries of an incompatible format, regardless of their tag. - Say that `QueryCacheOnDiskReadBytes` and `QueryCacheOnDiskWrittenBytes` count compressed bytes, in contrast to `QueryCacheReadBytes`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… CACHE` reads only its own entries `QueryResultCacheOnDisk::clear` used to read the first bytes of every downloaded key of the filesystem cache to recognize the entries of the query cache by their magic. In a filesystem cache shared with other data (e.g. `MergeTree` parts on object storage, which can hold millions of file segments) that turns `SYSTEM CLEAR QUERY CACHE` into a long synchronous disk scan. Now `makeFileCacheKey` puts a 32-bit marker into bits 64..95 of every key of the query cache on disk, and `clear` reads the headers only of the keys which carry it. The walk over the in-memory metadata of the filesystem cache remains (proportional to the number of file segments, without disk IO); the disk IO is proportional to the number of query cache entries. The marker sits in the middle of the key, because the filesystem cache derives the directory of a key from its topmost bits and the metadata bucket from its lowest bits. The remaining 96 bits of hash keep the entries apart; a foreign key which carries the marker by chance (probability 2^-32) is still recognized as foreign by its content. The log message of `clear` reports how many file segments were scanned and how many headers were read, and the documentation recommends a filesystem cache dedicated to query results. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…many rounds `test_query_cache_on_disk` restarts the server between writing and reading the entries, and `05235_query_cache_on_disk_concurrent` runs several rounds of concurrent queries. Both relied on the default `query_cache_ttl` of 60 seconds, which a restart or the rounds can exceed on slow builds (e.g. with sanitizers), turning the expected hits into misses. Set the TTL to an hour. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…f their order The tests tracked the limit currently written in the server configuration in a module global and replaced that literal value, so they only passed when run all together and in file order: running a single test, a different order, or a rerun after a failure left the global and the configuration out of sync, and `replace_in_config` silently matched nothing. The first test additionally assumed that the limit from the initial configuration was still in effect. Now every test sets the limit it needs itself, the replacement matches any current value, and the limit is applied with `SYSTEM RELOAD CONFIG` instead of a restart, since `query_cache.max_entry_size_in_bytes` is reloadable. Also fix the docstring, which claimed that `clickhouse-local` hardcodes the limit to 0: it reads it from the configuration, the reason for an integration test is that `clickhouse-local` has no in-memory query cache to read the entry weight from. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…erver build The entries survive restarts and can be shared between servers, but a result is only valid for the build which computed it: another build may compute a different result for the same query without a change of the TCP protocol revision. Record a fingerprint of the server build (`VERSION_DESCRIBE` and `VERSION_GITHASH`) in the fixed header, and treat an entry of another build like an entry of an incompatible format: a cache miss, overwritten on the next write. The entry format version is bumped to 6, the fixed header grows to 64 bytes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in-memory only in the query cache docs Co-Authored-By: Claude Opus 5.5 <[email protected]>
| { | ||
| /// The write path probes only the fixed header, so an entry with a healthy header but an unreadable body would | ||
| /// never be replaced until it expires. Drop it here so that the next write stores a fresh entry. | ||
| file_cache->removeKeyIfExists(cache_key, FileCache::getCommonOrigin().user_id); |
There was a problem hiding this comment.
This unconditional removeKeyIfExists is too broad: it turns any read-side exception into a permanent eviction of the on-disk entry.
That is not limited to corrupt payloads. A valid entry can also throw here for transient/resource reasons — the most plausible one is MEMORY_LIMIT_EXCEEDED / CANNOT_ALLOCATE_MEMORY, because the hit path eagerly deserializes the whole cached result into RAM, while the original query may still succeed streaming. In that case one low-memory probe deletes the shared cache entry for every later query/server instead of just treating this lookup as a miss.
I think the removal needs to be restricted to proven-corrupt / structurally unreadable entries (readCheckedBody failure, malformed access metadata / Native payload, etc.). Resource-limit and transient I/O exceptions should return a miss without deleting the entry.
|
@alexey-milovidov @thevar1able — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Closes: #115361
The query cache can now additionally store its entries on disk, backed by a preconfigured filesystem cache (an entry of the
filesystem_cachessection of the server configuration), selected per query with the new settingquery_cache_on_disk_cache_name. Compared to the in-memory query cache, this gives the entries more space, makes them survive server restarts, and (with a distributed filesystem cache) provides a way to share them between servers.Design, following the RFC in the issue:
Nativeformat, compressed with the codec from the new settingquery_cache_on_disk_codec(defaultZSTD(3); reading is independent of the setting because the compressed frames are self-describing).enable_reads_from_query_cache_on_diskandenable_writes_to_query_cache_on_disk(bothtrueby default, activated by settingquery_cache_on_disk_cache_name). If both caches are enabled for reads, the lookup is attempted first from memory and only on a miss from disk. If both caches are enabled for writes, the result is written to both. A result served from memory is not written to disk.system.query_cacheis out of scope, per the issue. New profile events:QueryCacheOnDiskHits,QueryCacheOnDiskMisses,QueryCacheOnDiskReadBytes,QueryCacheOnDiskWrittenBytes.Tests:
05019_query_cache_on_disk_localproves persistence across process restarts (separateclickhouse-localinvocations sharing one filesystem cache directory, including a cached non-deterministic result, TTL expiry, and disabled reads);05020_query_cache_on_diskcovers the server path with user isolation, sharing viaquery_cache_share_between_users, and error cases (unknown cache name, invalid codec).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The query cache can now store its entries on disk, backed by a preconfigured filesystem cache: this gives the entries more space, makes them survive server restarts, and (with a distributed filesystem cache) provides a way to share them between servers. Select the filesystem cache with the new setting
query_cache_on_disk_cache_name; see also the new settingsquery_cache_on_disk_codec,enable_writes_to_query_cache_on_disk, andenable_reads_from_query_cache_on_disk. Closes #115361.Workflow [PR]
Sync PR [sync-upstream/pr/115382]
Version info
26.10.1.1717-master(included in26.10and later)