Skip to content

Fix the userspace page cache of local disks returning a removed file's data for a new file at the same path - #128738

Merged
antonio2368 merged 3 commits into
ClickHouse:masterfrom
groeneai:local-disk-page-cache-file-version
Nov 3, 2026
Merged

antonio2368 merged 3 commits into
ClickHouse:masterfrom
groeneai:local-disk-page-cache-file-version

Conversation

@groeneai

@groeneai groeneai commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113617
Related: #128715

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed the userspace page cache of local disks (use_page_cache_for_local_disks) returning the data of a removed file for a new file written at the same path, for example a MergeTree part written again after TRUNCATE and DETACH/ATTACH TABLE.

Description

On 26.3.33.24 (LTS), 26.8.21.12 and 26.10.2.103, with page_cache_max_size > 0, use_page_cache_for_local_disks = 1 and local_filesystem_read_method = 'pread', a MergeTree part written again at the same path after TRUNCATE + DETACH/ATTACH TABLE (or DETACH PART) reads the previous part's data: sum(x) returns the old part's sum, or the query fails with CHECKSUM_DOESNT_MATCH when old and new 1 MiB blocks mix. No related open issue found.

PageCache.h requires a new file_version whenever a file's contents change, but DiskLocal::prepareRead keyed the cache by the path only.

The fix passes a version built from the stat that prepareRead already makes: modification time with nanoseconds, inode and size (the token StorageFile and LocalObjectStorage already use; the two helpers move from StorageFile.cpp to Common/filesystemHelpers unchanged in the first commit). A same-size rewrite within one timestamp tick, or within one second on filesystems with whole-second timestamps, can keep that token, so a file modified in the last 3 seconds gets a version of its own: the read still goes through the page cache, but its blocks are not shared. Files older than 3 seconds keep a stable version, so their hit rates are unchanged.

The mmap cache is not affected: every removal of old parts clears it. The uncompressed and text index caches have the same path-reuse problem; #128715 fixes them.

Validation: the new test fails on master (5050 three times) and passes with the fix, 50/50 runs. A size-only version makes it fail again; dropping the 3-second rule reproduces the stale read 10/10 on an ext4 filesystem with whole-second timestamps, while the fix is correct 10/10.


Workflow [PR]
Sync PR [sync-upstream/pr/128738]

Version info

  • Merged into: 26.11.1.1201-master (included in 26.11 and later)

groeneai and others added 3 commits November 2, 2026 16:56
`computeFileCacheVersionToken` and `isFileCacheVersionTokenSettled` move
from `StorageFile.cpp` to `Common/filesystemHelpers` unchanged, so that the
local disk can build a page cache file version from them in the next commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`DiskLocal::prepareRead` registered the page cache with the path only, so
the file version was empty. `PageCache.h` requires a new version whenever a
file's contents change. A MergeTree part written again under the same name
(block numbers restart after `TRUNCATE` + `DETACH`/`ATTACH TABLE`, or after
`DETACH PART`) produces files at the same paths, and every cached block of
the removed file was returned for the new one: wrong sums, or
`CHECKSUM_DOESNT_MATCH` when old and new blocks mix.

The version is now built from the `stat` that `prepareRead` already makes
(`computeFileCacheVersionToken`: mtime with nanoseconds, inode, size). A
same-size rewrite in the same timestamp tick (or the same second on
filesystems with whole-second timestamps) can keep that token, so a read of
a file modified in the last 3 seconds (`isFileCacheVersionTokenSettled`)
gets a process-unique version: it still goes through the page cache, but
its blocks are never shared with another read. Once a file has settled its
token is stable, so the hit rate for immutable MergeTree files is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the unsettled-token comment in DiskLocal::prepareRead to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (4 nits).

# Sev Finding Verdict Evidence / action
1 ❌ A descriptor shared by OpenedFileCache (path + flags key) could fill the new file's version with a removed file's bytes DISAGREE Needs a live reader of the removed file when the path is reused. MergeTree removes part files only when the part is uniquely owned (MergeTreeData.cpp:4923-4929), readers hold the part, and path reuse needs a table reload that Atomic refuses while the old instance is in use (DatabaseAtomic.cpp:489-499). Elsewhere that read is wrong even with the page cache off, an OpenedFileCache issue, not this change.
2 ⚠️ The test does not exercise the 3-second rule DISAGREE A token collision needs the same clock tick, a reused inode and the same size; SQL cannot build it on the runner's filesystems. Checked on ext4 with whole-second timestamps: without the rule 10/10 stale, with it 10/10 correct.
3 💡 Reads of files younger than 3 s add cells no other read uses AGREE Accepted price of the opt-in setting, stated in the description.
4 💡 Description overstated unchanged hit rates AGREE, fixed Description now says files older than 3 seconds.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261102-175700

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test body in clickhouse local --tmp with a 128 MiB page cache returns 5050 for every read after the rewrite on master (snapshot and a build of the first commit), every run.
b Root cause explained? DiskLocal::prepareRead registered the page cache with the path only (empty file_version), against the PageCache.h contract. A part written again at the same path keeps the old block keys, so the removed file's cached blocks are returned.
c Fix matches root cause? Yes. The version is supplied where the local-disk page-cache identity is built, from the existing stat; no bypass, no eviction.
d Test intent preserved / new tests added? New test 05483_local_disk_page_cache_file_rewritten_at_same_path.sh: part name proves path reuse, settled reads prove the version, PageCacheHits proves the cache is used. No existing test changed.
e Both directions demonstrated? Yes: base FAIL (5050 x3), fix OK, 50/50 runs. A size-only version fails the test; without the 3-second rule the stale read reproduces 10/10 on ext4 with whole-second timestamps (fix 10/10 correct).
f Fix is general across code paths? Encrypted over local delegates to DiskLocal::prepareRead; object storage already passes a strong token or uses unique blob paths; backups add no memory cache; both page-cache consumers read the version. Mmap cache: cleared on every part removal. Uncompressed/text index caches: #128715.
g Fix generalizes across inputs (params/datatypes/wrappers)? Same-size and larger rewrites, nanosecond and whole-second timestamp filesystems, missing or non-regular files (size unknown as before, cache unused), hard links (same token). Data types: N/A, byte-level cache.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format; page-cache keys are in memory only.
i Invariants and contracts preserved? Same StoredObject size and size estimate, still one stat per read, same cache path string; the counter only provides uniqueness (relaxed atomic).

Session id: cron:clickhouse-impl-self-slot-57:20261102-165400

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [73f5dd2]

Summary: ✅


AI Review

Summary

This PR versions local-disk userspace page-cache entries by file metadata, with unique versions for recently modified files, preventing stale reads when a path is reused. No actionable code findings at 73f5dd24eecd. The focused regression passed in Fast test.

Missing context / blind spots
  • ⚠️ No ClickHouse binary was available for an independent local rerun. The author reports baseline failures, 50 successful patched runs, and coarse-timestamp validation. CI's bugfix-validation jobs were dropped; Finish Workflow consequently reports missing validation. A successful validation rerun would close the remaining CI gap.
Final Verdict

Status: ✅ Approve. No code changes requested; CI validation remains pending.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @kssenii, could you review this and add the can be tested label so CI runs? DiskLocal::prepareRead registered local files in the userspace page cache with an empty file_version, so a MergeTree part written again at the same path read the removed file's cached blocks; it now passes a version built from the existing stat (mtime with nanoseconds, inode, size), made unique for files modified in the last 3 seconds.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-disk-abstractions Core disk abstractions: IDisk interface, DiskLocal, storage policies, volumes, disk management to... labels Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 73f5dd24e with master febcc9515 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

414 translation units recompiled, 3300 s compile time in total, 414 of them have a recent master baseline.

Job report

@antonio2368 antonio2368 self-assigned this Nov 3, 2026
@antonio2368
antonio2368 added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit bc3a3c0 Nov 3, 2026
527 of 531 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-disk-abstractions Core disk abstractions: IDisk interface, DiskLocal, storage policies, volumes, disk management to... pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants