Skip to content

Use pread when preadv2 with RWF_NOWAIT cannot be used, and recognize EPERM from it - #112945

Merged
alexey-milovidov merged 34 commits into
masterfrom
fix-preadv2-nowait-detection
Aug 13, 2026
Merged

alexey-milovidov merged 34 commits into
masterfrom
fix-preadv2-nowait-detection

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Related: #104634
Related: #49149
Related: #39753

The pread_threadpool read method hands every read off to a thread pool, unless the data is already in the page cache, which it checks with the preadv2 system call and the RWF_NOWAIT flag. Two things can go wrong with that check, and both were handled badly.

EPERM was not recognized. It is what a seccomp profile of a container runtime answers for a system call that is not in its allow list. ThreadPoolReader::submit handed the read off to the thread pool for ENOSYS and EOPNOTSUPP, but let EPERM through to the throw, failing the query with CANNOT_READ_FROM_FILE_DESCRIPTOR. This is the signature reported in #49149.

The check was never verified in advance. hasBugInPreadV2 only compared the kernel version, and nothing else was checked, so on a system where the check cannot work pread_threadpool kept paying for a thread pool hand-off on every read - including the reads that only had to copy the data from the page cache. In #104634, on Amazon Linux 2 (kernel 5.10), the profile shows ThreadPoolReaderPageCacheMiss 1,971,514 out of LocalThreadPoolJobs 1,972,484 - every read went to the pool - while the device only moved ~22 GB of the 258 GB the file descriptor delivered, i.e. ~90% of the data was in the page cache and still paid for the hand-off.

The system call is now probed once, before it is used, by preadNoWaitUnavailableReason. The probe passes an invalid file descriptor on purpose: seccomp filters and the system call table are consulted before the descriptor is looked up, so an available system call answers EBADF without reading anything, while a blocked one answers EPERM or ENOSYS. When it says the check cannot be used, applySettingsQuirks switches the default value of local_filesystem_read_method from pread_threadpool to pread at start time, and says why in the server log. Nothing downstream has to know: the reader, the userspace page cache eligibility in DiskLocal::prepareRead and the prefetched read pool all see a plain pread setting.

As with the other settings quirks, a value set explicitly - in the configuration, or with SET at runtime - is left alone. Such a session keeps pread_threadpool and keeps paying for the hand-off, which is what happens today.

The switch is a property of the host, so the setting is left marked as unchanged: only the changed settings are serialized into the query the initiator sends to the remote shards, and a host that cannot use the system call must not impose pread on the shards that can. An explicitly requested value stays changed and is still sent.

The per-read errno handling in ThreadPoolReader::submit is kept, with EPERM added to it: the probe answers for the system call, but a particular filesystem can still reject the flag (tmpfs answers EOPNOTSUPP, for example), and such a read is handed off to the thread pool instead of failing the query.

How it was tested

preadv2 was rejected the way a container runtime does it, with a seccomp filter installed by a small wrapper (SECCOMP_RET_ERRNO), and an old kernel was simulated with setarch --uname-2.6. Reading a 2 million row MergeTree table with the default local_filesystem_read_method, before (the released 26.7.1 binary) and after:

before after
no filter ThreadPoolReaderPageCacheHit 39, LocalThreadPoolJobs 90 ThreadPoolReaderPageCacheHit 34, ThreadPoolReaderPageCacheMiss 3, LocalThreadPoolJobs 93 - the read method stays pread_threadpool
preadv2 → EPERM Code: 74 ... errno: 1, Operation not permitted (CANNOT_READ_FROM_FILE_DESCRIPTOR), already while attaching the table the read method is pread, the query succeeds, no ThreadPoolReader events
preadv2 → ENOSYS ThreadPoolReaderPageCacheMiss 45, LocalThreadPoolJobs 135 - every read to the pool the read method is pread, no ThreadPoolReader events, LocalThreadPoolJobs 80
kernel reported as older than 5.11 ThreadPoolReaderPageCacheMiss 45, LocalThreadPoolJobs 135 the read method is pread, no ThreadPoolReader events, LocalThreadPoolJobs 81

In all three rejected cases the reason is in the log, for example:

<Warning> SettingsQuirks: The default value of local_filesystem_read_method has been switched from
'pread_threadpool' to 'pread' (you can explicitly set it back still), because the `preadv2` system call
is not available (the probe with an invalid file descriptor answered errno: 1, strerror: Operation not
permitted instead of `EBADF`); it is typically rejected by a `seccomp` profile of a container runtime,
and can be allowed in the runtime configuration. ...

An explicitly requested local_filesystem_read_method = 'pread_threadpool' is kept, on every one of those systems, and this is where the per-read EPERM handling earns its place: under the EPERM filter the same query fails on the released binary and succeeds here, with ThreadPoolReaderPageCacheMiss 45 and LocalThreadPoolJobs 135 - every read handed off to the pool, which is the documented cost of asking for it there.

Under the same filters, system.settings reports local_filesystem_read_method = 'pread' with changed = 0, so nothing is forwarded to the remote shards, while an explicitly requested pread_threadpool reports changed = 1 and is still sent.

Unit tests cover the errno classification, the probe's EBADF contract, and the quirk itself (the default is switched exactly when the probe says the system call is unusable, the switched value stays out of Settings::changes(), and an explicitly set value is never switched). An automated end-to-end test would need an instance with a restrictive seccomp profile, which the integration test framework cannot express today - it starts every instance with seccomp:unconfined.

Documented behavior impact

On a system where the page cache cannot be checked without waiting for the disk - Linux older than 5.11, a sandbox that rejects preadv2 with an error code, and systems other than Linux, where preadv2 does not exist and the method never checked the page cache in the first place - the default value of local_filesystem_read_method becomes pread instead of pread_threadpool, so local reads are performed in the calling thread. This includes the reads with O_DIRECT, which never look at the page cache and do not need the check; the read method is now resolved once, for the whole server, so they follow the same value. Nothing changes on a supported system, and nothing changes for an explicitly configured read method. The setting description in src/Core/Settings.cpp, from which the docs are generated, is updated in this PR.

A seccomp profile that terminates the process instead of rejecting the system call with an error code cannot be detected: the startup probe is itself a preadv2 call, so such a profile kills the server there. On master it kills it at the first read instead, under the same default read method.

Changelog category (leave one):

  • Improvement

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

The pread_threadpool read method needs the preadv2 system call with the RWF_NOWAIT flag to read the data that is already in the page cache without handing the read off to a thread pool. It is now checked at start time whether that system call can be used, and if it cannot - the Linux kernel is older than 5.11, or a seccomp profile of a container runtime rejects the system call - the default value of local_filesystem_read_method is switched to pread, and the reason is reported in the server log. Previously, every read paid for a thread pool hand-off on such systems, and a seccomp profile that answers EPERM made queries fail with CANNOT_READ_FROM_FILE_DESCRIPTOR.

Version info

  • Merged into: 26.8.1.1369 (included in 26.8 and later)

…d` then

The `pread_threadpool` read method hands every read off to a thread pool,
unless the data is already in the page cache, which it checks with the
`preadv2` system call and the `RWF_NOWAIT` flag. Two things can go wrong with
that check, and both were handled badly.

`EPERM` - what a `seccomp` profile of a container runtime answers for a system
call that is not in its allow list - was not recognized as the system call
being unavailable. Instead of handing the read off to the thread pool, as it
does for `ENOSYS` and `EOPNOTSUPP`, the read failed the query with
`CANNOT_READ_FROM_FILE_DESCRIPTOR`.

And when the check cannot be used at all - the kernel is older than 5.11,
where `RWF_NOWAIT` can report the end of the file instead of the data, or the
system call is blocked - `pread_threadpool` kept paying for a thread pool
hand-off on every read, including the reads that only had to copy the data
from the page cache.

The system call is now probed once, before it is used. An invalid file
descriptor is passed to it on purpose: `seccomp` filters and the system call
table are consulted before the descriptor is looked up, so an available system
call answers `EBADF` without reading anything. When it is not available,
`local_filesystem_read_method = 'pread_threadpool'` is treated as `'pread'`,
which reads the same data in the calling thread, and the server explains why
in `system.warnings` on startup. Reads with `O_DIRECT` never look at the page
cache and keep using the thread pool.

The `preadv2` system call and the knowledge about when it is usable moved to
`preadNoWait`, so that the reader and the read method selection agree on it.

Related: #104634
Related: #49149
Related: #39753

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a8beb0]

Summary: ✅


AI Review

Summary

This PR changes the default behavior of local_filesystem_read_method on hosts where preadv2(..., RWF_NOWAIT) cannot be used, by probing that capability once and switching the effective default from pread_threadpool to pread while keeping explicit user-configured values untouched. I reviewed the current diff, the touched code paths, the added tests, and the full prior discussion, and I did not find any remaining correctness, compatibility, or test-coverage issue that still holds in the current revision.

Final Verdict

✅ No remaining findings from this review pass.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 77/102 (75.49%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 1, 2026
@alexey-milovidov
alexey-milovidov requested a review from azat August 2, 2026 23:23
…pareRead`

`DiskLocal::prepareRead` disables the userspace page cache for the read methods
that are incompatible with it, and it branched on the requested
`local_fs_settings.method`. On a system where `preadNoWait` cannot be used,
`pread_threadpool` reads with `pread`, which is compatible with the page cache,
but the check still saw `pread_threadpool` and turned the page cache off.
It now resolves the method with `resolveLocalFSReadMethod` first, the same way
`createReadBufferFromFileBase` does, using the same estimated size basis to tell
whether the read will use `O_DIRECT`.

Also add braces around `__msan_unpoison`: it expands to nothing outside of an
MSan build, so `clang-tidy` reported the `if` statement as
`bugprone-suspicious-semicolon` in the `arm_tidy` build.
Comment thread src/IO/ReadMethod.cpp Resolved
Comment thread programs/server/Server.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1a8beb03e with master c42c154da (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
Binary Master PR Δ
programs/clickhouse-stripped 691.73 MiB 688.73 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

5 object files changed (+23.86 KiB total), 1 added.

Object file Master PR Δ

737 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

10 translation units recompiled, 24 s compile time in total, 9 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits August 4, 2026 00:11
…ead method

On a system where `preadNoWait` is unusable, `pread_threadpool` reads with
`pread`, so `ReadFromMergeTree` must not enable `MergeTreePrefetchedReadPool`
from the raw requested method.

Co-Authored-By: Claude Fable 5 <[email protected]>
The downgrade applies only to `local_filesystem_read_method = 'pread_threadpool'`
and only to reads without O_DIRECT; say so in the warning.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

alexey-milovidov commented Aug 4, 2026 •

Copy link
Copy Markdown
Member Author

🕵 The 04690_parquet_parallel_encoder_thread_starvation MSan timeout in Stateless tests (amd_msan, WasmEdge, parallel, 1/2) is unrelated to this PR: the test failed on 7–8 unrelated PRs per day since 2026-08-02, and it was removed from master by f41c98eb2ae (revert of #112959). This branch has merged master, so the test is gone and the red will clear on the next CI run. No action needed.

Comment thread src/Disks/DiskLocal.cpp Resolved
alexey-milovidov and others added 2 commits August 4, 2026 19:26
…s as `prepareRead`

`DiskLocal::prepareRead` resolved `direct_io` (and with it the effective read
method and the page cache decision) from `read_hint.value_or(file_size)`, while
the legacy build path in `ReadPipeline` called `createReadBufferFromFileBase`
with the hint only. For a null-hint read of a large file with
`min_bytes_to_use_direct_io` set, `prepareRead` kept `pread_threadpool` and
disabled the userspace page cache, while the buffer was opened without
`O_DIRECT` and resolved to `pread`. The stored object already carries the
stat'ed size, so pass it to the builder, and treat a failed stat as size zero
in `prepareRead` (the builder sees `UnknownSize` then), so both sides resolve
from the same value.

Co-Authored-By: Claude Fable 5 <[email protected]>
…` reads with `pread`

`02910_prefetch_unexpceted_exception` and
`04640_query_log_map_columns_serialization` assert side effects of the local
prefetched read pool: a failpoint inside `MergeTreePrefetchedReadPool` and the
`asynchronous_read_counters` keys in `system.query_log`. macOS has no
`preadv2`, so `pread_threadpool` is now treated as `pread` there and the pool
never runs for local reads - the intended behavior of this change - so the two
tests cannot pass on Darwin. The tests keep full coverage on Linux.

Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112945&sha=aee807c7c843036e7d38ae48b4ecef4df738628b&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
PR: #112945

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/server/Server.cpp Resolved
…lly requested

A `seccomp` profile that kills the process on unknown system calls must not
see the probe from read methods that do not depend on it. The resolution
now goes through a `resolveLocalFSReadMethod` overload that short-circuits
before `getPreadNoWaitSupport` unless the requested method is
`pread_threadpool`, and the startup warning in `sanityChecks` is emitted
only when the default profile actually selects `pread_threadpool`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the CI failures on 5edbad2:

@groeneai, investigate the two stateless failures above and provide fixes in separate PRs if they are real bugs (the client segfault on SIGINT in 02290_client_insert_cancel looks worth a look). If fixes are already in progress, link them here.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

All three are real, and all three now have an owner. The first one is not #111677, which changes its
disposition, so I start there.

Logical error: Next task callback is not set for query (amd_msan stress): already fixed, and it is a
different defect from #111677.
Two throw sites share that wording. #111677 is
Context::getMergeTreeAllRangesCallback (Context.cpp:8084), whose message ends for query with id:
and which reads the parallel-replicas member. This failure hit
Context::getClusterFunctionReadTaskCallback (Context.cpp:8046) instead, reading next_task_callback,
via StorageObjectStorageSource::createFileIterator. The failing query was
SELECT count() FROM remote('127.0.0.1', 'test_2', 'test_view') SAMPLE 1 from
03667_view_with_s3_cluster_and_sql_security_definer.sh, that is a SQL SECURITY DEFINER view over
s3Cluster read as a secondary query. getSQLSecurityOverriddenContext rebuilds the view context from
the global context for the DEFINER and NONE branches and re-propagates query state item by item; it
carried the three MergeTree parallel-replicas callbacks but not next_task_callback, so the cluster
function inside the view could not reach the initiator. #113371 propagates it and merged today at 10:06Z.
Presence probe on the changed file: setClusterFunctionReadTaskCallback appears 0 times at
5edbad2c740 and 1 time at the merge commit, and your build is 613 commits behind it, so it predates the
fix. Nothing further is owed here.

02290_client_insert_cancel (arm_binary): real client bug, fix open in #113431. You were right that
it is worth a look. The client returns 139 because it crashes at process exit, after its work is
finished, so SIGINT is only one way in; the same crash follows a plain INSERT that reads stdin.
UntrackedMemoryRegistry::instance() is a function-local static holding a boost::intrusive::list of
safe_link hooks, so its destructor nulls the hooks of every still-linked node. clickhouse-client was
the only entry point that did not join its global-pool threads before main returned: parsing stdin
lazily creates the process-lifetime format-parsing pool (FormatFactory.cpp:510), and those workers
detach() themselves on the shrink branch, so nothing joins them. Such a worker can still be unwinding
during static destruction, and its ~ThreadStatus then reaches UntrackedMemoryRegistry::remove,
unlinking through the destroyed head. The fix adds the shutdown guard to mainEntryClickHouseClient,
matching the clickhouse-local precedent in b219eaf99e94aeb; forcing the race reproduces it 15/15
before and 0/15 after. That PR already names this report of yours as one of its two carriers, so 0/65
reruns is expected: the window is narrow, not absent.

04510_backup_cleanup_empty_data_file_name (amd_tsan, s3 storage): real server bug, and not
concurrency.
The .lock check reads a stale mmap mapping, so the retry compares its own freshly
written lock against the previous attempt's contents:

01:21:17.752748 {42f83cb9} BackupImpl: Writing backup: Disk('backups','..._inc')
01:21:17.753159 {42f83cb9} BackupImpl: Checking lock file .lock
01:21:17.753300 {42f83cb9} BackupImpl: Lock file .lock contents do not match,
                           expected: ca4a40e7-971d-40c6-b06a-52a68f07241b,
                           actual:   68d1d634-ef50-4a90-ac33-3aad55c46adb

ca4a40e7 is the retry's own UUID; 68d1d634 belongs to the fault-injected attempt whose lock file
cleanup had just removed. The test is no-parallel and only two query ids touch that destination in the
whole server log, so there is no concurrent backup. The query_log ProfileEvents for those two ids settle
it: the retry has BackupLockFileReads=1, CreatedReadBufferMMap=1, MMappedFileCacheHits=1,
MMappedFileCacheMisses=0. Its single lock read came entirely from the mmap cache and never looked at the
file it had just written.

MMappedFileCache::hash keys on path, offset and length only, with no inode, mtime or size, so a file
recreated at the same path with the same length hits the old mapping. Nothing on the backup write path
invalidates that cache: clearMMappedFileCache has five call sites and none is in src/Backups/ or
src/Disks/. checkLockFile reaches mmap because BackupWriterDisk::readFile passes the session
ReadSettings through adjustBufferSize, which narrows buffer sizes but preserves the read method and
the mmap threshold.

One correction to the triage: the randomized draw also had min_bytes_to_use_mmap_io=1, and that is what
makes a 36 byte lock file eligible for mmap at all; local_filesystem_read_method=mmap alone is not
enough. You are right that your diff does not cause it, but the settings are the trigger rather than
incidental, so I would not leave it as flaky. CIDB gives 10 failures over 3 pull requests and 0 on master
in 40 days, including 2 on #109947 which added the test; the 7 on #103706 rewrite this same read path, so
they may be a different cause and I am not pooling them.

A fix task is created for this half, at full effort. I will post the fixing PR link here when it opens.

@azat azat 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.

Please look at the comments, and also I would suggest to squash everything to a single commit.

Comment thread src/IO/ReadMethod.cpp Resolved
Comment thread src/IO/ReadMethod.h Resolved
Comment thread src/IO/ReadPipeline.cpp Resolved
azat
azat previously requested changes Aug 5, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

The fixing PR for the 04510_backup_cleanup_empty_data_file_name half is #113617, as promised above.

It fixes the stale-read at the settings layer: BackupImpl::checkLockFile reads back a file this
process just wrote, so ReadSettings::disableCaches now also clears the mmap fields and the two
local-filesystem backup writers call it. That covers a second carrier as well, the userspace page
cache, which keys on path plus a file_version local disks never populate.

One thing worth flagging for your own PR, because it changes the reachability of this bug and I only
found it while writing the reachability sentence for the changelog. On master the 36 byte lock read
cannot reach the mmap cache under randomized settings alone: ReadPipeline's legacy local branch
calls createReadBufferFromFileBase(s.path, settings, s.read_hint) with no file_size, and
DiskLocal::prepareRead passes no read_hint for this read, so estimated_size stays 0 and the
estimated_size >= mmap_threshold conjunct is false however the runner draws
local_filesystem_read_method and min_bytes_to_use_mmap_io. Reproducing it on master needs
use_reader_executor = 1, since LocalSourceReader::open is the only local path that forwards a
size.

Your branch changes that. src/IO/ReadPipeline.cpp at 5edbad2c740 resolves file_size from
object.bytes_size and forwards it on that same legacy branch, and DiskLocal::prepareRead records
the real size in the StoredObject. So on your branch the lock read becomes mmap-eligible from the
randomized settings alone, with no experimental setting, which is exactly what the failing job's
CreatedReadBufferMMap = 1 and MMappedFileCacheHits = 1 show. Measured on unmodified master, the
same two settings without use_reader_executor give CreatedReadBufferMMap = 0 and the retry
succeeds.

That does not make the bug yours: the stale read is pre-existing and the size pass-through is a
correct change. It does mean your diff widens the set of configurations that hit it, so this failure
was not incidental to your PR after all, and I would expect it to keep reproducing on your branch
until #113617 lands. My earlier note here said min_bytes_to_use_mmap_io = 1 was the trigger, which
was right about the draw and incomplete about why the draw was sufficient on your branch and is not
on master.

alexey-milovidov and others added 4 commits August 6, 2026 13:08
…ize basis as `prepareRead`"

This reverts commit 5b23637.
…alFSReadMethod` comment

Co-Authored-By: Claude Fable 5 <[email protected]>
…s enabled

The prefetched-pool gate in `ReadFromMergeTree` resolved 'pread_threadpool'
with `direct_io = false`, so on a host without `preadNoWait` it rejected
`MergeTreePrefetchedReadPool` even for queries whose reads are forced onto
O_DIRECT by `min_bytes_to_use_direct_io`, although those reads keep the
thread pool. Resolve with `direct_io = true` while `direct_io_threshold` is
set, so such queries keep the pool; when direct IO is disabled entirely, the
downgrade to 'pread' still disables the pool as before.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the CI failures on 901ef4c:

  • Stress test (arm_tsan): Logical error: Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t> in FunctionComparison::executeArrayLexicographicEqualityImpl — matches the open issue Logical error: Bad cast from type A to B (STID: 1499-2747) #113640, fix in progress in Fix a logical error comparing arrays whose element type is Nothing #113609; unrelated to this PR.
  • Stress test (arm_msan): Logical error in IColumn::assertTypeEquality reached from SerializationDynamicElement::deserializeBinaryBulkWithMultipleStreams while reading a compact part (JSON/Dynamic subcolumn with the substreams cache). The same assertion fails across dozens of unrelated PRs and on master itself (71 failures under STID 2508-30f6 and 57 under STID 2508-2e0c in the last 60 days, latest today), so it is pre-existing and unrelated to this PR, which does not touch deserialization. I found no tracking issue for it.

@groeneai, investigate the second failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112945&sha=901ef4cb81f2987e1705be572ef50e0be9be1086&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR (and file a tracking issue). If a fix is already in progress, link it here.

…query_log_map_columns_serialization` as `no-darwin`

`ci/defs/darwin.skip` only affects the Darwin fast-test harness, while
ordinary `clickhouse-test` runs on macOS skip only tests tagged
`no-darwin`. Both tests assert local prefetched-read-pool side effects
that never happen when `pread_threadpool` resolves to `pread` on Darwin.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed f4da4a7e1b99: the 13th AI review round's sole Major is addressed — 02910_prefetch_unexpceted_exception and 04640_query_log_map_columns_serialization are now tagged no-darwin (the ci/defs/darwin.skip entries remain as the harness-level guard), on top of a fresh master merge (the branch was 891 commits behind).

Triage of the two CI reds on 984b5704:

Comment thread src/Disks/DiskLocal.cpp Resolved
alexey-milovidov and others added 2 commits August 12, 2026 03:21
…nstead of predicting it

`willUseDirectIO` proves only that `createReadBufferFromFileBase` will attempt
O_DIRECT. When the filesystem rejects the O_DIRECT open, the reader falls back
to cached IO and resolves the method as a non-direct read - downgrading
'pread_threadpool' to 'pread' on a host without `preadNoWait` - while
`DiskLocal::prepareRead` had already kept the method and disabled the
userspace page cache for a read that ends up page-cache-compatible.

New `canOpenWithDirectIO` probes the O_DIRECT open with the same flags the
reader uses, only when the page-cache decision depends on it. On probe failure,
direct IO is disabled for the read in the settings handed to the pipeline
source, so the reader deterministically resolves the same non-direct read.

New gtest `ReadMethod.DirectIOOpenProbeMatchesTheReader` asserts that the
probe and the reader take the same branch on whatever filesystem the test
runs on, and that a nonexistent file is never claimed O_DIRECT-capable.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Triage of the four stress reds on f4da4a7e — all are the known fleet-wide storms, unrelated to this PR:

Pushed 5ce30b5140dd on top of a fresh master merge: the 14th AI review round's Major (DiskLocal::prepareRead treating an attempted O_DIRECT open as a proof) is fixed with the requested regression test — details in the inline thread.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112945&sha=f4da4a7e1b9928b3d2dac3986f70a7b2a96e916f&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 — Sanitizer (STID: 1367-1a13), a LeakSanitizer report whose visible leak roots go through AggregateFunctionForEach::ensureAggregateData / QuantileExactBase::merge and IdentifierResolver::tryResolveTableIdentifier (StorageInMemoryMetadata copy). CIDB shows the same STID on master and 4 other PRs in the last 5 days, so it is not caused by the PRs it lands on, but I found no tracking issue for this signature (it does not look like #114291's StorageTimeSeriesSelector cycle or #113954's DDL/ZooKeeper cycle). Please provide a fix in a separate PR, or link the existing issue/fix if one is already in progress.

Comment thread src/Core/Settings.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

The -ForEach half already has a fix in progress: #113926 (mine, open). AggregateFunctionForEach::ensureAggregateData grows the per-element state array, creates fresh nested states, merges the old ones in and never destroys them, so each abandoned nested QuantileExact array stays unreachable and unfreed. It reproduces with one query on a plain ASan build, no stress phase.

Breadth confirmed independently, so I agree it is not caused by the PRs it lands on: 5 runs in a 10-day window, master at a7cd48316aab (2026-08-07 18:07, head_ref = 'master' checked explicitly) plus 4 PRs (#113575, #101135, #113022, and this one).

One correction on the signature: this report pools two distinct defects, and #113926 is only one of them.

So the STID is aliasing the two, which is why it does not match #114291 as a whole. #113926 removes the direct roots; the indirect remainder keeps the post-check red on its own until #114291 is fixed.

There is no tracking issue for the -ForEach half. #113926 links only the 2024 predecessor #60683, closed then for want of a test, which is what the repro above supplies. The 1367-1a13 hits in issue search are my own comments on #113954. I can file a separate issue for it if you would like it tracked outside the PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

On the suggestion to squash everything into a single commit: the branch deliberately keeps additive history while under review, so each review round stays diffable against the previous one (and the working convention here is to never rebase or amend a pushed branch). The end state on master can still be a single commit — squashing at merge time loses nothing.

This isn't true. We just keep all the development history on GitHub, that simple.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

But it was on point:

We can use SettingsQuirks to switch from pread_threadpool to pread at start time.

We can tolerate the fact that if a user has a server configured with pread, and thus the startup check is missed, and then switches to pread_threadpool at runtime, they get a worse performance.

This will simplify the code a lot. Like a totally different, and trivial, implementation.

… resolving it at every read

`preadv2` with the `RWF_NOWAIT` flag is what the `pread_threadpool` read
method needs to read the data that is already in the page cache without
handing the read off to a thread pool. Whether it can be used was resolved
separately at every place that inspects the read method, which needed
`resolveLocalFSReadMethod`, `willUseDirectIO` and `canOpenWithDirectIO`,
and changes in `DiskLocal::prepareRead`, `createReadBufferFromFileBase`,
`ReadFromMergeTree::readFromPool` and `Server`.

Resolve it once instead, where the other quirks of this kind live:
`applySettingsQuirks` switches the default value of
`local_filesystem_read_method` from 'pread_threadpool' to 'pread' when the
one-time probe says the system call cannot be used, and reports the reason
in the log. Everything downstream then sees a plain 'pread' setting and
needs no changes of its own, so all of the above is deleted.

Only the default is switched. A value set explicitly, in the configuration
or with `SET`, is left alone, as with the other settings quirks: such a
session keeps 'pread_threadpool' and keeps paying for the hand-off, which
is what happens today. The per-read `errno` handling in
`ThreadPoolReader::submit`, which now also recognizes `EPERM`, keeps that
session working instead of failing it with
`CANNOT_READ_FROM_FILE_DESCRIPTOR`.

The `system.warnings` entry goes away with `Server.cpp`: `applySettingsQuirks`
has no `Context` to add it to. The reason is in the server log instead.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Reimplemented that way in 637243cb808, and it is indeed much smaller: the per-read-site resolution is gone entirely - resolveLocalFSReadMethod, willUseDirectIO, canOpenWithDirectIO, all of src/IO/ReadMethod.cpp, and the changes in DiskLocal::prepareRead, createReadBufferFromFileBase, ReadFromMergeTree::readFromPool and Server.cpp, together with the PREAD_NO_WAIT_UNAVAILABLE warning type. Those files are byte-identical to master again (−422 lines).

What is left is the one-time probe in preadNoWaitUnavailableReason (kernel version, then a real preadv2 with an invalid file descriptor, where EBADF is the only answer that proves it ran), one if in applySettingsQuirks that switches the default local_filesystem_read_method from pread_threadpool to pread and logs the reason, and EPERM added to the per-read errno set in ThreadPoolReader::submit. Everything downstream just sees a plain pread setting, which is what removes the rest.

Taking the tolerance you offered: only the default is switched, so a value set explicitly - in the configuration or with SET - is left alone, the same way the neighbouring quirks in that file behave.

One thing that did not survive the move: the system.warnings entry. applySettingsQuirks has no Context, and getting one to it cost more code than the entry is worth, so the reason goes to the server log instead. Say the word if you would rather have it back.

Re-measured on a 2M row MergeTree table, preadv2 rejected by a seccomp filter (SECCOMP_RET_ERRNO) and an old kernel simulated with setarch --uname-2.6, with the released 26.7.1 binary as "before":

before after
no filter ThreadPoolReaderPageCacheHit 39, LocalThreadPoolJobs 90 ThreadPoolReaderPageCacheHit 34, ThreadPoolReaderPageCacheMiss 3, LocalThreadPoolJobs 93 - method unchanged
preadv2 → EPERM Code: 74 ... errno: 1, Operation not permitted (CANNOT_READ_FROM_FILE_DESCRIPTOR), already while attaching the table method is pread, query succeeds, no ThreadPoolReader events
preadv2 → ENOSYS ThreadPoolReaderPageCacheMiss 45, LocalThreadPoolJobs 135 method is pread, no ThreadPoolReader events, LocalThreadPoolJobs 80
kernel reported as older than 5.11 ThreadPoolReaderPageCacheMiss 45, LocalThreadPoolJobs 135 method is pread, no ThreadPoolReader events, LocalThreadPoolJobs 81

With an explicit local_filesystem_read_method = 'pread_threadpool' under the EPERM filter, the same query fails on the released binary and succeeds here (ThreadPoolReaderPageCacheMiss 45, LocalThreadPoolJobs 135) - every read to the pool, which is the cost of asking for it there, and what #49149 was about.

Unit tests cover the errno classification, the probe's EBADF contract, and the quirk itself. The PR description is updated, and CI on the previous head 5ce30b51 was fully green.

Noted on the history point - new commits only, nothing squashed or rewritten.

Comment thread src/Core/SettingsQuirks.cpp Resolved
Outside of an MSan build the macro expands to nothing, so an unbraced
`if (res > 0) __msan_unpoison(buf, res);` leaves an empty statement, and
`bugprone-suspicious-semicolon` rejects it:

    src/IO/preadNoWait.cpp:63:34: error: potentially unintended semicolon
    [bugprone-suspicious-semicolon,-warnings-as-errors]

https://s3.amazonaws.com/clickhouse-test-reports/PRs/112945/637243cb8083a15db724d93dd9baf2bb444a90bb/build_arm_tidy/build_clickhouse/build_clickhouse.log
Three findings from the review of the `SettingsQuirks` rewrite.

**The switched value was forwarded to the remote shards.** Assigning through
`settings[...]` marks the setting as changed, `BaseSettings::write` serializes
exactly the changed settings, and `Connection::sendQuery` sends those to every
shard. An initiator whose `preadv2` is blocked - or that runs an old kernel -
therefore imposed `local_filesystem_read_method = 'pread'` on shards where the
system call works, losing 'pread_threadpool' cluster-wide. The switch is a
property of the host, not of the query, so the changed bit is cleared again
and the setting stays out of `Settings::changes()`. Verified through the real
`Context`: under a `seccomp` filter that rejects `preadv2`, `system.settings`
now reports `value = 'pread'` with `changed = 0`, while an explicitly requested
'pread_threadpool' still reports `changed = 1` and is still sent.

**Two Darwin skips are no longer warranted.** Only the default is switched now,
and `03552_filesystem_read_prefetches_log` and
`04640_query_log_map_columns_serialization` both set
`local_filesystem_read_method = 'pread_threadpool'` in the query, so the
prefetched read pool still runs for them on macOS. Their `no-darwin` tags, and
the `ci/defs/darwin.skip` entry, are removed. `02910_prefetch_unexpceted_exception`
keeps its skip: it asks for the pool without asking for the read method, so it
relies on the default.

**The setting description overpromised.** The startup check detects a `seccomp`
profile only if the profile rejects the system call with an error code, which is
what container runtimes do; a profile that terminates the process instead cannot
be detected, and the wording now says so.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All three findings of the 15th AI review round are addressed in c98e1cb973f. The Blocker was real, and I confirmed the mechanism rather than the symptom.

Blocker - the switched value was forwarded to the shards. BaseSettings::begin is allChanged().begin() (SKIP_UNCHANGED), so BaseSettings::write serializes exactly the changed settings, and Connection::sendQuery (src/Client/Connection.cpp:1029) sends that. Assigning through settings[...] sets the changed bit, so an initiator with a blocked preadv2, or an old kernel, imposed local_filesystem_read_method = 'pread' on shards where the system call works. The switch is a property of the host, not of the query, so the changed bit is cleared again.

Verified through the real Context, not only in the unit test:

value changed
no filter pread_threadpool 0
preadv2 → EPERM pread 0
kernel reported as older than 5.11 pread 0
preadv2 → EPERM, explicit pread_threadpool pread_threadpool 1

The last row is the one that must still be sent, and is. SettingsQuirks.PreadThreadpoolNeedsPreadNoWait now also asserts the setting is absent from Settings::changes(), so the property is pinned.

Major - the Darwin skips. Correct, and it is a leftover from the previous design, which downgraded explicit values too. Checked each of the three:

test asks for pread_threadpool?
02910_prefetch_unexpceted_exception no - only allow_prefetched_read_pool_for_local_filesystem, so it relies on the default skip kept
03552_filesystem_read_prefetches_log.sql.j2 yes, in the query at line 16 no-darwin removed
04640_query_log_map_columns_serialization yes, in the query at line 30 no-darwin and the ci/defs/darwin.skip entry removed

Major - the kill-on-deny wording. Dismissed in an earlier round, but the situation changed with this design: the probe now runs at startup for the default read method, so a SECCOMP_RET_KILL_* profile terminates the server there rather than at the first read. The description now says the check detects a seccomp profile only if the profile rejects the system call with an error code, which is what container runtimes do, and that a profile which terminates the process cannot be detected.

Also in 845b08d3d69: Build (arm_tidy) failed on the previous head with bugprone-suspicious-semicolon at src/IO/preadNoWait.cpp:63 - outside an MSan build __msan_unpoison expands to nothing, so the unbraced if (res > 0) __msan_unpoison(buf, res); left an empty statement. The braces are back.

@alexey-milovidov
alexey-milovidov requested a review from azat August 12, 2026 15:59
alexey-milovidov and others added 2 commits August 13, 2026 12:40
On a host without `preadv2` (e.g. Darwin), the quirk fired in every
program that applies settings changes, and `clickhouse-client` writes
its log to stderr - so every stateless test failed with the warning in
the client's stderr. Report the reason like the other quirks do: only
when the caller passes a logger, which is `Context::setDefaultProfiles`
at server startup.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112945&sha=c98e1cb973f25c20d6ee69527f92ed9424d9adef&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
PR: #112945

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 1a8beb03ecc7: the Fast test (arm_darwin) red on c98e1cb9 was caused by this PR — on a host without preadv2 the quirk logged its warning unconditionally through getLogger("SettingsQuirks"), and clickhouse-client writes its log to stderr, so all 110 tests failed with having stderror. The warning is now reported like the other quirks in applySettingsQuirks: only to the caller that passes a logger, which is Context::setDefaultProfiles at server startup (clickhouse-local keeps its default fatal console level, so it stays quiet too). On top of a fresh master merge (the branch was 943 commits behind). All 6 SettingsQuirks/preadNoWait gtests pass.

@alexey-milovidov alexey-milovidov left a comment

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.

Ok, now it is clean.

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit a742383 Aug 13, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-preadv2-nowait-detection branch August 13, 2026 21:41
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants