Repository navigation
Remove per-query filesystem cache write limit - #114165
Conversation
`enable_filesystem_query_cache_limit` together with `filesystem_cache_max_download_size` did not limit how much a query writes into the cache: the per-query priority entry was created with size 0 and never incremented, so only a single reservation bigger than the whole limit was rejected. A query reading 12 MB with a 1 MiB limit wrote all 12 MB. - Query-side accounting now mirrors every reservation, not only the first one for a file segment. - Segments evicted during a reservation are dropped from the per-query mirror, so their bytes stop counting against the query and no stale iterator is kept for their key/offset. `QueryContext::remove` no longer throws `There is no <key>:<offset> in query context`: a missing record is normal, because eviction candidates are collected from the whole cache. - The reserve-ahead surplus returned by `FileSegment::shrinkFileSegmentToDownloadedSize` is uncharged from the query as well, otherwise a whole `reserve_granularity` granule (4Mi by default) stays charged per touched segment. - A query context now lives as long as the query rather than as long as its read buffers, and a finished query's `query_id` cannot inherit a stale budget. - `records` is guarded by its own leaf mutex, and obtaining a query context holder no longer takes the cache priority write lock. - A per-query queue entry may outlive its file segment, because any other thread can evict it, so the assertion in `LRUFileCachePriority::iterateImpl` is restricted to the other queues and a candidate which is already being evicted is skipped. - Added the `FilesystemCacheFailToReserveSpaceBecauseOfQueryLimit` profile event, so that reaching the limit is visible in `system.query_log`. - The documentation referenced `max_query_cache_size`, which does not exist in the code. - CI randomizes `enable_filesystem_query_cache_limit` for the `s3_cache` disk. Tests: `04817_filesystem_query_cache_limit` and the `FileCacheTest.QueryLimit*` gtests. Each of the changes above was reverted separately and the corresponding test was seen to fail without it. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [b6e770e] Summary: ❌
AI ReviewSummaryReviewed #114165 at Final VerdictStatus: ✅ Approve. |
- Uncharge an evicted segment from every query which cached it, not only from the query which happened to be reserving when the eviction took place. `Q1` used to keep being charged for a segment evicted during `Q2`'s reservation and stopped caching although its data was long gone. The evicted entries are now also collected when the evicting query has no per-query limit itself. - Do not queue a background download of the part of a file segment which does not fit into what the query has left to write: the download continues from a thread without a query context, so its bytes are not charged to the query which started it and used to bypass `filesystem_cache_max_download_size`. - `reserveAndDownload` in the unit test is const (clang-tidy `readability-make-member-function-const`). Adds `QueryLimitUnchargesSegmentsEvictedByAnotherQuery`, which fails without the first change (the limited query cannot cache anything after another query evicted its data). Co-Authored-By: Claude Opus 5 <[email protected]>
The reserve-ahead surplus given back by `FileSegment::shrinkFileSegmentToDownloadedSize` is the surplus of the whole file segment (`reserved_size - downloaded_size`), while a per-query record holds only what that query reserved of it. A segment whose download was taken over by another query therefore returns a surplus larger than the current query is charged for it, and uncharging it hit `chassert(entry_ptr->size >= size)` in `decrementSize` (abort in debug and sanitizer builds) or wrapped the per-query size around in release builds, after which the query could never cache anything again. Uncharge at most what the query is charged. Also destroy the context of a finished query in `getOrSetQueryContext` after `query_map_mutex` is released, as `removeQueryContext` already does. `QueryLimitUnchargeDoesNotUnderflow` aborts on `entry_ptr->size >= size` without the first change. Co-Authored-By: Claude Opus 5 <[email protected]>
The test needs its reads to populate the cache, while CI randomizes `read_from_filesystem_cache_if_exists_otherwise_bypass_cache` (and `enable_filesystem_cache`). With `read_from_filesystem_cache_if_exists_otherwise_bypass_cache = 1` the unlimited read wrote nothing into the cache, so "writes more than the limit" was 0. Both settings are now pinned per query, which also keeps them independent of the client-level randomization.
…-limit-missing-record
…dashboard This pull request adds the `FilesystemCacheFailToReserveSpaceBecauseOfQueryLimit` profile event, and `04817_filesystem_cache_dashboard_metrics_coverage` (added in master meanwhile) requires every filesystem cache metric to be plotted on the `Filesystem cache` dashboard. Show it next to the other reasons for skipping a space reservation.
The unwritten part of a reservation was given back to whichever query happened to complete the file segment, and to nobody at all when a background download completed it. A file segment is completed by its last holder, which after a hand-over of the download is not the query charged for the reserve-ahead, so a query could both stay charged for bytes it never wrote and be credited for bytes it did write, the latter letting it exceed `filesystem_cache_max_download_size`. `FileSegment::reserve` now remembers which query the reservation was charged to, as reported by `FileCache::tryReserve` itself, and the surplus goes back to exactly that query - to nobody when it was reserved without a query context, as a background download is. The write which follows a reservation consumes the previous reserve-ahead, so the query charged last owns all of it. Also do not start a background download which would write more than the current query has left: its bytes are charged to no query. The download thread computes the size on its own, so this can only decide whether to start at all. `QueryLimitSurplusGoesBackToTheQueryWhichReservedIt` hands a partially written segment over and completes it in another query, which fails when the surplus follows the completing query. Co-Authored-By: Claude Opus 5 <[email protected]>
`FileSegmentsHolder` has a `reset` method of its own, so `reserved.reset()` on the holder pointer is an ambiguous call (`readability-ambiguous-smartptr-reset-call`).
Build profile diff (arm_release)Comparing commit See the job log for details. |
…te to a query `filesystem_cache_max_download_size` is renamed to `filesystem_cache_query_limit_bytes`, keeping the old name as an alias, and defaults to `0`, which disables the limit. Its previous default of 128Gi was never reached, while `enable_filesystem_query_cache_limit` in the cache configuration was enough to make every query keep per-query accounting. That flag now only permits the limit and defaults to true, so a cache costs nothing until a query asks for a budget: with `0` a reservation does one atomic load and takes no lock, which `FileCacheQueryLimit::hasQueryContexts` and `FileSegment::has_query_limit_owner` are there for. Bytes written by a background download were charged to no query at all, so a query could hand a segment over to the download thread and keep writing past its budget. The reservation made without a query of its own is now charged to the query which reserved that segment (a thread which does belong to a query is never charged for another one), and a continuation which that query has no budget for is not started, as its reservation would fail and leave the segment unfinishable. A query which released its last read buffer before finishing used to leave its context behind until an unrelated read buffer was released. Finished contexts are now also swept when the next query arrives and when a reservation finds none of its own, so one leftover context cannot keep every later reservation taking the lock. `QueryLimitChargesReservationsWithoutAQuery` and `QueryLimitContextIsDroppedWhenTheNextQueryArrives` fail without the respective change. `04847_filesystem_query_cache_limit_per_query` checks that the budget is per query - two queries write more than one budget in total - and that a reused query id starts with a fresh one. `filesystem_cache_query_limit_bytes` is randomized in CI, mostly disabled because a set limit makes every reservation take the cache write lock. Co-Authored-By: Claude Opus 5 <[email protected]>
…entry
Uncharging a segment evicted by another query removed that segment's record from every query
mirror, including the record of a query which was reserving the same key and offset right then. A
reservation takes the cache write lock to create or find its record and the cache state lock to
account the reserved size, so between the two another thread could remove the record and its queue
entry, and the reservation then failed on an invalid iterator:
Logical error: 'Attempt to use invalid iterator (entry: false, iterator: false)'
LRUFileCachePriority::LRUIterator::assertValid()
LRUFileCachePriority::LRUIterator::incrementSize()
FileCache::doTryReserve()
An evicted segment now has its charge zeroed instead, and the record and its queue entry stay: they
are what a reservation in flight is holding, and a segment re-created at the same key and offset
reuses the record anyway. The uncharge needs no cache lock any more, so it happens right after
eviction rather than inside the write-lock block.
`QueryLimitUnchargeKeepsRecordsUsable` reproduces the interleaving and fails when the record is
removed instead of uncharged.
…-limit-missing-record
`04847_filesystem_query_cache_limit_per_query.sh` was committed with mode `100644`, so every CI run of it failed with return code 126 (`Permission denied`) before the test body ran. `02344_describe_cache` prints all filesystem cache settings, so it has to follow the new `enable_filesystem_query_cache_limit` default. Co-Authored-By: Claude Opus 5 <[email protected]>
…-limit-missing-record
Four defects of the per-query filesystem cache write limit, all found in review of #114165: * A segment which left the cache stayed charged to the queries which had cached it, unless it was evicted by a reservation. Dropping the cache or removing a key left the charge behind, so a query could stop writing into the cache while nothing of it was cached anymore. The uncharge now happens in `FileSegment::detach`, the single point where a segment leaves the cache, which also covers eviction: `doTryReserve` no longer has to collect what it evicted. That also fixes uncharging a candidate whose eviction then failed, since the old code took its snapshot before evicting. * The per-query mirror kept a record and a queue entry for every segment the query had ever cached, so both the mirror and the eviction walk over it grew without bound while only a small window was still charged. Removal now invalidates the entry (which releases the charge without any cache lock) and drops the record, and the entry leaves the queue through the priority's `invalidated_refs` drain on the query's next reservation. * `query_id` is reusable, so a background download which outlived its query could be charged to a new query which happened to use the same id. `DownloadState` now keeps a `weak_ptr` to the query context instead of the id: once that query is gone the handle is empty and nobody is charged. This also removes a hash lookup and a mutex from the surplus and the background download paths, which now call the context directly. * The owner of the outstanding reserve-ahead was replaced before the write which consumes it, so a handover (or a write failing right after the reservation) left those bytes charged to a query which never wrote them. The previous owner is now given them back, keeping it charged for exactly what it did write. `QueryLimitUnchargesSegmentsDroppedFromCache` covers the first one: without the uncharge in `detach` the query stays charged after `removeAllReleasable` and its next reservation fails. Co-Authored-By: Claude Opus 5 <[email protected]>
`26.8` is released, so the `filesystem_cache_query_limit_bytes` entry belongs to the `26.9` section of `SettingsChangesHistory`. The `storing-data` page still described the setting under its old name `filesystem_cache_max_download_size` and with the old defaults, so a user following it would configure the wrong knob and expect the opposite default. The autogenerated settings reference is left to its generator. Co-Authored-By: Claude Opus 5 <[email protected]>
The budget for the background continuation was stamped where the download is queued, in `FileSegment::complete`, so the query completing the segment as its last holder became the owner. That query need not have downloaded anything: a reader with `read_from_filesystem_cache_if_exists_otherwise_bypass_cache`, which is documented never to populate the cache, gets existing segments from `FileCache::get` and can be the last holder of a `PARTIALLY_DOWNLOADED` segment another query left behind, together with that query's remote file reader. The continuation was then charged to a query which wrote nothing. Stamp the budget in `FileSegment::getOrSetDownloader` instead: the continuation belongs to the query which was downloading the segment, and a passive holder never becomes a downloader. The assignment is unconditional, so a query which sets no limit still clears the previous owner instead of leaving it charged. `FileCache::getQueryBudgetIfExists` becomes `FileCache::getCurrentQueryBudget` and returns an optional, because the two null cases now differ: a query with no limit must clear the stamp, while the background download thread, which elects itself downloader before reading the stamp in `CacheMetadata::downloadImpl`, must keep it. Co-Authored-By: Claude Opus 5 <[email protected]>
… prefetch accounting, test strength Implements the blocking and major items of the AI review on the previous head. - `Server.cpp`: the merged-view check of the memory-pressure threshold triple runs after `config().replace`, so a failed `SYSTEM RELOAD CONFIG` (file valid alone, merge with a command-line override out of order) kept publishing the rejected values through `config()` and `system.server_settings`. Keep the previous `default` layer (`LayeredConfiguration::find`) and put it back when the merged view is rejected, before rethrowing. Verified with a live server started with `--reader_executor_memory_pressure_high_level_pct=80`: a reload setting `elevated=85` is rejected and `system.server_settings` keeps 75; a following valid reload applies. - `DiskLocal::prepareRead`: attach the executor prefetch pool for both prefetch-capable local methods (`pread_threadpool` and `pread_fake_async`, the set `MergeTreePrefetchedReadPool::checkReadMethodAllowed` accepts), so `local_filesystem_read_prefetch = 1` is no longer a silent no-op under `pread_fake_async` with `use_reader_executor = 1`. - `ReaderExecutor::cancelMachine`: `ReaderExecutorPrefetchWastedSourceBytes` now charges only the issued bytes the cancelled worker did not already commit into cache writers (its `BytesPushedToCacheSync`), as the counter's own description promises. - `ReaderExecutorPrefetchInFlight`: describe what the gauge measures (machine lifetime, including completed-but-uncollected read-ahead). - `test_reader_executor_metric`: `_measure` read a non-existent `ReaderExecutorRequestedBytes` (always 0), which made the cost-per-MiB KPI vacuous; switch to `ReaderExecutorDeliveredBytes`. `test_page_cache_path` now also asserts every warm sample issued bytes from the page-cache tier (`ReaderExecutorBytesFromPageCache`), not only fewer source requests. - `04331_reader_executor_s3_read_introspection`: assert the contract the test comment states for the warm scan directly: zero `bytes_from_source` and zero `source_requests`. Not changed, with reasons on the threads: the per-query `FileCache` charging gate is identical to master and is being fixed in #114165. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…created `FileCache::doTryReserve` created the key's directory last, after the segment had already recorded the reservation - `setQueueIterator`, `reserved_size += size`, and the size added to the main queue. When `create_directories` failed (no space or no inodes left), it returned false without undoing any of it. The segment was left `EMPTY` yet holding a queue entry, which `FileSegment::complete` asserts against, and the main queue kept counting the size. A later reservation of the same segment then took the fast path that assumes an existing queue entry, skipped creating the directory, and its write failed. Create the directory after eviction, so a full cache disk can still admit once space is reclaimed, and before the segment records the reservation. On failure undo what the exception path above already undoes: invalidate a freshly added queue entry, or give back the size added to an existing one. The per-query queue is left as the exception path leaves it; its accounting is being fixed in ClickHouse#114165. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Ergus
left a comment
There was a problem hiding this comment.
LGTM (the PR is big and only 4 comments easy to address were found)
As an extra detail, I see that the description doesn't mention the behaviour change. Users who set filesystem_cache_skip_download_if_exceeds_per_query_cache_write_limit = 0 change from "evict-and-recache" to "stop-caching" with no warning. I think that the entry should say so explicitly;
IMO "Backward Incompatible Change" or "Improvement" fits better than "Bug Fix", WDYT?
| {"load_marks_asynchronously", false, true, "Load marks of all streams in parallel by default. On remote disks, synchronous loading of marks of columns with many substreams (such as `JSON`) took one network round trip per stream."}, | ||
| {"ast_fuzzer_oracle", false, false, "New setting to enable correctness oracle checks in the server-side AST fuzzer."}, | ||
| {"filesystem_cache_skip_download_if_exceeds_per_query_cache_write_limit", true, true, "Obsolete: a query which reaches `filesystem_cache_query_limit_bytes` always stops caching now, it never evicts what it cached itself."}, | ||
| {"filesystem_cache_query_limit_bytes", 137438953472, 0, "Renamed from `filesystem_cache_max_download_size`, which stays as an alias, and disabled by default. The per-query filesystem cache write limit is now opt-in: the previous default of 128Gi was never reached in practice, while `enable_filesystem_query_cache_limit` in the cache configuration alone was enough to make every query maintain per-query accounting."}, |
There was a problem hiding this comment.
We need an entry like {"filesystem_cache_max_download_size", 137438953472, 0, "Alias for setting filesystem_cache_query_limit_bytes, whose default changed."}
|
|
||
| bool reserved = cache->tryReserve( | ||
| *this, size_to_reserve, *reserve_stat, *getKeyMetadata()->origin, lock_wait_timeout_milliseconds, failure_reason); | ||
| if (query_budget && !query_budget->tryChargeBytes(size_to_reserve)) |
There was a problem hiding this comment.
The budget is charged for the whole reserve-ahead block (size_to_reserve after rounding up to the granularity), not for the bytes about to be written.
Is it possible that with a 10 MiB limit, the third 4 MiB charge fails after 8 MiB, so the last 2 MiB of the budget is never used? Or I am missing something?
| shared->macros.set(std::move(macros)); | ||
| } | ||
|
|
||
| FileCacheQueryBudgetPtr Context::getFilesystemCacheQueryBudget(const FileCache & cache, size_t size_limit) const |
There was a problem hiding this comment.
FWIS the first caller fixes size_limit for the whole query because getFilesystemCacheQueryBudget ignores size_limit once the budget exists, so 2 queries with different filesystem_cache_query_limit_bytes share the first value.
- A reader with limit 0 inside a query whose subquery has a limit gets nullptr for its own reservations.
getOrSetDownloaderstill stamps the subquery's budget on that background continuation.
If this is intende we must document that "per query, first value wins", else we must chassert that the limits match.
| /// stay charged against the quota. Done before the `result_size == range().size()` early return | ||
| /// below, since with `reserve_granularity == boundary_alignment` a tiny read rounds up to the | ||
| /// whole range and would otherwise keep a full granule charged. | ||
| chassert(reserved_size >= downloaded_size); |
There was a problem hiding this comment.
Are these hunks leftovers from the earlier design that refunded the budget in shrinkFileSegmentToDownloadedSize?
…-limit-missing-record # Conflicts: # docs/concepts/features/configuration/server-config/storing-data.mdx # src/Client/BuzzHouse/Generator/SessionSettings.cpp # src/Core/Settings.cpp # src/Core/SettingsChangesHistory.cpp # src/Interpreters/Context.cpp # src/Interpreters/tests/gtest_filecache.cpp # tests/queries/0_stateless/04652_system_documentation_settings_history.sql
|
Why do we need this at all? |
| | `filesystem_cache_allow_background_download` | Boolean | `true` | Allows partially downloaded segments to be finished in the background. Disable to keep downloads in the foreground for the current query/session. | | ||
| | `max_query_cache_size` | Size | `false` | Maximum cache size per query. Requires `enable_filesystem_query_cache_limit` in cache config. | | ||
| | `filesystem_cache_skip_download_if_exceeds_per_query_cache_write_limit` | Boolean | `true` | Controls behavior when `max_query_cache_size` is reached: <br/>- `true`: Stops downloading new data <br/>- `false`: Evicts old data to make space for new data | | ||
| | `filesystem_cache_query_limit_bytes` | Size | `0` | Maximum amount of data a single query may write into the cache. `0` (the default) means no limit. Counts the space the query reserves itself, so data another query cached is not counted. Requires `enable_filesystem_query_cache_limit` in cache config. The former name `filesystem_cache_max_download_size` stays as an alias. | |
There was a problem hiding this comment.
If we do this setting as a fail safe to protect the cache from the case when one big query wash out all the data, I would expect to see that setting as a fraction from the all size.
Like 0.3 -- one request could not write (and evict) more than that.
SLRU also inherently guards against this scenario. When a large, cold request arrives, only the elements at the bottom of the queue are removed. However, no one offers defense against repeated queries designed to clear the cache, this feature does not protect from repeated queries either,
The limit capped how much one query could write into one filesystem cache: `filesystem_cache_max_download_size` on the query side, gated by the cache configuration setting `enable_filesystem_query_cache_limit`. It was expensive and it did not work. Each cache kept a second priority queue per query; `FileCache::doTryReserve` mirrored new entries into it under the cache state lock and `doEviction` walked it as a separate eviction pass. The accounting behind it was never correct - nothing decremented the per-query counters, so mirroring every reservation would have made them grow without bound, and the existing code sidestepped that by mirroring only the first reservation of each file segment, which undercounts instead. Rather than make the accounting correct, drop the feature. Nothing caps a single query's writes into a cache any more; the cache's own `max_size` and its eviction policy bound them, as they do for every other writer. `filesystem_cache_max_download_size` and `filesystem_cache_skip_download_if_exceeds_per_query_cache_write_limit` (with its alias `skip_download_if_exceeds_query_cache`) become obsolete settings, and so does the cache configuration setting `enable_filesystem_query_cache_limit`, so existing profiles and disk definitions keep parsing and are ignored. The tests of the feature are deleted rather than inverted. Co-Authored-By: Claude Opus 5 <[email protected]>
…-limit-missing-record # Conflicts: # src/Interpreters/FileCache/FileCache.cpp # src/Interpreters/FileCache/FileSegment.cpp # src/Interpreters/tests/gtest_filecache.cpp
…-limit-missing-record
The merge with master kept master's `FileCache` and `gtest_filecache.cpp`, which still used the removed `Interpreters/FileCache/QueryLimit.h`, breaking the build. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114165&sha=latest&name_0=PR #114165 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`DiskCacheProvider` no longer takes the query id, so clang-tidy reports `bugprone-unused-local-non-trivial-variable`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114165&sha=01d24cbdc9d90e2aa1d0ec436191efdcf377b097&name_0=PR #114165 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Removed the per-query filesystem cache write limit, which capped how much a single query could write into one filesystem cache. Its accounting never reflected what a query had actually written, and it cost a second priority queue per query on the cache reservation hot path. The settings
filesystem_cache_max_download_sizeandfilesystem_cache_skip_download_if_exceeds_per_query_cache_write_limit(with its aliasskip_download_if_exceeds_query_cache), and the cache configuration settingenable_filesystem_query_cache_limit, are now obsolete and ignored, so queries and disk definitions that set them keep working. It is recommended to just use SLRU cache policy instead.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/114165]
Version info
26.11.1.869-master(included in26.11and later)