Repository navigation
Conversation
`Stress test (arm_msan)` fails roughly once a week with `Segmentation fault (STID: 4348-2010)` in the `RemoteQueryExecutorReadContext` fiber during teardown. Over the last 100 days CIDB records 16 hits, all on that one check, including one on master; every other architecture and sanitizer has zero. On AArch64 with `-fsanitize=memory`, clang materialises the thread pointer (`mrs xN, TPIDR_EL0`) into a callee-saved register and keeps it live across a call. When that call switches to another OS thread's stack, the cached value still names the old thread, so the next MemorySanitizer shadow-TLS access dereferences an address unmapped in the current thread. Disassembling the exact failing binary shows `boost::context::fiber::resume` reading the thread pointer once in its prologue, calling into `::swapcontext`, and then storing through the stale register on the `force_unwind` throw path; the register's only other write is an epilogue reload on the return path that path skips. The offsets resolve to `__msan_param_tls`, `__msan_retval_tls` and `__msan_va_arg_tls`. The behaviour is specific to AArch64 for a mechanical reason: on x86-64 MSan TLS is segment-relative and resolved per access, so there is no register to go stale. Compiling the same translation unit for x86-64 produces 30 segment-relative accesses and no `mrs` at all. Rather than trying to keep fibers safe under an instrumentation limitation the compiler does not model, compile the fiber-backed remote-I/O paths out of that one build configuration, at the five places where the code already chooses between an asynchronous and a synchronous implementation and already has a working synchronous counterpart: `RemoteQueryExecutor::readAsync`, `RemoteQueryExecutor::sendQueryAsync`, the hedged branch building `HedgedConnections`, the asynchronous block in `ConnectionPoolWithFailover::tryGetEntry`, and the connection and read selectors in `distributedIndexAnalysis`. A new `src/Common/RemoteAsyncCapability.h` holds the single definition of the condition so no copy of it can drift. In `distributedIndexAnalysis` the selectors are gated rather than `establishConnectionsAsync` and `executeRemoteAnalysisAsync` themselves, because their own `#else` branches throw rather than falling back, and gating the implementations would have turned a crash into an exception. `processParallelReplicaPacketIfAny` is gated because it dereferences `read_context` unconditionally while `read_context` is never created without the asynchronous path. Settings values are left untouched. A settings-level guard would have been bypassable, and one of the six fiber construction sites is gated on `async_callback` rather than on any setting, so no settings-level scheme could have covered it. At build level the property is structural: no setting value, `SET`, profile, `DEFAULT` reset or test randomizer can produce a fiber here. Wherever the asynchronous path stays compiled in, the generated code is identical to before; this was measured across 24 translation-unit-by- configuration combinations with a control. The new header costs no additional preprocessed lines, and because both macros are always defined as 0 or 1 a dropped include is a build failure under `-Werror,-Wundef` rather than a silently disarmed guard. This does not fix the underlying compiler behaviour, which belongs upstream in LLVM; it makes the crash unreachable in the only configuration where it occurs. The cost is disclosed in the pull request description: that lane stops exercising fiber code, and a multi-shard read at low `max_threads` is serialized there because the planner keys stream parallelism on the setting rather than on whether the read blocks. That second point is a pre-existing defect on master, already reachable on FreeBSD, SunOS and Android builds, and is being fixed separately. Related: ClickHouse#110124 Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review — 1 blocker and 1 major raised, both declined with evidence; 1 nit notedAn independent model reviewed this change against the resulting tree, then a second reviewer ❌ Blocker — declined: the synchronous fallback is invisible to planner thread accounting
The mechanism is real and is disclosed in the description with the measurement (15.15 s vs 1.65 s) It is not introduced here. The proposed remedy was reviewed and rejected — three times, at three successively larger The finding's CI argument does not hold. It rests on One correction of my own, found while checking that argument. The description previously said
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-48:20260727-130500 |
|
cc @azat @yariks5s — could you review this? It compiles the fiber-backed remote-I/O paths out of aarch64 + MemorySanitizer builds only, by widening five build guards that already choose between an asynchronous and a synchronous implementation, so the |
|
Workflow [PR], commit [6e116c8] Summary: ❌
AI ReviewSummaryThis PR compiles the fiber-backed remote query send/read and hedged-connection paths out of the Final VerdictStatus: ✅ Approve |
`Build (arm_tidy)` failed on the new `src/Common/RemoteAsyncCapability.h` with `replace macro with enum [modernize-macro-to-enum]` for `CH_REMOTE_ASYNC_IO`. `.clang-tidy` sets `WarningsAsErrors: '*'`, so the diagnostic is a hard build failure. The check cannot be satisfied by converting the macros: both are consumed by `#if` (`CH_FIBERS_SUPPORTED` inside this header, `CH_REMOTE_ASYNC_IO` in `RemoteQueryExecutor`), which an enum cannot be. Being always defined as 0 or 1 is also what makes a dropped include a `-Wundef` build failure instead of a silently disarmed guard, so the value must stay a preprocessor symbol. Wrap both blocks in `NOLINTBEGIN`/`NOLINTEND`, which is what the tree already does for the same check on other headers defining constants that macros have to express: `Common/DateLUTImpl.h` and the four `Common/mysqlxx/mysqlxx/*.h` headers. Only `CH_REMOTE_ASYNC_IO` was reported, and only from `RemoteQueryExecutorReadContext.cpp`: clang-tidy exempts a macro it sees used in a preprocessor conditional, and that translation unit reaches the header transitively through `Common/Fiber.h` without testing the macro itself. The block form covers both macros regardless of which translation unit is analysed. No generated code changes: the preprocessed output of the reported translation unit is byte-identical before and after, and the linked binary's build id is unchanged.
Follows the convention in `.claude/CLAUDE.md`: refer to a function itself as `f` rather than `f()`, and wrap literal names in backticks. Comments only; the preprocessed output of the affected translation units is unchanged.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 39/40 (97.50%) · Uncovered code |
CI finish ledger — 6e116c8CI fully finished on this head (Finish Workflow success, 174 check-runs, 0 queued/in progress).
Not caused by this pull request: the diff is Session id: cron:our-pr-ci-monitor:20260728-070000 |
|
Still needed. #111656 and this PR fix two different defects, and I can show it empirically rather than by argument. The signature recurs on builds that already contain #111656. #111656 merged 2026-07-24T16:10:19Z. STID 4348-2010 then fired twice:
I checked presence per build rather than inferring it from commit distance: both heads carry On the Different mechanism. #111656 repairs a stack walk that reads off the fiber stack. This one is a store: on AArch64 with Different platform, as you noted in your UPD. All 17 CIDB hits over 100 days are File sets do not intersect either: #111656 touches For completeness: merged #110152 (mine) does not fix this one either - it addresses the padding-shadow defect, and the crashing binary already contains it. |
|
Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Related: #110124
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Stress test (arm_msan)fails roughly once a week withSegmentation fault (STID: 4348-2010)in theRemoteQueryExecutorReadContextfiber during teardown. CIDB over the last 100 days: 16 hits, all onStress test (arm_msan)(15 distinct pull requests plus one master hit on 2026-06-10, sha7bd1b86ef3ef), and zero hits on every other check, architecture and sanitizer. Each hit kills the server mid-run and discards the remainder of that job's coverage.Root cause. On AArch64 with
-fsanitize=memory, clang materialises the thread pointer (mrs xN, TPIDR_EL0) into a callee-saved register and keeps it live across a call. When that call switches to another OS thread's stack, the cached value still names the old thread, so the next MemorySanitizer shadow-TLS access dereferences an address that is unmapped in the current thread. ClickHouse resumes suspended remote-I/O fibers on threads other than the suspending one, and destroys them while suspended (force_unwind) on the caller's thread, which is why every hit is a shutdown or timeout teardown.Disassembling the exact failing binary (
clickhouse-common-static_26.8.1.1_arm64.debfrom abuild_arm_msanjob,readelf -nBuild IDb337b381a47106833eee64c02435cbed21e2b920, matching thebuild id:line infatal.log), inboost::context::fiber::resume() &&:x22is provably not reloaded on that path: its only writes in the function are that prologuemrsand an epilogueldp x22, x21, [sp,#0x40]which sits on the fall-through return path that theb.eqskips. The offsets resolve against the binary's own symbol table to__msan_param_tls,__msan_retval_tlsand__msan_va_arg_tls— MemorySanitizer's own shadow area, no user data.This is arch-exclusive for a mechanical reason. On x86-64 MSan TLS is
%fs-relative and resolved by the CPU per access, so there is no register to go stale; compiling the same translation unit--target=x86_64-linux-gnuproduces 30fs:accesses and 0mrs. AArch64 has no segment register, so the thread pointer must live in a general-purpose register, and once there it is hoistable. AddressSanitizer is immune (per-contextfake_stacksave and restore) and ThreadSanitizer switches fibers explicitly. That matches the CIDB distribution exactly.What this pull request does. It compiles out the fiber-backed remote-I/O paths on AArch64 with MemorySanitizer, at the five places where the code already makes a build-conditional asynchronous-versus-synchronous choice, driven by one capability macro in a new
src/Common/RemoteAsyncCapability.h:RemoteQueryExecutor::readAsync#if defined(OS_LINUX) || defined(OS_DARWIN),#else return read();RemoteQueryExecutor::sendQueryAsync#else sendQuery(); return -1;HedgedConnections#if defined(OS_LINUX), falls through toMultiplexedConnectionsConnectionPoolWithFailover::tryGetEntry's asynchronous block#if defined(OS_LINUX)plusif (async_callback), synchronousConnectionEstablisherbeside itdistributedIndexAnalysis's connection and read selectorsif (use_hedged_requests)/if (use_async_reading)with the synchronous variants beside themNo mechanism is invented; each of the five conditions is widened, and every
#elsebranch already runs today on non-Linux builds.processParallelReplicaPacketIfAnyis guarded too because it dereferencesread_contextunconditionally andread_contextis never created without the asynchronous path.Note for the last row: the selectors are gated, not
establishConnectionsAsync/executeRemoteAnalysisAsync's own#ifs, whose#elsethrowsLOGICAL_ERROR "Hedged connections are not supported on this platform". Gating the implementations would have converted a crash into an exception.Settings values are deliberately left untouched. The guard is at build level rather than in
applySettingsQuirksbecause a settings-level scheme is bypassable:Context::setSettings,setSettingWithLockandresetSettingsToDefaultValuenever call it, andInterpreterSetQuery::executeForCurrentContextapplies changes and then resets defaults, soSETTINGS async_socket_for_remote = DEFAULTrestores the compiled default after any quirk ran. One of the six fiber construction sites (ConnectionPoolWithFailover.cpp) is gated onasync_callbackrather than on any setting, so no settings-level scheme could ever have covered it. Gating at build level makes the property structural: no setting value,SET, profile,DEFAULTreset or test randomizer can produce a fiber in this build.Verification. The change is verified at object level, because the crash needs an aarch64 plus MemorySanitizer build and cannot be reproduced by any functional test.
CH_FIBERS_SUPPORTEDandCH_REMOTE_ASYNC_IOwere asserted with the real build flags across 7 configurations: both 0 for aarch64 with MemorySanitizer, both 1 for x86 with MemorySanitizer, and for AddressSanitizer, ThreadSanitizer, UndefinedBehaviorSanitizer and release builds on aarch64, and release on x86.CH_REMOTE_ASYNC_IOis 1, the generated code is identical to master across 24 translation-unit-by-configuration combinations, with a control proving the comparison can detect a real difference. Release behaviour is unchanged.SuspendSendingQueryToShardstays 0, and the four tests that set these settings explicitly pass.base/defines.his already in their closures). Because both macros are always defined as 0 or 1, a dropped include is a build failure under-Werror,-Wundefrather than a silently disarmed guard.aarch64-linux-gnu -fsanitize=memorywith the real build flags and-Weverything -Werror:RemoteQueryExecutor,ConnectionPoolWithFailover,distributedIndexAnalysis,HedgedConnectionsFactory,RemoteQueryExecutorReadContext,checkStackSize,PacketReceiver,ConnectionEstablisher,HedgedConnections,AsyncTaskExecutor,RemoteSource— 11 of 11, zero diagnostics. Compiling out a code path can strand a private member, so this is checked rather than assumed:packet_in_progressneeds the[[maybe_unused]]this pull request adds (dropping it is a hard-Wunused-private-fielderror on that configuration), whileread_packet_type_separatelyneeds none, because its constructor initializer is a function call and clang counts that as a use. The second case is an incidental suppression rather than a designed one: if that initializer is ever simplified to a literal, this configuration stops building.Because the base rate is roughly one hit per week fleet-wide, a single green
Stress test (arm_msan)run on this pull request is not proof. The durable check is the CIDB signature count over three or more weeks against the 16 hits in the preceding 100 days.Costs, disclosed. Two, and neither is hidden.
First, the arm_msan lane stops exercising fiber code; it takes the same synchronous paths that non-Linux builds always take. That is a real coverage loss on one lane, traded against that lane crashing weekly and discarding the rest of the run.
Second, on this configuration a multi-shard read at low
max_threadsis serialized. Measured on a real binary,SELECT sleep(1.5) FROM remote('127.{1..10}', system.one)at--max_threads 1 --max_distributed_connections 10takes 15.15 s instead of 1.65 s.01602_max_distributed_connectionsand01514_distributed_cancel_query_on_errorwould fail if that lane ran stateless tests. It does not.arm_msanhas exactly one job in the whole configuration —Stress test (arm_msan)— and on it the stress runner records only its own script status:run_func_testcollects each worker's return code into a local list it uses solely as a completion counter, and its caller discards the return value. Neither test is in that job's smoke check or hung check. The arm_msan binary does reach stateless tests through one other door,Bugfix validation (functional tests, aarch64), which runs each ARM build type in turn — but that job runs only the tests a pull request itself changes, this one changes none, and it isallow_failureregardless.01602costs 600 s of one stress worker's time budget when it does run (its two retry loops each spend 30 attempts attimeout 10, reaching the runner's per-test cap), and no individual query can reach the hung-check threshold because each is killed at 10 s.The cause of that serialization is a pre-existing defect on master, not something this change introduces. The planner raises stream parallelism to compensate for blocking remote reads, but it keys that on the setting rather than on whether the read will actually block:
readAsyncis already#if defined(OS_LINUX) || defined(OS_DARWIN)with#else return read();, and the planner is platform-blind, so on a FreeBSD, SunOS or Android build of master todayreadAsyncreturns synchronously whileasync_socket_for_remoteis still true and no compensation engages. The control measurement confirms the mechanism: withasync_socket_for_remote = 0the same query takes 1.60 s on both binaries, so synchronous remote reads are not slow — synchronous reads while the setting claims asynchronous are.That residual is being fixed separately and is not a prerequisite for this change. It is kept out of this pull request deliberately: three successively larger designs for it were reviewed and rejected, and the shape that survives requires defining thread-accounting composition semantics for unions, joins, selectors and completed pipelines, which is a change with its own design questions and its own review surface. I will link the follow-up pull request here when it opens. If you would rather see that one first, say so and I will reorder.
Finally, the underlying compiler behaviour is not fixed here.
swapcontextchanging the thread pointer is outside LLVM's model, and the right long-term home is upstream. This change makes the crash unreachable in the one configuration where it can occur.My merged #110152 does not cover this. That pull request fixes a different aarch64 MemorySanitizer fiber defect (padding shadow), and its content is compiled into the binary that produced this crash — inside
contrib/boost,git merge-base --is-ancestor 24df31b3e5c13c e24b1b25e334is true — and the signature fired anyway. Both are needed.