Repository navigation
Conversation
|
Workflow [PR], commit [e8ce8a9] Summary: ❌
AI ReviewSummaryThis 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
Tests
Final VerdictChanges required before merge. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1338/1594 (83.94%) · Uncovered code |
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]>
…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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1184/1405 (84.27%) · Uncovered code |
…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`.
`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.
|
🕵 Addressed the outstanding AI-review findings (blocker + 6 majors + 3 test items) in Blocker — remote-cache hit detection does not validate the full identity One size/chunk contract on write and read Planner subquery handoff Re-entrant fast path vs lease expiry
Cancellation during the stampede wait Tests Verified locally: The previous CI red, |
| Block header_block; | ||
| { | ||
| NativeReader reader(buf, /*server_revision=*/0); | ||
| header_block = reader.read(); |
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
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`
…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.
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
|
🕵 Addressed the three remaining AI-review findings, and fixed a real bug they led me to, on top of a fresh
The schema block was not covered by that hardening —
Tests. Two gtests assert the specific Verified locally: The remaining reds on the previous run were the |
| settings[Setting::query_cache_max_size_in_bytes], | ||
| settings[Setting::query_cache_max_entries]); | ||
|
|
||
| if (query_result_cache_writer_value.hasEntryAlreadyAvailable()) |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
Changelog category (leave one):
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.typeis set toredis,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_PROGRESSlock mechanism to prevent redundant query execution across nodes.Documentation entry for user-facing changes
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:
QueryResultCacheinto an abstract interface (IQueryResultCache) with aLocalQueryResultCacheimplementation preserving existing behaviorRemoteQueryResultCachethat delegates storage to a pluggableIRemoteCacheBackendRedisRemoteCacheBackendimplementing Redis-based storage with connection poolingQueryResultCacheFactoryfor config-driven cache type selection (localorredis)IN_PROGRESSlock usingSET … NX PXto prevent thundering herd on cache missessystem.query_cacheuses RedisSCANto enumerate entries when the Redis backend is activeuse_query_cache,query_cache_ttl,query_cache_tag,query_cache_share_between_users, etc.) work identically with bothbackends
Configuration (in
config.xml):