Skip to content

Query cache on disk, backed by the filesystem cache - #115382

Merged
alexey-milovidov merged 68 commits into
masterfrom
query-cache-on-disk
Oct 7, 2026
Merged

alexey-milovidov merged 68 commits into
masterfrom
query-cache-on-disk

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Closes: #115361

The query cache can now additionally store its entries on disk, backed by a preconfigured filesystem cache (an entry of the filesystem_caches section of the server configuration), selected per query with the new setting query_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:

  • The entries are ordinary filesystem cache entries, indistinguishable from other data in the same filesystem cache: 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 itself. The keys are hashed with a salt so that they cannot intersect with other keys in the filesystem cache.
  • No extra in-memory state is kept: all metadata needed to validate an entry (TTL, user id, roles, the shared flag) is serialized into the entry itself, followed by the result payload in Native format, compressed with the codec from the new setting query_cache_on_disk_codec (default ZSTD(3); reading is independent of the setting because the compressed frames are self-describing).
  • The on-disk cache works independently of the in-memory cache and can separately be enabled for reads and/or writes with the new settings enable_reads_from_query_cache_on_disk and enable_writes_to_query_cache_on_disk (both true by default, activated by setting query_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.
  • A stale (expired TTL), partially evicted, corrupt, or inaccessible (another user's non-shared) entry is treated as a cache miss; stale entries are overwritten on the next write.
  • Introspection of the on-disk entries in system.query_cache is out of scope, per the issue. New profile events: QueryCacheOnDiskHits, QueryCacheOnDiskMisses, QueryCacheOnDiskReadBytes, QueryCacheOnDiskWrittenBytes.

Tests: 05019_query_cache_on_disk_local proves persistence across process restarts (separate clickhouse-local invocations sharing one filesystem cache directory, including a cached non-deterministic result, TTL expiry, and disabled reads); 05020_query_cache_on_disk covers the server path with user isolation, sharing via query_cache_share_between_users, and error cases (unknown cache name, invalid codec).

Changelog category (leave one):

  • New Feature

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 settings query_cache_on_disk_codec, enable_writes_to_query_cache_on_disk, and enable_reads_from_query_cache_on_disk. Closes #115361.


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

Version info

  • Merged into: 26.10.1.1717-master (included in 26.10 and later)

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

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d98ed01]

Summary: ✅


AI Review

Summary

This 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
  • ⚠️ Majors
    • [src/Interpreters/Cache/QueryResultCacheOnDisk.cpp:791] The on-disk read path deletes the cache key on every exception, not just on proven corruption. Because cache hits eagerly materialize the whole result in memory, a valid entry can fail here with MEMORY_LIMIT_EXCEEDED / CANNOT_ALLOCATE_MEMORY (or another transient read-side failure) even though the original query can still succeed streaming. One low-memory probe then evicts the shared cache entry for everyone instead of treating this lookup as a miss.
    • Suggested fix: keep the existing eager removal for checksum / format / parse corruption, but do not delete the key on resource-limit or transient I/O exceptions.
Tests
  • ⚠️ Add a focused regression where an entry is written under generous limits, then a read is forced to fail on the cache-hit path because of a tighter memory budget (or equivalent injected allocation failure), and verify that the lookup falls back to a miss without deleting the on-disk entry; a later read with normal limits should still hit.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: stop treating every read-side exception as proof that the cached entry is corrupt; only delete the on-disk key for exceptions that prove the serialized entry itself is bad.

LLVM Coverage Report

Measured on commit d98ed01.

Metric Baseline Current Δ
Lines 88.20% 88.30% +0.10%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 606/654 (92.66%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 19, 2026
thevar1able and others added 5 commits August 19, 2026 03:51
`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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

12 object files changed (+298.18 KiB total), 1 added.

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%)

Job report

@rschu1ze rschu1ze mentioned this pull request Aug 19, 2026
1 task
…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.
@mintlify

mintlify Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 6, 2026, 11:54 PM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 04070_url_base_setting leaves table 04070_url_base_setting_test_1_url_nc_creds (URL engine) whose named collection was dropped (NAMED_COLLECTION_DOESNT_EXIST during metadata loading) - the same pattern as #123636 fixed for MongoDB. Related: #112805

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #112805.

What happened in this run (clickhouse-server.stress.log, 17:04:47):

  1. The stress harness ignored DROP TABLE IF EXISTS 04070_url_base_setting_test_1_url_nc_creds (InterpreterDropQuery: Ignore DROP TABLE query for table test_1.04070_url_base_setting_test_1_url_nc_creds).
  2. The AST fuzzer replayed it as DETACH TABLE IF EXISTS test_1.04070_url_base_setting_test_1_url_nc_creds (Counting detached table ...), so the table was detached with its metadata file kept.
  3. DROP NAMED COLLECTION IF EXISTS 04070_url_base_setting_test_1_nc_creds then succeeded: a detached table is not in DatabaseCatalog, so InterpreterDropNamedCollectionQuery treats its dependency as a leftover of a failed CREATE and removes it.
  4. At the restart the table is attached again from its metadata and fails with NAMED_COLLECTION_DOESNT_EXIST.

Unlike the MongoDB case of #123636, the URL engine already registers the dependency (NamedCollectionFactory: Adding dependency: collection=04070_url_base_setting_test_1_nc_creds, table=test_1.04070_url_base_setting_test_1_url_nc_creds at CREATE); the hole is the plain DETACH path. It reproduces on current master without the test:

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: 669

This is the first case of 04660_drop_named_collection_detached_table in #112805, which expects NAMED_COLLECTION_IS_USED there and passes on its head (Bugfix validation OK, flaky checks 50/50), so I am not opening a separate PR. #116768 is not involved: no DROP of this table actually ran.

thevar1able and others added 5 commits October 6, 2026 18:50
- 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]>
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, noted that the Stress test (amd_debug) restart failure (URL table detached, then its named collection dropped) is handled by #112805 and is unrelated to this PR.

{
/// 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 2c6c359 Oct 7, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the query-cache-on-disk branch October 7, 2026 09:42
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @thevar1able — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. labels Nov 22, 2026

This branch was successfully deployed

1 active deployment
staging - docs — d98ed012 Deployed Oct 6, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-feature Pull request with new product feature 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.

Query cache on disk (2)

5 participants