Skip to content

Check data parts on local disks with O_DIRECT - #133447

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:part-check-direct-io
Nov 23, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:part-check-direct-io

Conversation

@groeneai

@groeneai groeneai commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #133431

Changelog category (leave one):

  • Improvement

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

The check of a data part on a local disk (CHECK TABLE, and the check of a part that failed to be read) now reads its files with O_DIRECT, bypassing the OS page cache, so wrong data in the page cache no longer makes a healthy part look broken and get detached. It is controlled by the new MergeTree setting check_part_use_direct_io (enabled by default). When a part that failed to be read passes this check, a warning is logged and the new ProfileEvent PartCheckPassedAfterPageCacheReadError is incremented. Closes #133431.

Description

When a query fails to read a part with CHECKSUM_DOESNT_MATCH, ReplicatedMergeTreePartCheckThread re-checks it with checkDataPart. On a local disk the check read through the query's OS page cache, so wrong cached bytes made a healthy part look broken: detached and removed from Keeper.

Changes:

  • checkDataPart reads the files of a full part on a local disk (also an encrypted disk over it) with O_DIRECT and 4 MiB buffers, opening each file through the disk with its size as the read hint. Column files are looked up in the directory listing, without reading the skp_idx.packed index or a column sample (both buffered). Packed parts, object storages (also local_blob_storage) and the part just written by OPTIMIZE ... DRY RUN are read as before.
  • New MergeTree setting check_part_use_direct_io, default true; compatibility below 26.12 restores the buffered check.
  • When a check requested after a failed read of the part passes with O_DIRECT, it logs a warning and increments PartCheckPassedAfterPageCacheReadError.
  • Test failpoint file_read_corrupt_data_without_direct_io corrupts buffered reads of .bin files.

Not included: the optional POSIX_FADV_DONTNEED, so queries can fail on the part until the kernel evicts the wrong pages; the part is not detached.

Validation: a stateless test checks that CHECK TABLE on MergeTree and ReplicatedMergeTree opens every file with O_DIRECT (buffered with the setting off). An integration test (also a part with JSON and no columns_substreams.txt) makes a SELECT fail with CHECKSUM_DOESNT_MATCH through the failpoint: the part check passes, the part stays active and in Keeper; with the setting off (a manual run) the part is detached.

Cost, CHECK TABLE of 4.66 GiB in 16 parts on local NVMe (debug build, CPU-bound): buffered 422-738 ms cold, 225-229 ms warm, O_DIRECT 191-256 ms. O_DIRECT always reads the device, so on slow storage with a warm page cache the check can be slower.


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

Version info

  • Merged into: 26.12.1.300-master (included in 26.12 and later)

groeneai and others added 4 commits November 21, 2026 20:22
When a query fails to read a part with a checksum error, the replicated
part check thread re-verifies the part with checkDataPart. On a local disk
that check read the files through the kernel page cache, the same cache the
failed query read from, so wrong data in the page cache made a healthy part
look broken: it was detached and removed from Keeper (ClickHouse#133431).

checkDataPart now reads the files of a full part on a `local` disk with
O_DIRECT and 4 MiB buffers, controlled by the new MergeTree setting
`check_part_use_direct_io` (default true; `compatibility` restores the
buffered check). O_DIRECT is selected by the read hint, so every file is
opened with its size as the hint: the previous no-hint reads would never
use O_DIRECT whatever `direct_io_threshold` says (ReadPipeline uses
`read_hint.value_or(0)`). A missing file keeps no hint, so it still fails
at open with the same error code. Packed parts and object storages
(including `local_blob_storage`) keep their settings: they read the members
in their own way.

The broken part callback now says whether a query failed to read the part
(the reader path of reportBrokenPart) or the part merely sits on a broken
disk. When a check requested because of a read error passes, and it
created O_DIRECT buffers in this thread with no fallback to buffered IO,
the check thread logs a warning and increments the new ProfileEvent
`PartCheckPassedAfterPageCacheReadError`. A read error reported while the
part's check is already running is merged into that check, as before, and
gives no warning.

Tests: a stateless test asserts that CHECK TABLE on MergeTree and
ReplicatedMergeTree opens every file of the part with O_DIRECT, and with
the setting off reads buffered. An integration test uses the new test
failpoint `file_read_corrupt_data_without_direct_io`, which corrupts
buffered reads of `.bin` files, to make a SELECT fail with
CHECKSUM_DOESNT_MATCH; the part check passes, the part stays active and in
Keeper, and the warning and ProfileEvent appear. The failpoint is limited
to `.bin` files because it is process-wide: corrupting the server's reads
of `/sys/fs/cgroup/cpu.max` makes AsynchronousMetrics throw a
std::invalid_argument, which aborts a debug server.

Closes ClickHouse#133431

Co-Authored-By: Claude Opus 5.5 <[email protected]>
checkDataPart returns empty checksums when the check stops at a
retryable error (for example MEMORY_LIMIT_EXCEEDED). The O_DIRECT
counter has already grown by then, so checkPartImpl logged the
page-cache warning and incremented PartCheckPassedAfterPageCacheReadError
for a part that was not fully verified. Require non-empty checksums,
the same signal DataPartsExchange uses.

Also describe after_read_error as "reading the part failed": merges,
mutations and sending a part to a replica report it too, not only
queries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The direct-I/O part check opened every file through the part storage. For a
name starting with `skp_idx_` the storage first resolves the `skp_idx.packed`
overlay, and the first lookup on a storage object loads the archive index with
a buffered read (`DataPartStorageOnDiskBase::getSkipIndicesPackedReader`,
`ReadSettings{}`). A part with skip indices both in `skp_idx.packed` and in a
standalone `skp_idx_*` file (`packed_skip_index_max_bytes` keeps large index
files standalone) whose index was not loaded yet thus still read the page cache
during the check, and wrong cached index bytes could still make a healthy part
look broken. A fetched part is in that state: it is loaded without the
consistency check, which is what reads the index for parts loaded at ATTACH or
startup.

In the direct-I/O branch, open the physical file through the disk of the part
storage with its size as the read hint. Names that are not physical files keep
the old path, so the errors for missing files are unchanged.

The stateless test gets a case with such a layout on a fetched replica: String
columns only (in debug builds the load of a part with a numeric column reads the
index), `prewarm_mark_cache = 0`, `replace_long_file_name_to_hash = 0` and
`index_granularity_bytes` pinned so randomized MergeTree settings keep the
layout and the index unread. Without this change the case reads one buffer
through the page cache in 20 of 20 randomized runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a comment restating the after_read_error parameter name and one narrating why the direct-I/O settings are set.

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

groeneai commented Nov 21, 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; 7 findings over 6 rounds) plus my own review (3 findings kept).

# Sev Finding Verdict Evidence / action
1 ⚠️ A check that stops at a retryable error (checkDataPart returns empty checksums) still logged the page-cache warning and counted PartCheckPassedAfterPageCacheReadError AGREE, fixed @ efcdf98 the warning now requires non-empty checksums
2 💡 "a query failed to read" in the flag, ProfileEvent and setting docs; merges and part sends set the flag too AGREE, fixed @ efcdf98 wording "failed to be read"
3 ⚠️ A read error reported while a check of the same part is already running gives no warning DISAGREE the request is folded into it by the existing dedup in enqueuePart, the check result is correct, and while the wrong pages stay cached the next failed read re-enqueues the part with the flag
4 ⚠️ The integration test could be a stateless test DISAGREE the failpoint corrupts every buffered .bin read of the server process; the shared stateless server runs other tests and an embedded Keeper whose changelog_*.bin entries are read back at runtime (Changelog.cpp LogEntryStorage::getEntry)
5 ❌ On a part with skip indices both in skp_idx.packed and in standalone files, opening a standalone skp_idx_* file through the part storage loads the archive index through the page cache AGREE, fixed @ 028c42a in the direct-I/O path the check reads the files through the disk; 05842 covers this layout on a fetched part
6 💡 The warning attributes any non-retryable read error of the part, also a reader bug, to the page cache noted, not blocking wording of the issue's item 3; the text says "probably"
7 ❌ A user column whose name starts with skp_idx_ makes the check's stream lookup load the skp_idx.packed index through the page cache AGREE, fixed @ 2139b85 the direct-I/O check looks column streams up in the directory listing; 05842 covers it (22 O_DIRECT / 0 ordinary buffers, was 22 / 1)
8 ⚠️ No integration case with check_part_use_direct_io = 0 after a read error DISAGREE the setting is applied in isCheckedWithDirectIO, covered both ways by 05842 through the same checkDataPart overload the part check thread calls; the setting-off detach was measured manually
9 ⚠️ The setting description omits that packed parts are still checked through the page cache AGREE, fixed @ cc27a23 stated in the setting description
10 ⚠️ No test on an encrypted disk over a local disk DISAGREE measured: CHECK TABLE there opens every file with O_DIRECT (Wide 14, Compact 9, RMT 13; 0 ordinary) and passes; O_DIRECT reads of encrypted files are covered by 04669/04692

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05842_check_part_use_direct_io shows the read mode of CHECK TABLE on demand (13 of 13 part files buffered on master, 13 of 13 O_DIRECT with the fix). test_part_check_direct_io makes a SELECT fail with CHECKSUM_DOESNT_MATCH through a failpoint that corrupts buffered reads of .bin files, which triggers the part check every run.
b Root cause explained? The part check after a read error used a default ReadSettings, i.e. buffered reads through the same OS page cache the failed query read; drop_cache_and_check only covers disks with a ClickHouse filesystem cache. O_DIRECT is selected by the read hint, and checkDataPart passed none, so direct_io_threshold = 1 alone does nothing.
c Fix matches root cause? Yes. The check reads full parts on local disks with O_DIRECT and passes each file's size as the read hint. Without the hint (mutant) every file is read buffered again.
d Test intent preserved / new tests added? New stateless test (MergeTree and ReplicatedMergeTree, setting on/off, and a fetched part with skip indices both in skp_idx.packed and in a standalone file) and new integration test (read error, check passes, part kept, warning + ProfileEvent). No existing test changed.
e Both directions demonstrated? Stateless: fails on master (unknown setting; its "on" half reads 13 files buffered) and on a no-hint mutant; the fetched-part case fails 20/20 with random settings when the files are read through the part storage (one buffered read of the skp_idx.packed index); passes 50/50 with random settings. Integration: 5/5 with the fix; fails with the read hint removed and with the read-error flag removed; with check_part_use_direct_io = 0 the part is detached as broken (old behaviour).
f Fix is general across code paths? All file reads of the check go through one helper, including projections. It opens the physical file through the disk, not through the part storage, whose skp_idx_* lookup loads the skp_idx.packed index with a buffered read. Every caller of the public checkDataPart (part check thread, CHECK TABLE for both engines, checksum recalculation, OPTIMIZE ... DRY RUN) gets it. An encrypted local disk forwards the hint. Packed parts and object storages keep their own read paths.
g Fix generalizes across inputs (params/datatypes/wrappers)? Wide and Compact parts, projections, empty files (no buffer is created), missing files (no hint, so the open error is unchanged). A filesystem without O_DIRECT falls back to buffered reads, and the stateless oracle holds there too.
h Backward compatible? (maintainer-approved exception only) New MergeTree setting with an inline history record; compatibility 26.11 gives check_part_use_direct_io = 0 (measured). No format change.
i Invariants and contracts preserved? The check reads the same bytes and compares the same checksums; error codes for missing files are unchanged. The check queue invariant (parts_set matches parts_queue) is untouched: the flag is set on an existing entry under parts_mutex. The warning reads per-thread counters of the synchronous check only.

Session id: cron:clickhouse-impl-slot-5:20261121-195200

@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23b710d]

Summary: ✅


AI Review

Summary

Reviewed head 23b710d2e229f81edb3e90504add23c04bd6526f. The change makes checkDataPart verify full parts on local disks with O_DIRECT, adds a compatibility-controlled setting, and reports successful checks after read errors. No actionable findings remain. The previous blocker involving buffered reads of legacy dynamic-column prefixes is fixed in the current code and covered by the regression test.

Missing context / blind spots
  • ⚠️ Full CI at the reviewed head is still running, and no local ClickHouse build was available. The focused stateless test 05842_check_part_use_direct_io passes at this head. Both read-error integration cases passed before the merge from master; the head integration run remains the outstanding runtime check.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... labels Nov 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 23b710d2e with master 19f5e0ac8 (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

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

Job report

groeneai and others added 3 commits November 22, 2026 00:42
…t check

The stream lookup of a Wide part asked the part storage whether a column file
exists. For a name starting with `skp_idx_` the storage first loads the index of
`skp_idx.packed`, and it reads it with default `ReadSettings`, through the page
cache. So for a column named like `skp_idx_value` on a part whose archive index
was not read yet (a fetched part), the check still did one buffered read, and
wrong cached bytes there could make the check report a healthy part as broken.

Column files are never members of `skp_idx.packed`, so with `O_DIRECT` the check
now resolves the column streams against the part directory listing, through the
existing `Checksums` overloads of `getStreamNameOrHash` and
`getStreamNameForColumn`. Without `O_DIRECT` the lookup is unchanged.

`05842_check_part_use_direct_io` gets a `skp_idx_value` column in the fetched-part
case: before this commit `CHECK TABLE` created 22 `O_DIRECT` buffers and 1
ordinary one there, now 22 and 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rough the page cache

`isCheckedWithDirectIO` requires full part storage, so a part in packed storage
(`min_bytes_for_full_part_storage` > 0) keeps the buffered check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`createReadBufferFromFileBase` opens files with `O_DIRECT` only on Linux and
FreeBSD, so on macOS the check reads buffered and counts neither
`CreatedReadBufferDirectIO` nor `CreatedReadBufferDirectIOFailed`, and the
`*_on` rows of the test differ (`Fast test (arm_darwin)`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
…treams.txt

With `enumerate_dynamic_streams = false` the enumeration does not use the
column, but `getColumnSample` still deserialized the structure prefixes of
`JSON` and `Dynamic` columns with buffered metadata read settings. A page
cache read error there made the part check of a healthy legacy Wide part
fail, and the part was detached and removed from Keeper.

The integration test now also covers a Wide part with a `JSON` column and
no `columns_substreams.txt` (the layout written before 25.8).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The dry run checks the part that its own merge has just written, so the
data is in the page cache, mostly still dirty. Reading it with O_DIRECT
first forces the writeback and then reads the device: both DRY RUN
performance tests got slower (json_merge_shared_data_statistics +22.5%,
text_index_merge +15-28% on 21 queries). O_DIRECT protects existing
parts from being detached after a wrong page cache read; a failed dry run
check only fails the query, and the part is removed anyway.

checkDataPart gets allow_direct_io (default true), and the dry run passes
false. The test checks that the dry run reads through the page cache.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e22397e

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
AST fuzzer (amd_release, oracle) / AST fuzzer oracle mismatch trunk bug, not this PR: SELECT * FROM (SELECT * FROM (SELECT 1 AS a, 'x' AS b) INNER JOIN (SELECT 1 AS a, 'y' AS b) USING (a)) returns 1 x x on master 26.12.1.1 (unwrapped: 1 x y), the duplicate-name collision #107127 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261122-083020

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status of the two red checks on e22397e:

  • CH Inc sync (build failed): the new after_read_error argument of MergeTreeData::BrokenPartCallback broke the private-only StorageSharedMergeTree, which passed a one-argument no-op callback (no matching constructor for initialization of 'MergeTreeData', the only error in all four failed builds). Adapted it in the sync branch.
  • AST fuzzer (amd_release, oracle): the subquery wrap oracle mismatch on duplicate column names from JOIN ... USING, unrelated to this change and tracked by Fix wrong result for duplicate-named subquery columns wrapped in SELECT * #107127.

Merged master (23b710d, no conflicts; the changed translation units compile) to re-run the CI.

@stresshouse

stresshouse Bot commented Nov 23, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

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

no significant changes detected. K_source=4 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: fa6783c9-a91e-4e23-850a-06d818d57308
  • MIRAI run: 3eb065d4-392d-4720-95fd-e89a43fd9daa
  • PR check IDs:
    • clickbench_896185_1795398522
    • clickbench_896191_1795398521
    • tpch_adapted_1_official_896217_1795398522
    • tpch_adapted_1_official_896227_1795398521

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status at 23b710d: all checks are green, the branch contains a master merge from 2026-11-23, and there are no unresolved review threads, so nothing was pushed.

One thing inside a green check: Stress test (amd_debug) reports Possible deadlock on shutdown (see gdb.log). It is unrelated to this change: the main thread sleeps in ReadWriteBufferFromHTTP::waitBeforeRetry under RestCatalog::loadConfig ← DatabaseDataLake::getTablesIterator ← DatabaseCatalog::shutdownImpl (the listing of tables for the Buffer flush before shutdown, with an unreachable catalog), and no thread is in the part check. Fix: #133669

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 23, 2026
Merged via the queue into ClickHouse:master with commit 797be5a Nov 23, 2026
195 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 23, 2026
@alexbakharew

Copy link
Copy Markdown
Contributor

On an EBS volume this makes CHECK TABLE several times slower when the table fits in the page cache. Our nightly benchmark checks a table of about 85 GiB there, and the two checks went from 126-171 s to 582 s and 700 s (about 125 MiB/s, the default gp3 throughput), while on a local NVMe the difference is small (1.22 s vs 1.36 s for 2.93 GiB). The issue says check_part_use_direct_io is there to turn this off where O_DIRECT is slow, so maybe the setting description could say that too.

@groeneai @clickgapai

@clickgapai

Copy link
Copy Markdown
Contributor

@alexbakharew The fix from #133447 isn't in yet: its test fails the structural check.

  • 05836_ttl_cast_probe_representative_columns.sql creates ttl_probe_variant_overflow without a DROP TABLE IF EXISTS first.
  • Re-runs and parallel runs fail with "table already exists".

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I'll send a PR that adds this to the check_part_use_direct_io description (turn it off where direct reads are slower than the page cache, e.g. on EBS when the table fits in memory) and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I opened #134174. It adds a paragraph to the check_part_use_direct_io description: disable the setting where direct reads are slower than reads through the page cache, for example on an Amazon EBS volume when the table fits in the page cache. The default is unchanged.

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-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... pr-improvement Pull request with some product 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.

Part check should read data with O_DIRECT, bypassing the OS page cache

5 participants