Skip to content

Add Redis-backed query result cache with stampede protection - #98856

Open
fastio wants to merge 39 commits into
ClickHouse:masterfrom
fastio:external-query-result-cache
Open

fastio wants to merge 39 commits into
ClickHouse:masterfrom
fastio:external-query-result-cache

Conversation

@fastio

@fastio fastio commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

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

Add support for an external Redis-backed query result cache that enables cross-node cache sharing in ClickHouse clusters. When query_cache.type is set to redis,
cached query results are stored in Redis instead of in-process memory, allowing all nodes in a cluster to share cache entries. Includes anti-stampede protection via
an IN_PROGRESS lock mechanism to prevent redundant query execution across nodes.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Motivation: In multi-node ClickHouse deployments behind a load balancer, the existing in-process query cache cannot share results across nodes. Each node
independently caches and evicts entries, leading to redundant query execution and wasted resources.

Changes:

  • Refactor QueryResultCache into an abstract interface (IQueryResultCache) with a LocalQueryResultCache implementation preserving existing behavior
  • Add RemoteQueryResultCache that delegates storage to a pluggable IRemoteCacheBackend
  • Add RedisRemoteCacheBackend implementing Redis-based storage with connection pooling
  • Add QueryResultCacheFactory for config-driven cache type selection (local or redis)
  • Implement anti-stampede IN_PROGRESS lock using SET … NX PX to prevent thundering herd on cache misses
  • Graceful degradation: when Redis is unavailable, queries execute normally and cache operations are silently skipped
  • system.query_cache uses Redis SCAN to enumerate entries when the Redis backend is active
  • All existing query cache settings (use_query_cache, query_cache_ttl, query_cache_tag, query_cache_share_between_users, etc.) work identically with both
    backends

Configuration (in config.xml):

<query_cache>
    <type>redis</type>
    <redis>
        <host>redis.example.com</host>
        <port>6379</port>
        <password>secret</password>
        <db_index>0</db_index>
        <pool_size>16</pool_size>
        <lock_ttl_ms>30000</lock_ttl_ms>
        <lock_poll_interval_ms>200</lock_poll_interval_ms>
        <lock_max_wait_ms>30000</lock_max_wait_ms>
    </redis>
</query_cache>

Tests:
- Stateless tests for the abstract cache interface and local backend behavior
- Integration tests covering: single-node hit/miss, cross-node sharing, TTL expiry, clear all/by tag, user isolation, shared entries, Redis failure graceful
degradation, max entry size limits, min query runs, stampede protection, lock cleanup, non-deterministic function handling, and cross-node count consistency


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> High risk because it refactors the core query result cache into pluggable implementations and adds a Redis-backed, multi-node, lock-based write path with new serialization formats and failure-handling behavior.
> 
> **Overview**
> Adds a **Redis-backed distributed query result cache** selectable via `query_cache.type=redis`, enabling cached results to be shared across ClickHouse nodes and documenting configuration, behavior differences, and limitations.
> 
> Refactors the existing cache into an `IQueryResultCache` interface with a `LocalQueryResultCache` and a new `RemoteQueryResultCache` backed by `RedisRemoteCacheBackend`, including key/value serialization, generation-based invalidation for `SYSTEM CLEAR QUERY CACHE`, and anti-stampede `IN_PROGRESS` locking with heartbeat/timeout.
> 
> Integrates cache-type registration via `QueryResultCacheFactory` into server startup (and explicitly forces `clickhouse-local` to a no-op cache), extends Redis connection handling with retries/timeouts/pooling utilities, adds a new `EXTERNAL_QUERY_RESULT_CACHE_ERROR` code, and includes unit/integration config coverage for serialization and Redis mode.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 31635cf19cb99a2253e22732a37e1c2ad79be1af. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e8ce8a9]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: Stream A for column B with type C is not found (STID: 3190-58ae) FAIL cidb
Stress test (arm_asan_ubsan) FAIL
Sanitizer (STID: 2868-2d0a) FAIL cidb
Stress test (arm_tsan) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6444) FAIL cidb

AI Review

Summary

This PR adds a Redis-backed query result cache and closes a lot of earlier review items, but I still see one blocker on the untrusted-payload read path and two major contract regressions in the new handoff / reload behavior. I would not merge it in the current state.

Findings

❌ Blockers

  • [src/Interpreters/Cache/QueryResultCache.cpp:765, 953, 1045; src/Formats/NativeReader.cpp:191-202] The new pre-decode guards still only validate columns / rows before handing the buffer to NativeReader. NativeReader::read then allocates column-name and type strings with readStringBinary's 1 GiB default limit, so a forged Redis value can still force large allocations through huge name/type lengths before EOF. The remote read path still does not reliably degrade malformed external values to cache misses.
    Suggested fix: bound or explicitly parse the schema/block header strings before calling NativeReader::read, or use query-cache-specific capped string reads for column names/types in this path.

⚠️ Majors

  • [src/Interpreters/executeQuery.cpp:1990] hasEntryAlreadyAvailable() now makes the top-level query re-read and serve a cached result even when enable_reads_from_query_cache = 0. That violates the explicit "no reads" contract: a query can still hit the cache after contending on another node's IN_PROGRESS lock.
    Suggested fix: gate this handoff on enable_reads_from_query_cache, matching the Planner subquery path.
  • [src/Interpreters/Context.cpp:5214] SYSTEM RELOAD CONFIG only pushes size / entry / chunk limits into the existing cache object. query_cache.type and the query_cache.redis.* connection / lock_* settings are only consumed during initial construction, so backend switches or Redis reconfiguration are silently ignored until restart.
    Suggested fix: either recreate the cache when those keys change or document them as startup-only and reject live changes explicitly.
Tests
  • ⚠️ [tests/integration/test_external_query_result_cache/test.py:1082] test_reads_disabled does not cover the new top-level stampede handoff: it only checks ProfileEvents['QueryCacheHits'], while the buggy fast path uses hasCacheEntryForKey(false) and emits no hit event. A focused regression needs a contended wait on the same key with enable_reads_from_query_cache = 0.
  • ⚠️ [tests/integration/test_external_query_result_cache/test.py:785] The cancellation coverage still does not prove that a cancelled waiter / writer releases the remote lock or aborts the new wait loop. The current failure-based case can exit before any IN_PROGRESS lock is actually acquired.
Final Verdict

Changes required before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 1338/1594 (83.94%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 6, 2026
Comment thread programs/server/Server.cpp Resolved
Comment thread src/Storages/RedisCommon.cpp Resolved
Comment thread src/Storages/RedisCommon.cpp Resolved
Comment thread docs/en/operations/query-cache.md Resolved
Comment thread programs/server/Server.cpp Resolved
Comment thread src/Storages/RedisCommon.cpp Resolved
The style check failed on `test_external_query_result_cache/test.py:1169`
with `F541 [*] f-string without any placeholders`. The `assert` message
used an `f`-prefixed literal `f"Concurrent query errors:\n"` that contains
no placeholders. Removed the unnecessary `f` prefix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 19, 2026 07:34
…lt-cache

# Conflicts:
#	programs/local/LocalServer.cpp
#	programs/server/Server.cpp
…imit

`SELECT sleep(6)` fails with `TOO_SLOW` because the default
`function_sleep_max_microseconds_per_block` allows at most 3 seconds per
block. Raise the limit in the test queries so the slow query can actually
outlive `lock_ttl_ms`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98856&sha=db0a377ee1d0be9814cc68f68a943c14e982bd27&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29
PR: ClickHouse#98856

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.20% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 1184/1405 (84.27%) · Uncovered code

Full report · Diff report

…ache identity

`QueryResultCache::Key::operator==` compares only `ast_hash` and `is_subquery` - that is the
equality the in-process cache needs, where the rest of the identity holds by construction. Values
in Redis are untrusted (corruption, manual writes, namespace collisions), so a value planted under
our key with a different `tag`, `is_shared`, `user_id` or `current_user_roles` used to pass the
check. Reads now additionally require that re-encoding the stored key reproduces exactly the Redis
key that was read (`decodeAndValidate`), which binds tag, access scope and AST at once.

`hasNonStaleEntry` used to deserialize only the `Key`, so an `Entry` that no reader can decode
(malformed, oversized, too many chunks) still made every writer skip recomputation until the TTL
expired. It now runs the same bounded full-value validation as the read path.

Other fixes from the same review:

- Enforce one size/chunk contract on write and read. `isSerializedEntryStorable` rejects a write
  whose serialized blob exceeds `max_entry_size_in_bytes` or whose chunk count exceeds
  `max_entry_chunks`, so a valid write can no longer become a permanent miss.
- Recheck the data key on the re-entrant `hasNonStaleEntry` fast path. The lock is a fixed-TTL
  advisory lease: if it expired and another node stored a fresh value, `setIfValid` would have
  clobbered it, because it only validates generations.
- Make `SYSTEM CLEAR QUERY CACHE TAG ''` an exact empty-tag clear. The empty string used to double
  as the internal clear-all marker, which disabled the exact-tag filter and let the glob delete
  unrelated tags such as `:foo`. Clear-all is now an explicit flag.
- Iterate `system.query_cache` reads in client-side bounded `SCAN` batches instead of a
  cursor-to-zero loop inside one Lua script, and cap `dump` at 100000 entries. A diagnostic query
  no longer occupies Redis's single event loop for the whole traversal.
- Check `CurrentThread::checkIfNotCancelled` in `pollForResult`. The wait runs synchronously during
  writer construction, before any processor can observe cancellation, so a client disconnect or
  `KILL QUERY` used to leave the thread polling until `lock_max_wait_ms`.
- Mirror the `executeQuery` stampede handoff in the `Planner` subquery path. A waited-on subquery
  used to re-execute the original plan with `skip_insert` set, so stampede protection only delayed
  the duplicate work. Only the plan's root node is replaced, so the nodes recorded in
  `query_node_to_plan_step_mapping` for nested query nodes stay alive.

Tests: `test_lock_ttl_expiry_allows_progress` now plants the lock key ClickHouse actually derives
for the query (learned from a warm-up run) instead of a key the cache never consults; added
`test_clear_empty_tag_is_exact` and `test_unreadable_write_is_skipped`.
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner August 3, 2026 09:41
`Entry::deserializeFrom` checked the byte and row limits only after `NativeReader` had already
materialized a chunk. `NativeReader` reserves capacity for the row count declared in the block
header before reading any data, so a forged or corrupt Redis payload could allocate far beyond the
configured guard even though the check would eventually reject it.

`checkBlockBoundsBeforeRead` now peeks the block header (`columns`, `rows`) without consuming it
and rejects the block when the declared row count cannot be backed by the bytes left in the value,
or when it would overshoot the remaining `max_entry_size_in_rows` budget.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the outstanding AI-review findings (blocker + 6 majors + 3 test items) in 94d322aa5f6 and a9d003e5442, on top of a fresh master merge.

Blocker — remote-cache hit detection does not validate the full identity
Key::operator== compares only ast_hash and is_subquery, which is the equality the in-process cache needs but not enough for an external store. Reads now go through RedisRemoteCacheBackend::decodeAndValidate, which additionally requires that re-encoding the stored key reproduces exactly the Redis key that was read. That binds tag, is_shared, user_id and current_user_roles at once. hasNonStaleEntry reuses the same bounded full-value validation instead of deserializing only the Key, so an unreadable Entry no longer suppresses recomputation until the TTL expires.

One size/chunk contract on write and read
isSerializedEntryStorable rejects a write whose serialized blob exceeds max_entry_size_in_bytes or whose chunk count exceeds max_entry_chunks — the same measures the read path applies — so a valid write can no longer become a permanent miss. Separately, checkBlockBoundsBeforeRead peeks the Native block header and rejects a block whose declared row count cannot be backed by the bytes left in the value or would overshoot the row budget, before NativeReader reserves capacity for it.

Planner subquery handoff
The Planner subquery path now mirrors the executeQuery handoff: when hasEntryAlreadyAvailable is true after waiting on another node, the result is served from the cache instead of executing the built plan. Only the plan's root node is replaced (replaceNodeWithPlan), so the nodes recorded in query_node_to_plan_step_mapping for nested query nodes stay alive.

Re-entrant fast path vs lease expiry
The lock is a fixed-TTL advisory lease, so holding it locally does not mean nothing was written meanwhile. The fast path now rechecks the data key before returning false, otherwise setIfValid would clobber a newer value — it only validates generations.

SYSTEM CLEAR QUERY CACHE TAG ''
Clear-all is now an explicit flag passed into the Lua helper, so the empty string stays a first-class exact tag and the ...::*:<hash> glob no longer reaches tags such as :foo.

system.query_cache over a large cache
dump and count iterate in client-side bounded SCAN batches instead of a cursor-to-zero loop inside one Lua script, and dump is capped at 100000 entries. A diagnostic query no longer occupies Redis's single event loop for the whole traversal.

Cancellation during the stampede wait
pollForResult calls CurrentThread::checkIfNotCancelled on every iteration. The wait runs synchronously during writer construction, before any processor can observe cancellation, so a client disconnect or KILL QUERY used to leave the thread polling until lock_max_wait_ms.

Tests
test_lock_ttl_expiry_allows_progress now derives the real lock key from a warm-up run instead of planting stale_lock_test:lock, which the cache never consults. Added test_clear_empty_tag_is_exact (empty tag vs :foo) and test_unreadable_write_is_skipped (query_cache_squash_partial_results = 0 with more than max_entry_chunks tiny blocks, on a new node with max_entry_chunks = 4). Added two gtests for the pre-decode block bounds.

Verified locally: ninja clickhouse unit_tests_dbms clean, 28/28 *QueryResultCache* gtests pass, and 47/47 runnable query_cache / query_result_cache stateless tests pass against a local server (the 3 remaining failures need a cluster config, a writable access storage and a filesystem-cache storage policy, none of which the minimal local server has). The Redis integration tests could not be run here.

The previous CI red, 04627_analyzer_compatibility_final_all_joined_tables, is unrelated and was fixed by #111991, which merged shortly after this branch's last master merge — the merge in this push pulls it in.

Block header_block;
{
NativeReader reader(buf, /*server_revision=*/0);
header_block = reader.read();

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.

Key::deserializeFrom still feeds the schema block from Redis straight into NativeReader. That block is always written as header->cloneEmpty(), so a malformed value only has to change the row-count varint here: NativeReader::read accepts anything up to DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS and then calls reserve(rows) before it notices the payload is bogus (src/Formats/NativeReader.cpp:164, src/Formats/NativeReader.cpp:223).

The new checkBlockBoundsBeforeRead hardening only protects the entry blocks, not this first NativeReader call, so a planted Redis value can still force a large allocation while we are only reconstructing the key/header. Please peek the schema block header first and reject any non-zero or impossible row count before reader.read().

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.

checkSchemaBlockBoundsBeforeRead now enforces rows == 0, but it still does not bound the per-column name/type strings before NativeReader::read. A forged schema block with columns = 1, rows = 0, and a 1 GiB name/type length passes the current columns <= bytes_left / 2 check at src/Interpreters/Cache/QueryResultCache.cpp:781-785, then NativeReader::read allocates for column.name / type_name at src/Formats/NativeReader.cpp:191-202 before it notices EOF.

So the schema-block deserialize path can still allocate far beyond the cache limits.

`master` moved the documentation from the Docusaurus tree under
`docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every
file this branch edits. The edits are replayed at the new paths:

- `docs/en/operations/query-cache.md` -> `docs/concepts/features/performance/caches/query-cache.mdx`
@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Aug 10, 2026
…the row bound, and reload `max_entry_chunks`

Three findings on the untrusted-Redis-payload read path:

- `checkBlockBoundsBeforeRead` bounded a declared row count only by one bit
  per row, which is far looser than a fixed-width schema allows. It now
  derives a per-row lower bound from the entry`s header (`minNativeBytesPerRow`),
  so a small blob can no longer declare millions of rows and make
  `NativeReader::read` reserve for them.
- `Key::deserializeFrom` fed the schema block straight into `NativeReader`.
  That block is always written as `header->cloneEmpty()`, so
  `checkSchemaBlockBoundsBeforeRead` now rejects any non-zero row count, and a
  column count that the remaining bytes cannot back, before the read.
- `max_entry_chunks` was fixed at startup. It is now threaded through
  `IQueryResultCache::updateConfiguration` and `setEntrySizeLimits`, like the
  byte and row limits, so `SYSTEM RELOAD CONFIG` applies it.
The two new gtests assert the specific `TOO_LARGE_ARRAY_SIZE` rejection rather
than any exception: a plain `ATTEMPT_TO_READ_AFTER_EOF` would mean
`NativeReader` had already reserved capacity for the forged row count, which is
exactly what the guards must prevent. Both fail without them.

`test_max_entry_chunks_is_reloadable` raises the chunk budget in the config of
`node3` and reloads it, so a write that was skipped before the reload is stored
after it.
@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 10, 2026
Poco parses the empty array reply `*0` into a *null* `Array` rather than an
empty one - `Type<Array>::read` leaves `_elements` unset for a zero length - and
`Array::size` reads `Nullable::value` unconditionally, so it throws
`NullValueException`. `SCAN` returns an empty batch whenever the scanned slice
matches nothing, which is routine, so every read of `system.query_cache` against
a cache with no matching keys failed with `Code: 1000. Null value` instead of
returning no rows.

Introduced with the client-side batched `SCAN` that replaced the cursor-to-zero
Lua scripts. All array replies now go through `arraySize`, which treats a null
array as empty.

Reproduced by `test_system_query_cache_multiple_entries`,
`test_system_query_cache_stale_column` and
`test_clear_by_tag_releases_inflight_lock`, which failed on every integration
shard: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=98856&sha=a9d003e5442764958d8359f30a7df666b4a6ea5b&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%202%2F6%29
@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the three remaining AI-review findings, and fixed a real bug they led me to, on top of a fresh master merge (cd49563e2b4, f426f9b39f8, e8ce8a9fc63).

NativeReader reservation is not bounded tightly enough — checkBlockBoundsBeforeRead only required rows <= bytes_left * 8, which is one bit per row and far looser than any real schema. It now derives the bound from the entry's own header: minNativeBytesPerRow walks the types (fixed-width types contribute their exact width, Array/Map one offset, Nullable the null-map byte plus the nested value, Tuple the sum of its elements, everything else one byte) and the declared row count must be backed by rows * min_bytes_per_row bytes. With a fixed-width schema a small blob can no longer declare millions of rows.

The schema block was not covered by that hardening — Key::deserializeFrom fed the first NativeReader call straight from Redis. That block is always written as header->cloneEmpty(), so checkSchemaBlockBoundsBeforeRead now rejects any non-zero row count outright, plus a column count the remaining bytes cannot back, before reader.read.

max_entry_chunks was fixed at startup — it is now threaded through IQueryResultCache::updateConfiguration and RedisRemoteCacheBackend::setEntrySizeLimits (the member became std::atomic, like the byte and row limits), and Context::updateQueryResultCacheConfiguration reads it from the config, so SYSTEM RELOAD CONFIG applies it. LocalQueryResultCache ignores it — it never deserializes anything.

system.query_cache threw Null value — while checking the above I ran the integration suite and found the client-side batched SCAN that replaced the cursor-to-zero Lua scripts is broken for the common case. Poco parses the empty array reply *0 into a null Array rather than an empty one (Type<Array>::read leaves _elements unset for a zero length), and Array::size reads Nullable::value unconditionally. SCAN returns an empty batch whenever the scanned slice matches nothing, so every read of system.query_cache over a cache with no matching keys failed with Code: 1000. DB::Exception: Null value instead of returning no rows. All array replies now go through arraySize, which treats a null array as empty. This is what failed test_system_query_cache_multiple_entries, test_system_query_cache_stale_column and test_clear_by_tag_releases_inflight_lock on every integration shard of the previous run.

Tests. Two gtests assert the specific TOO_LARGE_ARRAY_SIZE rejection rather than merely "it throws" — a plain ATTEMPT_TO_READ_AFTER_EOF would mean the reservation had already happened, which is exactly what the guards must prevent; both fail without them. test_max_entry_chunks_is_reloadable raises the chunk budget in node3's config and reloads, so a write skipped before the reload is stored after it.

Verified locally: ninja clickhouse unit_tests_dbms clean, 30/30 *QueryResultCache* gtests, and the three previously failing integration tests plus the new one pass (test_system_query_cache_multiple_entries, test_system_query_cache_stale_column, test_clear_by_tag_releases_inflight_lock, test_max_entry_chunks_is_reloadable).

The remaining reds on the previous run were the Stress test Not-ready Set is passed as the second argument for function 'globalNullIn' failures, which are the known unrelated #107619.

settings[Setting::query_cache_max_size_in_bytes],
settings[Setting::query_cache_max_entries]);

if (query_result_cache_writer_value.hasEntryAlreadyAvailable())

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.

hasEntryAlreadyAvailable() only means another writer finished while we were waiting; it does not override enable_reads_from_query_cache. In this branch a query with use_query_cache = 1, enable_reads_from_query_cache = 0 can still return a cached result after contending on an IN_PROGRESS lock, because we unconditionally re-read via createReader.

The current test_reads_disabled will miss this regression: this internal handoff uses hasCacheEntryForKey(false), so ProfileEvents['QueryCacheHits'] stays 0 even when the result came from the cache. Please gate this fast path on enable_reads_from_query_cache (like the Planner path already does) and extend the test to exercise a contended wait.

LOG_DEBUG(shared->log, "Lowered query result cache size to {} because the system has limited RAM", formatReadableSizeWithBinarySuffix(size));
}
shared->query_result_cache->updateConfiguration(size, max_entries, max_entry_size_in_bytes, max_entry_size_in_rows);
shared->query_result_cache->updateConfiguration(size, max_entries, max_entry_size_in_bytes, max_entry_size_in_rows, max_entry_chunks);

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.

SYSTEM RELOAD CONFIG still only rereads the size / entry / chunk limits on the already-created cache object. query_cache.type and the query_cache.redis.* connection / lock_* settings are only consumed during the initial setQueryResultCache, so switching from local to redis (or changing the Redis endpoint / lock timings) is a silent no-op until restart.

Because this PR advertises a config-driven backend choice, the reload path should either recreate the cache when those keys change or clearly treat them as startup-only and reject live changes.

@abashkeev abashkeev added the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Sep 3, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@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 19, 2026

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. external Author is not a member of the ClickHouse organization hold Skip for auto-updating. manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants