Skip to content

Fix: filesystem cache disk IO error must not mark MergeTree parts as broken - #99386

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
tiandiwonder:fix-cache-disk-failure-broken-parts
Mar 25, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
tiandiwonder:fix-cache-disk-failure-broken-parts

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When starting a MergeTree table backed by S3 with a local filesystem cache, a disk IO error during cache write causes the part to be incorrectly marked as broken — even though the data in S3 is intact. ref #83823

Root cause: loadDataPart() calls isRetryableException() to decide whether to mark_broken or rethrow. Cache write IO errors were not recognized as retryable, so they fell into the mark_broken branch instead of propagating.

Core call chain:

loadDataPartWithRetries()
  └─ loadDataPart()
       catch (...) {
         if (isRetryableException()) throw;   // rethrow → no broken marking
         mark_broken();  ← BUG: cache IO error ends up here
       }
       └─ loadColumnsChecksumsIndexes()
            └─ CachedOnDiskReadBufferFromFile::writeCache()
                 └─ FileSegment::write() → local cache disk write → EIO

Fix

  • New error code CACHE_CANNOT_WRITE_TO_CACHE_DISK: thrown when local cache disk write fails
  • isRetryableException() now recognizes CACHE_CANNOT_WRITE_TO_CACHE_DISK → rethrows instead of marking broken → propagates to startup failure with a clear error message
  • New setting skip_cache_on_disk_failure (default false) in cache disk config: when true, cache write failures are silently bypassed and the read falls back to S3 — suitable for degraded-mode operation
  • Failpoint cache_filesystem_failure added for testing

Behavior

Scenario skip_cache_on_disk_failure=false (default) skip_cache_on_disk_failure=true
Cache disk IO failure Exception propagates → server refuses to start with clear error Silently bypassed, reads from S3, logs ERROR
Part marked as broken? No (core fix) No

Integration Tests

4 scenarios in tests/integration/test_cache_bypass_on_disk_failure/:

  • test_skip_cache_on_disk_failure_select: skip=true, failpoint during SELECT → succeeds, no broken parts
  • test_noskip_cache_on_disk_failure_select: skip=false, failpoint during SELECT → raises CACHE_CANNOT_WRITE_TO_CACHE_DISK
  • test_skip_cache_on_disk_failure_attach: skip=true, failpoint during ATTACH TABLE → part loads successfully, system.detached_parts empty
  • test_noskip_cache_on_disk_failure_attach: skip=false, failpoint during ATTACH TABLE → ATTACH fails, but system.detached_parts remains empty (core assertion of the bug fix)

Modified Files

File Change
src/Common/ErrorCodes.cpp New error code CACHE_CANNOT_WRITE_TO_CACHE_DISK
src/Common/FailPoint.cpp Register cache_filesystem_failure failpoint
src/Interpreters/Cache/FileCacheSettings.cpp New setting skip_cache_on_disk_failure (Bool, default false)
src/Interpreters/Cache/FileCache.h/.cpp Expose skipCacheOnDiskFailure()
src/Interpreters/Cache/FileSegment.cpp Failpoint injection before next() + fs::filesystem_error catch
src/Disks/IO/CachedOnDiskReadBufferFromFile.h/.cpp Rewrite writeCache() with skip logic + CACHED read fallback
src/Storages/MergeTree/checkDataPart.cpp isRetryableException() handles CACHE_CANNOT_WRITE_TO_CACHE_DISK
tests/integration/test_cache_bypass_on_disk_failure/ New integration test (4 scenarios)

Changelog category (leave one)

Bug Fix (MergeTree)

Changelog entry

Fix: filesystem cache disk IO error during MergeTree part loading no longer incorrectly marks parts as broken when S3 data is intact. Add skip_cache_on_disk_failure cache disk setting to control error propagation behavior.

🤖 Generated with Claude Code


Note

Medium Risk
Changes how filesystem cache write failures are surfaced/handled during MergeTree reads/part loading, which can affect startup/query behavior under cache-disk faults. Adds a new config flag to silently bypass cache writes, so misconfiguration could mask underlying storage issues.

Overview
Prevents filesystem cache disk write failures from being treated as non-retryable MergeTree part load errors by introducing new error code CACHE_CANNOT_WRITE_TO_CACHE_DISK and classifying it as retryable in checkDataPart.cpp.

Adds cache-level control via new setting skip_cache_on_disk_failure (default false) exposed on FileCache and plumbed through CachedOnDiskReadBufferFromFile so cache write IO errors can either fail fast with a clear exception or silently bypass cache writes and fall back to remote reads.

Improves testability/robustness by adding failpoint cache_filesystem_failure, hardening FileSegment::write() error handling (convert filesystem_error to ErrnoException), and adding integration tests covering SELECT/ATTACH behavior for both skip modes to ensure parts are not moved to system.detached_parts.

Written by Cursor Bugbot for commit ff7f9ff. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.4.1.240 (included in 26.4 and later)
  • Backported to: 26.3.33.45

…broken

When reading part metadata files (e.g. `checksums.txt`) at startup via
`CachedOnDiskReadBufferFromFile`, a local cache disk IO failure was
propagated up through `writeCache()` as a raw `ErrnoException`. This
caused `loadDataPart()` to treat it as data corruption and mark the part
as broken, even though the underlying S3 data was intact.

Fix the read path by:

- Adding a new `CACHE_CANNOT_WRITE_TO_CACHE_DISK` (code 771) error code
  that wraps cache disk IO errors from `writeCache()`.
- Adding a new `skip_cache_on_disk_failure` (Bool, default false) setting
  to `FileCacheSettings`. When true, cache write failures are silently
  bypassed (LOG_ERROR logged); when false (default), they are wrapped
  as `CACHE_CANNOT_WRITE_TO_CACHE_DISK` and propagated.
- Registering `cache_filesystem_failure` failpoint in `FileSegment::write`
  to enable injection-based testing.
- Adding `fs::filesystem_error` catch in `FileSegment::write` to ensure
  state machine consistency if `std::filesystem::file_size()` throws.
- Marking `CACHE_CANNOT_WRITE_TO_CACHE_DISK` as retryable in
  `isRetryableException()` so that `loadDataPart()` rethrows instead of
  marking the part broken, propagating the error to `loadDataPartWithRetries`
  which exhausts retries and causes a clear startup failure.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [152482f]

Summary: ✅


AI Review

Summary

This PR correctly targets a real issue (cache disk write failures should not mark MergeTree parts as broken), but there are two exception-construction bugs in FileSegment::write that can make errno-based handling nondeterministic and misclassify failures. Verdict: request changes until errno propagation is fixed.

Missing context

  • ⚠️ No CI logs/results were provided in this review task context.

Findings

❌ Blockers

  • [src/Interpreters/Cache/FileSegment.cpp:427] ErrnoException(EIO, ...) uses EIO as the ClickHouse error code and captures ambient errno as saved_errno. This makes e.getErrno() nondeterministic and can drive wrong recovery path decisions.
    • Suggested fix: construct with explicit errno (ErrnoException(<ch_code>, EIO, ...) or ErrnoException::throwWithErrno).
  • [src/Interpreters/Cache/FileSegment.cpp:483] ErrnoException(e.code().value(), ...) has the same issue: OS errno is placed into CH code, while saved_errno is not set from filesystem_error code.
    • Suggested fix: use overload with explicit errno (ErrnoException(<ch_code>, e.code().value(), ...)).

💡 Nits

  • [src/Interpreters/Cache/FileCacheSettings.cpp:55] Setting description says errors are propagated as startup failures, but the code path is also used by runtime reads (SELECT cache miss).
    • Suggested fix: reword to a runtime-safe description (for example, “errors are propagated to the caller”).

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsHistory.cpp ➖
Safe rollout ⚠️ Blocked by incorrect errno propagation in new exception paths
Compilation time ✅

Performance & Safety

  • The two ErrnoException constructor misuses are safety-relevant: they can produce incorrect errno classification and therefore incorrect fallback/error behavior under disk failure.

Final Verdict

  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix both ErrnoException construction sites in FileSegment::write to preserve explicit OS errno in saved_errno.
    • Update skip_cache_on_disk_failure description text to avoid startup-only wording.

@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Mar 13, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

throw ErrnoException(e.code().value(),
"Filesystem error in cache write ({}), current cache state: {}",
e.what(), getInfoForLogUnlocked(lk));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong ErrnoException constructor loses filesystem error code

Medium Severity

The fs::filesystem_error catch block creates ErrnoException(e.code().value(), fmt, args...) which matches the constructor ErrnoException(int code, FormatStringHelper, Args...). Here the POSIX errno (e.g. EIO=5) becomes the ClickHouse error code, while saved_errno is set to the ambient thread-local errno, not e.code().value(). When this exception reaches writeCache(), e.getErrno() returns the wrong value. If the ambient errno happens to be 28 (ENOSPC) or 122 (EDQUOT), a real disk IO error gets silently swallowed instead of propagating as CACHE_CANNOT_WRITE_TO_CACHE_DISK. The four-argument constructor ErrnoException(clickhouse_code, e.code().value(), fmt, args...) is needed to explicitly set both the ClickHouse error code and the errno.

Fix in Cursor Fix in Web

fiu_do_on(FailPoints::cache_filesystem_failure,
{
throw ErrnoException(EIO, "Failpoint: simulated cache disk IO failure");
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Failpoint ErrnoException doesn't set errno to EIO

Medium Severity

ErrnoException(EIO, "Failpoint: ...") matches the constructor ErrnoException(int code, T&& message) where EIO (5) becomes the ClickHouse error code and saved_errno captures the ambient thread-local errno — not EIO. So getErrno() returns a nondeterministic value. In FileSegment::write()'s catch handler, is_no_space_left_error could be incorrectly true if the ambient errno is 28 or 122, and writeCache() could silently swallow the error instead of throwing CACHE_CANNOT_WRITE_TO_CACHE_DISK. This makes all four integration tests nondeterministic. The four-argument constructor with explicit with_errno parameter is needed.

Fix in Cursor Fix in Web

DECLARE(Bool, write_cache_per_user_id_directory, false, "Internal ClickHouse Cloud setting", 0) \
DECLARE(Bool, allow_dynamic_cache_resize, false, "Allow dynamic resize of filesystem cache", 0) \
DECLARE(Double, max_size_ratio_to_total_space, 0, "Ratio of `max_size` to total disk space", 0) \
DECLARE(Bool, skip_cache_on_disk_failure, false, "If true, bypass filesystem cache operations silently on disk IO errors. If false (default), disk IO errors are propagated as startup failures.", 0) \

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.

Nit: the setting description says disk I/O errors are propagated as startup failures, but this code path is also hit during runtime reads (for example SELECT on cache miss). Please reword it to avoid implying this is startup-only.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 16, 2026
{
auto lk = lock();
setDownloadFailedUnlocked(lk);
throw ErrnoException(e.code().value(),

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.

⚠️ Same constructor issue here: ErrnoException(e.code().value(), ...) passes OS errno as the ClickHouse code and does not preserve e.code().value() as saved_errno (it captures ambient errno). As a result, downstream handling that relies on e.getErrno() can become incorrect. Please use the overload with explicit errno, e.g. ErrnoException(<ch_error_code>, e.code().value(), "...").


fiu_do_on(FailPoints::cache_filesystem_failure,
{
throw ErrnoException(EIO, "Failpoint: simulated cache disk IO failure");

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.

⚠️ ErrnoException(EIO, ...) uses EIO as the ClickHouse exception code, while saved_errno is taken from ambient errno. That makes e.getErrno() nondeterministic here and can misclassify errors (for example as no-space) depending on unrelated thread-local errno. Please construct with explicit errno: ErrnoException(<ch_error_code>, EIO, "...") (or throwWithErrno).

@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.70% 83.80% +0.10%
Functions 23.90% 23.90% +0.00%
Branches 76.20% 76.30% +0.10%

PR changed lines: PR changed-lines coverage: 74.80% (95/127, 0 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov

Copy link
Copy Markdown
Member

Thanks! Just resolve the last review comments, and we can merge...

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The code LGTM

@alexey-milovidov alexey-milovidov self-assigned this Mar 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Mar 25, 2026
Merged via the queue into ClickHouse:master with commit d068e28 Mar 25, 2026
159 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 25, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Backporting to fix 26.3 CI

@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 10, 2026
PedroTadim added a commit that referenced this pull request Sep 10, 2026
Resolve the three conflicts of the #99386 cherry-pick against 26.3.

`FailPoint.cpp` and `FileSegment.cpp` conflict only because 26.3 still has
`file_segment_pause_before_write`, which master removed: keep it and add the
new `cache_filesystem_failure` next to it.

`02344_describe_cache.reference` conflicts because `DESCRIBE FILESYSTEM CACHE`
prints one column per `FileCacheSettings` entry and 26.3 has a setting master
lacks (`dynamic_resize_lock_wait_ms`). Rebuild the row from 26.3's, inserting
the new `skip_cache_on_disk_failure` at the position the merged declaration
list gives it, between `max_size_ratio_to_total_space` and `use_split_cache`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 10, 2026
Cherry pick #99386 to 26.3: Fix: filesystem cache disk IO error must not mark MergeTree parts as broken
robot-clickhouse added a commit that referenced this pull request Sep 10, 2026
@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 Sep 10, 2026
PedroTadim added a commit that referenced this pull request Sep 11, 2026
Backport #99386 to 26.3: Fix: filesystem cache disk IO error must not mark MergeTree parts as broken
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 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants