Skip to content

Filesystem cache: encode segment size in the cache file name - #107415

Merged
alexey-milovidov merged 33 commits into
masterfrom
filecache-size-in-filename
Jul 16, 2026
Merged

alexey-milovidov merged 33 commits into
masterfrom
filecache-size-in-filename

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 13, 2026 •

Copy link
Copy Markdown
Member

On startup, filesystem cache metadata loading has to learn the size of every cache file. Previously this was a stat per 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, loadMetadataForKey reads the size straight from the file name and skips the stat.

Backward compatible and crash safe:

  • Legacy <offset> files (written by older versions) and files left by a download interrupted before the rename are still loaded — by falling back to a stat.
  • 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.

FileSegment tracks whether its on-disk file carries the size suffix (hasSizeInFileName) so getPath always returns the real name, including across detach/removal. Reporting paths (system.filesystem_cache.cache_path, SYSTEM SYNC FILESYSTEM CACHE) now use the path captured in FileSegmentInfo rather than recomputing it from the offset.

Validated with test_parallel_cache_loading_on_startup, test_system_sync_filesystem_cache, and a new test_cache_file_size_in_name (on-disk naming + backward-compatible loading of legacy <offset> files).

Related: #107414
Related: #107416

Changelog category (leave one):

  • Performance Improvement

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 a stat per file. Loading of cache files written by older versions remains supported.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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]>
@alexey-milovidov
alexey-milovidov force-pushed the filecache-size-in-filename branch from f2ed23b to 34b3567 Compare June 13, 2026 20:16
@alexey-milovidov
alexey-milovidov changed the base branch from filecache-load-avoid-redundant-opendir to master June 13, 2026 20:16
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [acd8886]

Summary: ✅


AI Review

Summary

This PR encodes fully downloaded filesystem-cache segment sizes into the on-disk file name so startup can restore metadata without a stat per file, and it fixes several rename/path-consistency problems found during review. The rename/load path now looks substantially better, but one corruption-recovery gap still remains in the steady-state cached-read loop, and the Performance Improvement claim is still missing focused startup-time evidence.

Findings

⚠️ Majors

  • [src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp:1163-1218, 1520-1624] [dismissed by author -- https://github.com/Filesystem cache: encode segment size in the cache file name #107415#discussion_r3510465314] The new short-file bypass only runs while building a cached read state. Once a DOWNLOADED _<size> segment has already been opened successfully, updateReadStateIfNeeded keeps reusing the same cached descriptor until the segment ends, so truncating the file after the first cached read still falls through to the existing zero-bytes-on-an-unfinished-range LOGICAL_ERROR path instead of rerouting to REMOTE_FS_READ_BYPASS_CACHE. I still consider this real because the current code has no size revalidation in the steady-state cached-read loop, while the new comments/tests describe truncated cache files as self-healing rather than surfacing a server-bug-class exception.
Tests
  • ⚠️ The Performance Improvement category still lacks direct proof for the promised startup win. The change clearly removes one stat per cache file in loadMetadataForKey, but the PR still has no before/after startup measurement or focused benchmark at realistic cache-file counts to quantify that improvement.
  • ⚠️ [tests/integration/test_merge_tree_check_part_with_cache/test.py:25-31] still skips debug/sanitizer builds entirely, so the changed CHECK TABLE path is not exercised in the configurations where a cache-corruption LOGICAL_ERROR becomes fatal. A focused repro that truncates a cache file after the first cached buffer has been opened would close the remaining gap above.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 13, 2026
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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@alexey-milovidov
alexey-milovidov requested a review from kssenii June 13, 2026 21:54
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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
  • StressHouse run: 4bcae560-9fe2-4cb4-b6e2-2184e87b5771
  • MIRAI run: 4809c1a1-f569-4ae6-a7c0-7ac863845e62
  • PR check IDs:
    • clickbench_703966_1784177858
    • clickbench_703979_1784177858
    • clickbench_703985_1784177858
    • tpch_adapted_1_official_703991_1784177858
    • tpch_adapted_1_official_703997_1784177858
    • tpch_adapted_1_official_704002_1784177858

alexey-milovidov and others added 2 commits June 14, 2026 02:33
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 67988ab to address the review feedback: setDownloadedUnlocked now renames the cache file (<offset> → <offset>_<size>) before publishing the DOWNLOADED state. Previously a throwing fs::rename could leave a DOWNLOADED segment with a stale downloader_id (both callers reset the downloader only after setDownloadedUnlocked returns), violating assertCorrectness. With the reorder, a rename failure leaves the segment DOWNLOADING (downloader still set, a valid state), so the completion stays consistent and is retried.

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 future_error shutdown race unrelated to this PR; a separate tracking issue/fix would be welcome if one does not already exist.

@groeneai

Copy link
Copy Markdown
Collaborator

@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: std::promise<void>::~promise() (future:509) below std::__shared_ptr_emplace<std::packaged_task<void()>>::__on_zero_shared() (future:1112), which is exactly the make_shared<packaged_task<void()>> that threadPoolCallbackRunnerUnsafe (src/Common/threadPoolCallbackRunner.h) creates. Only the outermost frame differs (the last shared_ptr holder at teardown; on your run, KeeperRequestDispatcherOld::shutdown()::$_0). On ThreadPool::finalize() the worker drains the queue and destroys a still-queued task unrun, so ~promise() stores a broken-promise std::future_error (a std::logic_error) and the waiter's tryLogCurrentException aborts in debug/sanitizer builds.

PR #107383 replaces the bare packaged_task with an explicit-promise task whose destructor always satisfies the promise with Exception(CANNOT_SCHEDULE_TASK) on the drop path, so future.get() returns an ordinary catchable error instead of aborting, regardless of which lambda holds the last ref. Mirrors merged precedent #73629 (same fix for the sibling ThreadPoolCallbackRunnerLocal).

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.

@kssenii kssenii self-assigned this Jun 14, 2026
alexey-milovidov and others added 2 commits June 14, 2026 14:45
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]>
alexey-milovidov and others added 3 commits June 16, 2026 14:07
…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]>
alexey-milovidov and others added 2 commits June 18, 2026 04:54
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review Block: pushed 585e33077e6, which invalidates the pre-rename <offset> name in OpenedFileCache right after a successful rename to <offset>_<size> in renameToIncludeSizeInNameUnlocked.

The bug was real. After the rename, removeFileSegmentImpl computes the path via getFileSegmentPath, which honors hasSizeInFileName() and therefore invalidates only the current <offset>_<size> name. A reader that opened the segment while it was still downloading (named <offset>) leaves a live OpenedFileCache entry keyed by <offset>; that entry survived removal. A new segment created at the same key/offset is again named <offset> while it downloads, so a reader opening it could lock the stale weak_ptr and read from the removed segment’\s descriptor. Pre-PR this could not happen because the file kept the <offset> name for its whole lifetime, so removal invalidated exactly the name readers had cached.

The fix mirrors the existing invalidation in removeFileSegmentImpl (both getFlagsForLocalRead() and ... | O_DIRECT). Existing readers keep their shared descriptors (the inode is unchanged across the rename), so only future opens are affected. The FileSegment.cpp translation unit compiles cleanly with the change.

On the remaining ⚠️ about startup-time performance evidence: that thread already records the rationale (a direct per-file stat removal whose win scales with file count and per-stat latency) and leaves the decision on whether to add a dedicated CI benchmark to @alexey-milovidov, since such a benchmark would be dominated by I/O noise on shared runners.

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Jul 12, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 223/262 (85.11%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 16, 2026
Merged via the queue into master with commit 427f5d8 Jul 16, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the filecache-size-in-filename branch July 16, 2026 15:49
CheSema added a commit that referenced this pull request Jul 16, 2026
#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]>
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… 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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…n-filename

Filesystem cache: encode segment size in the cache file name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants