Repository navigation
Filesystem cache: encode segment size in the cache file name - #107415
Conversation
Startup metadata loading previously had to `stat` every cache file just to obtain its size, which dominates load time for caches with many files, where loading is bound by filesystem metadata latency. Encode the size into the file name of a fully downloaded regular segment: `<offset>` becomes `<offset>_<size>`. The rename happens atomically when a segment reaches its final size (`setDownloadedUnlocked` and the shrink-to-downloaded-size path). `FileSegment` tracks whether its on-disk file carries the size suffix (`hasSizeInFileName`) so that `getPath` always returns the real name, including across `detach`/removal. On startup, `loadMetadataForKey` reads the size directly from the file name and avoids the `stat` entirely. Files left without a size suffix - legacy `<offset>` files written by older versions, or files left by a download interrupted before the rename - are still loaded by falling back to a `stat`, so the change is backward compatible and crash safe (`rename` is atomic, so a crash leaves either `<offset>` or `<offset>_<size>`, both of which load correctly). Ephemeral (temporary) segments keep their `_temporary` marker and are removed on load as before. Call sites that reported a segment's path from its offset alone (`system.filesystem_cache.cache_path`, `SYSTEM SYNC FILESYSTEM CACHE`) now use the path captured in `FileSegmentInfo`, which reflects the real name. Adds an integration test covering the on-disk naming and backward-compatible loading of legacy `<offset>` files. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
f2ed23b to
34b3567
Compare
|
Workflow [PR], commit [acd8886] Summary: ✅
AI ReviewSummaryThis PR encodes fully downloaded filesystem-cache segment sizes into the on-disk file name so startup can restore metadata without a Findings
Tests
Final Verdict
|
| auto size = offset_it->file_size(); | ||
| /// Legacy `<offset>` files (and files left by a download that was interrupted before | ||
| /// the size was encoded into the name) require a `stat` to obtain the size. | ||
| UInt64 size = size_from_name.has_value() ? *size_from_name : offset_it->file_size(); |
There was a problem hiding this comment.
This PR is categorized as a Performance Improvement, but the only new evidence here verifies the naming/backward-compatibility behavior. I do not see a before/after startup measurement or a focused benchmark showing the expected win from avoiding file_size in loadMetadataForKey at realistic segment counts. Please add that measurement to the PR/test evidence, or include a small benchmark, so the changelog claim is verifiable.
There was a problem hiding this comment.
The mechanism is a direct reduction in startup syscalls: loadMetadataForKey previously issued one stat per cache file to learn its size, and that path is bound by filesystem metadata latency, so it dominates load time for caches with many files. Encoding <size> in the file name lets the loader read the size straight from the directory entry (already enumerated during the directory scan), removing the per-file stat entirely. The win therefore scales with the number of cache files and the per-stat latency of the underlying filesystem.
Adding a stable startup-time benchmark to CI is tricky (it would be dominated by I/O noise on the shared runners). Leaving the decision on whether to add a dedicated benchmark to @alexey-milovidov; the correctness and backward-compatibility behavior is covered by test_cache_file_size_in_name, test_parallel_cache_loading_on_startup, and test_system_sync_filesystem_cache.
|
📊 Cloud Performance Report ✅ AI verdict: This PR reworks the filesystem cache: it encodes segment size in the on-disk file name so startup metadata loading can skip a per-file stat, and adds lazy detection/recovery of externally truncated cache files on the read path. Both flagged ClickBench queries (Q4 -17.0%, Q15 -16.5%) correctly held at no_change: each source median lands inside master's current-era variance band while CPU time stays flat, so the apparent deltas are run-to-run variance, not a real speedup. That matches the diff, whose changed code is on the startup and error-recovery paths rather than the steady-state query read hot path. No regressions or genuine improvements detected. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
A fully downloaded regular cache segment is renamed from `<offset>` to `<offset>_<size>` so that startup can read the size from the file name. A read that opened the segment's cache file before completion cached a reader under the old name; once the segment finished downloading, `getCacheReadBuffer` recomputed the path as `<offset>_<size>` and tripped the `info.cache_file_reader->getFileName() == path` assertion (a logical error in debug/sanitizer builds). This aborted queries that read from a cached `s3` disk, e.g. `INSERT INTO test.hits_s3 SELECT * FROM test.hits`, which made the server fail to start in several stateless test jobs. Drop that assertion: the open descriptor stays valid across the rename and the caller (`prepareReadFromFileSegmentState`) reseeks the buffer, so reopening under the current name is safe. Additionally, read the path and open the file under the segment lock, so a reader never observes the brief window in which the file has been renamed on disk but `hasSizeInFileName` (read by `getPath`) has not yet been flipped (or vice versa) and tries to open a name that no longer exists. CI report: #107415 Co-Authored-By: Claude Opus 4.8 <[email protected]>
… files The backward-compatibility part of the test rewrote the on-disk cache file names from `<offset>_<size>` to the legacy `<offset>` form while the server was still running. The running server keeps the in-memory size-suffixed name (`hasSizeInFileName`), so on the next shutdown `assertCacheCorrectness` looked for `<offset>_<size>`, did not find it, and raised a logical error. Nothing in ClickHouse renames cache files behind a live server, so this only happened in the test. Stop the server before rewriting the names and start it afterwards. CI report: #107415 Co-Authored-By: Claude Opus 4.8 <[email protected]>
`setDownloadedUnlocked` published the `DOWNLOADED` state before renaming the cache file from `<offset>` to `<offset>_<size>`. Both callers (`completePartAndResetDownloader` and `complete`) reset the downloader only after `setDownloadedUnlocked` returns, so a throwing `fs::rename` left the segment `DOWNLOADED` with a stale `downloader_id`, violating the completed segment invariant checked by `assertCorrectnessUnlocked` (which expects an empty downloader for `DOWNLOADED`) and leaving inconsistent ownership state after a cache filesystem error. Perform the rename before publishing `DOWNLOADED`. On failure the segment is left `DOWNLOADING` with its downloader still set, which is a valid state, so the completion stays consistent and is retried. `rename` is still atomic, so a crash leaves either `<offset>` or `<offset>_<size>`, both of which load correctly. Addresses review feedback on #107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed 67988ab to address the review feedback: The remaining CI reds are unrelated to this change (which touches only the filesystem cache):
@groeneai, please investigate the stress-test flake: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107415&sha=5eedc4b0851a5c39fe09d483694ce2b7838f7954&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 — it is a pre-existing, merge-path |
|
@alexey-milovidov Confirmed, and no separate tracking issue is needed: this is the broken-promise shutdown race already tracked and fixed by PR #107383 (on review, CI green). The arm_debug failure (STID 2508-3dee) is a sibling of STID 2508-38c6. Every sighting shares the same two crash frames: PR #107383 replaces the bare The 30-day broad signature is 4 hits across 4 distinct PRs including master, all teardown, none touching thread-pool internals, consistent with your "pre-existing, unrelated" read. |
Follow-up to dropping the `getCacheReadBuffer` assertion: keep the cache-file open lock-free. The earlier change additionally took the segment lock around reading the path and opening the file; drop that. The open descriptor survives the post-download rename of the segment's file (`<offset>` -> `<offset>_<size>`) and the caller reseeks the returned buffer, so simply reopening under the current name is enough. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… filecache-size-in-filename
…rently Address review (kssenii, clickhouse-gh): a fully downloaded regular segment is renamed from `<offset>` to `<offset>_<size>` by `renameToIncludeSizeInNameUnlocked` while it may still be read, because reads are allowed before a segment is fully downloaded. `getPath` is lock-free, so the name computed in `getCacheReadBuffer` can become stale if the rename happens right before the open, and the open then fails because the file has already moved to its new name. Wrap the open in a `try`/`catch`: on failure, recompute the path while holding the segment lock — the rename runs under the same lock, so this serializes against it and observes the final name — and retry once. The fast path stays lock-free; the lock is taken only on the rare failure. If the path is unchanged, the failure is unrelated to the rename and is propagated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address review (kssenii): in the `FileSegment` constructor, the size is encoded into the file name only for fully downloaded regular segments, so `size_in_filename` may be set on creation only together with the `DOWNLOADED` state. Add a `chassert` next to the existing state-based asserts. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Encoding a fully downloaded segment's size into its file name (`<offset>` -> `<offset>_<size>`) is a startup optimization, but it was done with a fallible `fs::rename` whose failure could escape completion. `renameToIncludeSizeInNameUnlocked` runs from `setDownloadedUnlocked` while the segment is still `DOWNLOADING` with its downloader set. If the `rename` threw, `complete` / `completePartAndResetDownloader` never reached `resetDownloaderUnlocked`, so the segment was left owned by the unwinding query and no other reader could acquire it to retry. The throw also propagated into `FileSegmentsHolder::reset`, which then retried the same already-moved-from segment in a loop (`File segment is nullptr`). The segment is already fully downloaded and valid under its legacy `<offset>` name (which the loader handles via a `stat` fallback), so the rename is now best-effort: on failure we log and keep the legacy name without propagating the error. Completion then clears the downloader and publishes `DOWNLOADED` as usual. Adds `FileCacheTest.RenameToIncludeSizeInNameFailureKeepsSegmentConsistent`, which forces the rename to fail and asserts the segment completes without throwing, clears its downloader, and keeps the legacy name. Verified A/B: the test fails (and the holder loops on `File segment is nullptr`) without this change. Addresses review feedback on #107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
When opening a cache file we retry the open once under the segment lock to handle the `<offset>` -> `<offset>_<size>` rename happening concurrently. That race can surface only as `FILE_DOESNT_EXIST` (the old name is gone), so narrow the `catch` to that error code and propagate everything else immediately, instead of masking unrelated open failures behind a path recompute and retry. Addresses review feedback (kssenii) on #107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After `renameToIncludeSizeInNameUnlocked` renames a fully downloaded regular segment from `<offset>` to `<offset>_<size>`, a reader that opened the segment while it was still named `<offset>` leaves a live entry in `OpenedFileCache` keyed by the old name. When the segment is later removed, `removeFileSegmentImpl` invalidates only the current (`<offset>_<size>`) name, so the old `<offset>` entry survives. A future segment created at the same key and offset is again named `<offset>` while it downloads, so opening it could reuse the stale descriptor of the removed segment and read its old bytes. Drop the `<offset>` entry from `OpenedFileCache` right after a successful rename, mirroring the flag handling in `removeFileSegmentImpl` (the file may have been opened with or without `O_DIRECT`). Existing readers keep their own shared descriptors, which stay valid across the rename because the inode is unchanged; this only prevents future opens from reusing the pre-rename descriptor. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI review Block: pushed The bug was real. After the rename, The fix mirrors the existing invalidation in On the remaining |
S3 sporadically returns transient errors (e.g. `503 Service Unavailable`) for the `clickhouse-datasets` bucket, and `wget` retries only network-level errors, not HTTP errors, so a single 503 failed the whole `Performance Comparison` job at the `Download datasets` step. The step result also carried no `info`, so the CI report showed a bare `ERROR` and the cause was only findable in `job.log`. Move the download into a shared helper that retries each `wget | tar` pipeline with backoff (the pipe cannot be resumed mid-stream, and extraction into the target directory is idempotent, so rerun the whole pipeline) and returns per-dataset error descriptions, which now go into `Result.info`. Use it in both the performance comparison job and the profile collection job. Also drop the `-c` (continue) wget flag, which is a no-op with `-O-`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107415&sha=c0ba65e6aa6a1785e890e54d4ea742802c1da7b9&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%202%2F6%29 PR: ClickHouse#107415 Co-Authored-By: Claude Fable 5 <[email protected]>
…ilename # Conflicts: # src/Interpreters/tests/gtest_filecache.cpp
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 223/262 (85.11%) · Uncovered code |
#107415 renames a fully downloaded segment's file from `<offset>` to `<offset>_<size>` on completion, and `getPath` is lock-free - so the name `preadSegmentNode` computes can go stale between it and the filesystem open, surfacing as `FILE_DOESNT_EXIST` for a file that exists under its new name. Mirror the fix that PR applied to the legacy `CachedOnDiskReadBufferFromFile`: recompute the path under the segment lock (the rename runs under the same lock) and retry the open once; an unchanged path means the missing file is not explained by a rename and the error propagates. The streaming-reader slot and anchor cache are rename-safe already: a held descriptor survives the rename, and a stale-keyed entry just misses into a fresh open. Related: #107415 Co-Authored-By: Claude Opus 4.8 <[email protected]>
S3 sporadically returns transient errors (e.g. `503 Service Unavailable`) for the `clickhouse-datasets` bucket, and `wget` retries only network-level errors, not HTTP errors, so a single 503 failed the whole `Performance Comparison` job at the `Download datasets` step. The step result also carried no `info`, so the CI report showed a bare `ERROR` and the cause was only findable in `job.log`. Move the download into a shared helper that retries each `wget | tar` pipeline with backoff (the pipe cannot be resumed mid-stream, and extraction into the target directory is idempotent, so rerun the whole pipeline) and returns per-dataset error descriptions, which now go into `Result.info`. Use it in both the performance comparison job and the profile collection job. Also drop the `-c` (continue) wget flag, which is a no-op with `-O-`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107415&sha=c0ba65e6aa6a1785e890e54d4ea742802c1da7b9&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%202%2F6%29 PR: ClickHouse#107415 Co-Authored-By: Claude Fable 5 <[email protected]>
A fully downloaded regular cache segment is renamed from `<offset>` to `<offset>_<size>` so that startup can read the size from the file name. A read that opened the segment's cache file before completion cached a reader under the old name; once the segment finished downloading, `getCacheReadBuffer` recomputed the path as `<offset>_<size>` and tripped the `info.cache_file_reader->getFileName() == path` assertion (a logical error in debug/sanitizer builds). This aborted queries that read from a cached `s3` disk, e.g. `INSERT INTO test.hits_s3 SELECT * FROM test.hits`, which made the server fail to start in several stateless test jobs. Drop that assertion: the open descriptor stays valid across the rename and the caller (`prepareReadFromFileSegmentState`) reseeks the buffer, so reopening under the current name is safe. Additionally, read the path and open the file under the segment lock, so a reader never observes the brief window in which the file has been renamed on disk but `hasSizeInFileName` (read by `getPath`) has not yet been flipped (or vice versa) and tries to open a name that no longer exists. CI report: ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 <[email protected]>
… files The backward-compatibility part of the test rewrote the on-disk cache file names from `<offset>_<size>` to the legacy `<offset>` form while the server was still running. The running server keeps the in-memory size-suffixed name (`hasSizeInFileName`), so on the next shutdown `assertCacheCorrectness` looked for `<offset>_<size>`, did not find it, and raised a logical error. Nothing in ClickHouse renames cache files behind a live server, so this only happened in the test. Stop the server before rewriting the names and start it afterwards. CI report: ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 <[email protected]>
`setDownloadedUnlocked` published the `DOWNLOADED` state before renaming the cache file from `<offset>` to `<offset>_<size>`. Both callers (`completePartAndResetDownloader` and `complete`) reset the downloader only after `setDownloadedUnlocked` returns, so a throwing `fs::rename` left the segment `DOWNLOADED` with a stale `downloader_id`, violating the completed segment invariant checked by `assertCorrectnessUnlocked` (which expects an empty downloader for `DOWNLOADED`) and leaving inconsistent ownership state after a cache filesystem error. Perform the rename before publishing `DOWNLOADED`. On failure the segment is left `DOWNLOADING` with its downloader still set, which is a valid state, so the completion stays consistent and is retried. `rename` is still atomic, so a crash leaves either `<offset>` or `<offset>_<size>`, both of which load correctly. Addresses review feedback on ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Encoding a fully downloaded segment's size into its file name (`<offset>` -> `<offset>_<size>`) is a startup optimization, but it was done with a fallible `fs::rename` whose failure could escape completion. `renameToIncludeSizeInNameUnlocked` runs from `setDownloadedUnlocked` while the segment is still `DOWNLOADING` with its downloader set. If the `rename` threw, `complete` / `completePartAndResetDownloader` never reached `resetDownloaderUnlocked`, so the segment was left owned by the unwinding query and no other reader could acquire it to retry. The throw also propagated into `FileSegmentsHolder::reset`, which then retried the same already-moved-from segment in a loop (`File segment is nullptr`). The segment is already fully downloaded and valid under its legacy `<offset>` name (which the loader handles via a `stat` fallback), so the rename is now best-effort: on failure we log and keep the legacy name without propagating the error. Completion then clears the downloader and publishes `DOWNLOADED` as usual. Adds `FileCacheTest.RenameToIncludeSizeInNameFailureKeepsSegmentConsistent`, which forces the rename to fail and asserts the segment completes without throwing, clears its downloader, and keeps the legacy name. Verified A/B: the test fails (and the holder loops on `File segment is nullptr`) without this change. Addresses review feedback on ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
When opening a cache file we retry the open once under the segment lock to handle the `<offset>` -> `<offset>_<size>` rename happening concurrently. That race can surface only as `FILE_DOESNT_EXIST` (the old name is gone), so narrow the `catch` to that error code and propagate everything else immediately, instead of masking unrelated open failures behind a path recompute and retry. Addresses review feedback (kssenii) on ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… error Startup metadata loading trusts the `<size>` encoded in a fully downloaded regular segment's file name without a `stat`. If such a file is truncated outside ClickHouse, the segment is restored as fully `DOWNLOADED` but the on-disk file is shorter than recorded. On read this previously surfaced as a `LOGICAL_ERROR` (the "empty cache file" exception for a zero-length file, or "Having zero bytes, but range is not finished" for a shorter one). `getCacheReadBuffer` already opens the cache file and reads its size, so we can detect `actual_size < downloaded_size` there with no extra `stat`. Treat it as a possible inconsistency rather than a server-bug-class `LOGICAL_ERROR`: discard the broken segment via `removeFileSegmentIfExists(..., can_be_broken = true)` (the same primitive `LockedKey::sync` uses for size mismatches) and fail with a retryable `CANNOT_READ_ALL_DATA`. On retry the segment is gone, so the data is re-fetched from the source. Restricted to `DOWNLOADED` segments, where `downloaded_size` is final, to avoid racing with an in-progress download. Adds `test_cache_file_truncated_size_in_name`, which truncates a `<offset>_<size>` cache file (to a shorter size and to zero bytes), restarts, and asserts the query recovers without a logical error and returns intact data. Addresses the review feedback on ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A fully downloaded regular cache file is renamed to `<offset>_<size>`, and startup metadata loading reads the size straight from the file name without a `stat` (`FileCache::loadMetadataForKey`). The `FileSegment` constructor for the `DOWNLOADED` state, however, still did `chassert(fs::file_size(getPath()) == size_)`. For an externally truncated or corrupted `<offset>_<size>` file this fired during `loadMetadataForKey`, aborting server startup in debug/sanitizer builds, before `getCacheReadBuffer`'s lazy discard could run. It also re-introduced the very `stat` the size-in-filename optimization avoids. Skip the assertion when the size came from the file name (`chassert(size_in_filename || fs::file_size(getPath()) == size_)`). The legacy `<offset>` path (size obtained via `stat`) keeps the check. A truncated file is still handled lazily on read: `getCacheReadBuffer` compares the on-disk size against `downloaded_size` and discards the broken entry, re-fetching from the source with a retryable error. This fixes the `test_filesystem_cache` startup crash seen across the sanitizer integration shards (the new `test_cache_file_truncated_size_in_name` restarts the server with a truncated cache file). Confirmed by the CI backtrace (`FileSegment.cpp:106` -> `FileCache::loadMetadataForKey`). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107415&sha=8922934414a6e90c4fb4a608de9b5f14c727cc31&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29 PR: ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
With the size-in-filename change, reading a truncated cache file no longer raises a `LOGICAL_ERROR`: `getCacheReadBuffer` discards the broken segment (removing its on-disk file) and fails the read with a retryable `CANNOT_READ_ALL_DATA`. As a result the corrupted segment of `all_1_1_0` is dropped by the failed read, so `CHECK TABLE` then reads it as a clean cache miss, re-fetches it from the source and re-populates a correct cache entry — the cache self-heals instead of being left removed by `CHECK TABLE`. The previous assertion that the part's cache is removed after `CHECK TABLE` (`assert len(cache_path) == 0`) therefore no longer holds; the cache is present again. Assert that it is present (self-healed), while the untouched part `all_2_2_0` keeps its cache. This matches the deterministic failure on the non-sanitizer integration shards (`arm_binary`, `amd_llvm_coverage`), where the test is not skipped. PR: ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Commit `fbfd9a76119` relaxed the `chassert(fs::file_size(getPath()) == size_)` in the `FileSegment` constructor for `<offset>_<size>` segments, but the same on-disk size check survived in `FileSegment::assertCorrectnessUnlocked` for the `DOWNLOADED` state (`chassert(file_size == range().size())`). `FileCache::loadMetadata` calls `assertCacheCorrectness` right after loading all keys (`FileCache.cpp:2137`), which iterates every segment and reaches that assertion. For an externally truncated `<offset>_<size>` file the segment is restored as fully `DOWNLOADED` with the encoded size, so the on-disk file is shorter than `range().size()` and the assertion fired during the end-of-load correctness check — aborting server startup in debug/sanitizer builds, before `getCacheReadBuffer`'s lazy discard could run. Skip the on-disk size `stat` and assertion when the size came from the file name (`size_in_filename`), mirroring the constructor. This also avoids re-introducing the very `stat` the size-in-filename optimization removes. A truncated file is still handled lazily on read: `getCacheReadBuffer` compares the on-disk size against `downloaded_size` and discards the broken entry, re-fetching from the source with a retryable error. The legacy `<offset>` path (size obtained via `stat`) keeps the check. This fixes the `test_cache_file_truncated_size_in_name` startup crash and the resulting cascade of `Connection refused` failures across every `test_filesystem_cache` integration shard. Addresses the review feedback on ClickHouse#107415 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107415&sha=4f25d806daf277e22d868cac90bb93f222ba92e6&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… source When `getCacheReadBuffer` detects that a fully downloaded `<offset>_<size>` cache file is shorter than its recorded size (it was truncated outside ClickHouse), it discards the broken segment. Previously it then threw `CANNOT_READ_ALL_DATA`, expecting the caller to retry and re-fetch the data. That works for data segments read at query time, but not for cache files that back a part's mark/metadata files, which are read during `MergeTree` part loading at startup. There the `CANNOT_READ_ALL_DATA` is interpreted as a broken part: the loader detaches the part instead of recovering, so the table ends up with zero active parts and queries return zero rows (the failure seen in `test_cache_file_truncated_size_in_name`). Fix: after discarding the broken segment (now `DETACHED`), `getCacheReadBuffer` returns `nullptr`, and `createReadFromFileSegmentState` re-routes the read to `REMOTE_FS_READ_BYPASS_CACHE` -- the same outcome as the existing `DETACHED` branch -- so the data is transparently re-fetched from the source and the part loads. This restores the fail-open-then-refetch behavior of `master` while keeping the size-in-filename optimization. A corrupted cache file is also no longer surfaced to the user as an error. Updated `test_check_part_with_cache` (the truncated read now succeeds with the correct result instead of raising) and the comments in `test_cache_file_truncated_size_in_name`. Verified `test_cache_file_truncated_size_in_name` passes locally on a debug build. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107415&sha=297a2d993500fca016cfd1a8ea1367b6b9f67478&name_0=PR PR: ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the AI review "Request changes" on `getCacheReadBuffer` (`CachedOnDiskReadBufferFromFile.cpp`) in PR ClickHouse#107415. When several readers race on the same externally truncated `<offset>_<size>` cache file, one reader can discard/detach the segment between another reader opening the short file and the `cache_file_size < downloaded_size` re-check. Previously the recovery branch only fired while the segment was still `DOWNLOADED`, so the losing reader saw `DETACHED`, skipped the bypass, kept its truncated descriptor and later reached the `Having zero bytes...` `LOGICAL_ERROR` instead of re-fetching from the source. A second, narrower window existed even for a `DOWNLOADED` segment: `getKeyMetadata` throws a `LOGICAL_ERROR` if the segment is detached between the state check and the removal. Fix: - Trigger the discard/bypass for a `DETACHED` segment as well. This is the only extra state reachable here (`createReadFromFileSegmentState` never routes `DETACHED` to the cached read), so it can only arise from the race. `downloaded_size` is not reset on detach, so the truncation is still detectable, and bypassing to the source is the correct outcome for a segment that is already gone. - Make the key-metadata lookup best-effort with `tryGetKeyMetadata` (instead of `getKeyMetadata`, which throws on a detached segment). `removeFileSegmentIfExists` is already idempotent. Adds `test_cache_file_truncated_size_in_name_concurrent_readers`: many parallel scans, released together by a barrier, race on the same truncated segments and must all bypass/refetch without a `LOGICAL_ERROR`, with the data left intact. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…n-name rename Encoding the segment size in the file name (`<offset>` -> `<offset>_<size>`) is a best-effort startup optimization done from `renameToIncludeSizeInNameUnlocked`. When the target name is already occupied (e.g. by a leftover directory), the rename fails and the real segment stays under its legacy `<offset>` name, while the stale `<offset>_<size>` artifact remains on disk. On the next restart `loadMetadataForKey` parsed both names as live segments for the same offset, which: - in debug/sanitizer builds hit the `chassert(false)` on the duplicate-offset path, aborting server startup; - in release builds removed whichever entry was iterated second, so if the stale suffixed artifact was seen first, startup deleted the real legacy cache file and kept the bogus `<offset>_<size>` entry (iteration-order dependent). Harden `loadMetadataForKey` phase 1: - Skip non-regular directory entries (using the type already cached by `directory_iterator`, so no extra `stat`). A non-regular `<offset>_<size>` entry is exactly what makes the rename fail, so it must never be parsed and trusted as a segment. - Deduplicate by offset, preferring the legacy `<offset>` file (its size comes from a real `stat`, and it is the segment whose rename failed) over the suffixed duplicate. The stale artifact is left on disk rather than deleted, to avoid a destructive action on this path. Extend `FileCacheTest.RenameToIncludeSizeInNameFailureKeepsSegmentConsistent` through a cache reload: after forcing the rename failure it reopens the cache and asserts startup restores exactly one segment from the legacy file, keeps that file intact, and never hits the duplicate-offset path. Addresses the AI review finding on ClickHouse#107415 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…n-filename Filesystem cache: encode segment size in the cache file name
On startup, filesystem cache metadata loading has to learn the size of every cache file. Previously this was a
statper file, which dominates load time for caches with many files (loading is bound by filesystem metadata latency).This encodes the size into the file name of a fully downloaded regular segment:
<offset>becomes<offset>_<size>. The rename happens atomically when a segment reaches its final size. On startup,loadMetadataForKeyreads the size straight from the file name and skips thestat.Backward compatible and crash safe:
<offset>files (written by older versions) and files left by a download interrupted before the rename are still loaded — by falling back to astat.renameis atomic, so a crash leaves either<offset>or<offset>_<size>, both of which load correctly._temporarymarker and are removed on load as before.FileSegmenttracks whether its on-disk file carries the size suffix (hasSizeInFileName) sogetPathalways returns the real name, including acrossdetach/removal. Reporting paths (system.filesystem_cache.cache_path,SYSTEM SYNC FILESYSTEM CACHE) now use the path captured inFileSegmentInforather than recomputing it from the offset.Validated with
test_parallel_cache_loading_on_startup,test_system_sync_filesystem_cache, and a newtest_cache_file_size_in_name(on-disk naming + backward-compatible loading of legacy<offset>files).Related: #107414
Related: #107416
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up filesystem cache loading on startup by encoding each cache file's size in its name (
<offset>_<size>), avoiding astatper file. Loading of cache files written by older versions remains supported.Documentation entry for user-facing changes