Skip to content

Fix ssd_cache dictionaries with the same PATH returning each other's values - #122465

Merged
nihalzp merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-ssd-cache-dictionaries-same-path
Nov 11, 2026
Merged

nihalzp merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-ssd-cache-dictionaries-same-path

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

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 ssd_cache and complex_key_ssd_cache dictionaries that share a PATH returning each other's values from dictGet, and Cache data corrupted errors in queries that run during SYSTEM RELOAD DICTIONARY of an SSD cache dictionary. Each dictionary instance now creates its own cache file instead of truncating the file another instance may still be reading.

Description

On 26.8.10.6 and 26.3.33.24, two ssd_cache dictionaries created with the same PATH silently return each other's values from dictGet. The documented layout example uses a fixed PATH, so copies of it share one file. No public issue exists; reproduction below.

Root cause: the SSDCacheFileBuffer constructor opens <PATH>.bin with O_TRUNC. A second storage on that path truncates the file the first one still reads and writes its own blocks from block 0. The first storage's index still points at those offsets, and a well-formed foreign block has a valid checksum, so the lookup returns the other dictionary's value. SYSTEM RELOAD DICTIONARY does the same to running queries that still use the previous instance.

Change: the constructor creates and preallocates a new file under a unique temporary name (O_EXCL), then renames it over <PATH>.bin, or over the file a symlink there points to. A storage that still has the previous file open keeps its own inode, and a new storage still starts empty. This one constructor opens the file for both key types. The previous file stays allocated while its instance is alive, so a reload needs FILE_SIZE of free disk space, and the file's directory must be writable by the server. Rejecting a PATH already in use would need an owner identity that survives SYSTEM RELOAD and CREATE OR REPLACE, where two instances of one dictionary share the path.

Validation: the new test (simple and complex keys) fails on master with 435 and 419 of 500 values wrong and passes with the fix in 50 of 50 randomized runs; the existing SSD cache tests pass. With 12 concurrent readers and SYSTEM RELOAD DICTIONARY in a loop for 180 s, 102 of 679 queries failed with CORRUPTED_DATA on master; on the fix, none failed with it or returned a wrong value.

Reproduction
CREATE TABLE src_a (id UInt64, value UInt64) ENGINE = TinyLog;
CREATE TABLE src_b (id UInt64, value UInt64) ENGINE = TinyLog;
INSERT INTO src_a SELECT number, 1000 + number FROM numbers(500);
INSERT INTO src_b SELECT number, 9000000 + number FROM numbers(500);
CREATE DICTIONARY dict_a (id UInt64, value UInt64 DEFAULT 0) PRIMARY KEY id SOURCE(CLICKHOUSE(TABLE 'src_a'))
LIFETIME(MIN 1000 MAX 2000) LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 PATH '/var/lib/clickhouse/user_files/shared'));
CREATE DICTIONARY dict_b (id UInt64, value UInt64 DEFAULT 0) PRIMARY KEY id SOURCE(CLICKHOUSE(TABLE 'src_b'))
LIFETIME(MIN 1000 MAX 2000) LAYOUT(SSD_CACHE(BLOCK_SIZE 4096 FILE_SIZE 65536 WRITE_BUFFER_SIZE 4096 PATH '/var/lib/clickhouse/user_files/shared'));
SELECT sum(dictGet('dict_a', 'value', number)) FROM numbers(500) FORMAT Null;
SELECT sum(dictGet('dict_b', 'value', number)) FROM numbers(500) FORMAT Null;
TRUNCATE TABLE src_a; TRUNCATE TABLE src_b;
SELECT arraySort(groupArray(dictGet('dict_a', 'value', number))) FROM numbers(3);  -- [9000000,9000001,9000002], dict_b's values

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

Version info

  • Merged into: 26.11.1.1921-master (included in 26.11 and later)
  • Backported to: 26.3.64.2

groeneai and others added 4 commits September 26, 2026 09:22
…values

SSDCacheFileBuffer opened <PATH>.bin with O_TRUNC. When a second storage was
created on a path whose file another live storage still had open, it
truncated that file and wrote its own blocks from block 0. The first
storage's index still pointed at those offsets, and the block checksum was
valid because the blocks were well-formed blocks of the other storage, so
dictGet returned the other dictionary's values without an error. Two
instances of one dictionary overlap the same way during SYSTEM RELOAD
DICTIONARY, where queries still reading the previous instance then failed
with CORRUPTED_DATA.

Create the file under a unique temporary name with O_EXCL and rename it over
<PATH>.bin instead. A storage that still has the previous file open keeps
reading its own inode, which is freed when its last descriptor closes. Every
storage still starts with an empty cache.

Rejecting a PATH that is already in use was not chosen: it needs an owner
identity that survives SYSTEM RELOAD and CREATE OR REPLACE, where two
instances of one dictionary briefly share the path, and the new instance
would still truncate the file under the old one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cache file was created under a temporary name next to <PATH>.bin and
renamed over <PATH>.bin. rename(2) does not follow a symlink at its target,
so a link at <PATH>.bin (for example to a file on another disk) was replaced
by a regular file, while the old in-place open followed it. The link chain is
now resolved first (at most 40 links, then ELOOP, as open does), and the new
file is created in the directory of the file the chain points to and renamed
over that file, so the link stays and its target becomes the cache.

The temporary name is now a fixed-length ssd_cache_<seed>.tmp instead of
<PATH>.bin.<seed>.tmp, so a <PATH>.bin that fits NAME_MAX no longer fails
with ENAMETOOLONG.

The test also covers a dangling relative link at the cache file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rename(2) checks only the permissions of the directory, so an existing
<PATH>.bin, or the file a symlink there points to, was replaced even when the
server could not open it for reading and writing, where the old in-place
O_RDWR open failed with EACCES and left the file intact. The constructor now
checks read and write access to that file before creating anything, and any
error other than ENOENT fails with CANNOT_OPEN_FILE as before.

The symlink loop now stops at a path that names a directory (a link whose
target ends in '/'), so such a link fails as it did before instead of
resolving one level too deep. It also uses FS::isSymlinkNoThrow, so an lstat
error such as ENAMETOOLONG reaches the access check and keeps
CANNOT_OPEN_FILE instead of surfacing as a std::filesystem error.

The error for a failed open of the temporary file now also names the file
it was going to replace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The symlink comment now states why the link is resolved (rename(2) overwrites a symlink) instead of describing the loop, and the access comment no longer says rename(2) checks only the directory's permissions, which is not true in a sticky directory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 26, 2026
@groeneai

groeneai commented Sep 26, 2026 •

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

An independent model reviewed this before publication (engine: codex; 5 findings over 3 rounds, with my own cold review each round) and again after the AI review (2 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ rename replaced a symlink at <PATH>.bin with a regular file, where the in-place open followed the link AGREE, fixed @ f1235c2 The link chain is resolved first and the new file is renamed over its target. A cycle still fails with ELOOP. Covered in 05258.
2 💡 The temporary name grew with the configured basename, so a name close to NAME_MAX failed AGREE, fixed @ f1235c2 The temporary name now has a short fixed length and sits in the same directory.
3 ⚠️ rename needs only a writable directory, so it replaced an existing file the server cannot write, which the in-place open refused AGREE, fixed @ dbdc5b0 An existing target the server cannot open for reading and writing is refused with CANNOT_OPEN_FILE, as before. Proven with a manual non-root probe. A stateless test cannot assert it, because a server running as root passes every permission check.
4 💡 A link whose target ends in / resolved one level too deep and created a file inside that directory AGREE, fixed @ dbdc5b0 Resolution stops at a path that names a directory, so it fails as before.
5 💡 The replacement file gets the server's default mode, not the mode of a file an admin created in advance noted, not changed The server's umask (027 by default) applies, as it does to every file the server creates, including this one whenever it does not exist yet.
6 💡 An existing file in a directory the server cannot write, or a bind-mounted file, can no longer be the cache file noted, not changed Every instance needs its own file under the same name, so the directory must be writable. The description says so.
7 💡 An open that fails after the kernel created the file (O_DIRECT on a file system without it) leaves the temporary file behind noted, not changed Only reachable on a file system where the cache can never load. The leftover file is empty.
8 💡 A FIFO, socket or device node at the target that the server can read and write is replaced, where the in-place open failed and left it alone noted, not changed Needs a special file named *.bin under the cache path, or a symlink to one. On such a target the cache never loaded before this change.
9 ⚠️ AI review: rename published the new file before the preallocation, so a SYSTEM RELOAD DICTIONARY without FILE_SIZE of free space left the failed attempt's partial allocation at <PATH>.bin AGREE, fixed @ 4072d8b The file is renamed only after the preallocation succeeds and is removed if it fails. On a 64 MiB ext4 file system with a 40 MiB cache, a failed reload used to leave 0 bytes free; now <PATH>.bin and the free space stay as they were.
10 💡 An abrupt termination during the preallocation leaves the temporary file behind, now at full size noted, not changed Needs a kill inside the fallocate call, which takes under 5 ms for 4 GiB on XFS and ext4. The leftover is named ssd_cache_<n>.tmp.
11 💡 On FreeBSD, posix_fallocate returns its error instead of setting errno, so the < 0 check misses a failure noted, not changed Unchanged code, same on master. Honoring it would make the load fail wherever the file system does not support preallocation (EINVAL), so it needs its own change.

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

Session ids: cron:clickhouse-review-slot-49:20260926-192500, cron:clickhouse-maint-slot-13:20260926-205300

@groeneai
groeneai requested review from nihalzp and vdimir September 26, 2026 20:08
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dead399]

Summary: ✅


AI Review

Summary

The PR isolates ssd_cache and complex_key_ssd_cache storage instances by replacing the cache file with a newly allocated inode, protecting existing readers when dictionaries share a PATH or reload. No unresolved actionable findings remain. The previous preallocation failure finding is fixed, and the new regression test passes in the latest CI report.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 26, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). label Sep 26, 2026
The new cache file was renamed over <PATH>.bin before the last constructor
steps that can fail (F_NOCACHE on macOS and the preallocation). A
SYSTEM RELOAD DICTIONARY without FILE_SIZE of free space therefore failed
after <PATH>.bin already named the new file. The old instance kept working
on its unlinked inode, but <PATH>.bin was left holding whatever the failed
preallocation had reserved: with a 40 MiB cache on a 64 MiB ext4 file
system that was all remaining space, so the file system stayed at 0 bytes
free and an unrelated 8 MiB write failed with ENOSPC.

The new file is now renamed last and removed if any step before or at the
rename fails, so a failed reload leaves <PATH>.bin and the free space as
they were.

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

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dead399cf with master 4d1bce945 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c6e4b71cf; 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.

Object file sizes

4 object files changed (+17.89 KiB total), 0 added.

Object file Master PR Δ
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/registerCacheDictionaries.cpp.o 1.00 MiB 1.02 MiB +17.88 KiB (+1.74%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4072d8b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / optimize_time_filter_with_preimage #6 dashboard confirmed_regression: client_time 0.4222 -> 0.5393 s (+27.7%), which the shard's own report calls only unstable. #6 is the Date month baseline arm: it runs with optimize_time_filter_with_preimage = 0, a single-threaded count() scan of a MergeTree table that never touches a dictionary, while this diff only changes how an SSD cache dictionary creates its cache file. In the last 7 days the same query was reported slower on 65 other pull requests and unstable on 128 on arm, true master included #122156 (mine, open), which removes this arm together with the other two = 0 baselines
Mergeable Check, PR rollups, red only because of the row above #122156 (mine, open)

All 169 check runs completed (129 pass, 39 not selected, 1 red), Finish Workflow is green and
CH Inc sync passed. CIDB has no FAIL or ERROR test row on this head. The shard's 4 too long
and 2 unstable are informational: neither fails a shard on its own.

Session id: cron:our-pr-ci-monitor:20260927-023024

@nihalzp nihalzp self-assigned this Nov 11, 2026
@nihalzp
nihalzp added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ClickHouse:master with commit 74b1a6e Nov 11, 2026
179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 11, 2026
@nihalzp nihalzp added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 11, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 11, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 11, 2026
Backport #122465 to 26.10: Fix `ssd_cache` dictionaries with the same `PATH` returning each other's values
clickhouse-gh Bot added a commit that referenced this pull request Nov 11, 2026
Backport #122465 to 26.9: Fix `ssd_cache` dictionaries with the same `PATH` returning each other's values
clickhouse-gh Bot added a commit that referenced this pull request Nov 12, 2026
Backport #122465 to 26.8: Fix `ssd_cache` dictionaries with the same `PATH` returning each other's values
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
… the same `PATH` returning each other's values
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
… the same `PATH` returning each other's values
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
…h the same `PATH` returning each other's values
robot-ch-test-poll3 added a commit that referenced this pull request Nov 13, 2026
Cherry pick #122465 to 26.3: Fix `ssd_cache` dictionaries with the same `PATH` returning each other's values
robot-clickhouse added a commit that referenced this pull request Nov 13, 2026
…`PATH` returning each other's values
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
… `PATH` returning each other's values
nihalzp pushed a commit that referenced this pull request Nov 14, 2026
nihalzp added a commit that referenced this pull request Nov 14, 2026
Backport #122465 to 26.3: Fix `ssd_cache` dictionaries with the same `PATH` returning each other's values
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-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

6 participants