Skip to content

Do not construct remote-I/O fibers on AArch64 with MemorySanitizer - #112124

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/investigate-stid-4348-2010-r2
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/investigate-stid-4348-2010-r2

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #110124

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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 with Segmentation fault (STID: 4348-2010) in the RemoteQueryExecutorReadContext fiber during teardown. CIDB over the last 100 days: 16 hits, all on Stress test (arm_msan) (15 distinct pull requests plus one master hit on 2026-06-10, sha 7bd1b86ef3ef), 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.deb from a build_arm_msan job, readelf -n Build ID b337b381a47106833eee64c02435cbed21e2b920, matching the build id: line in fatal.log), in boost::context::fiber::resume() &&:

357d4da4: mrs  x22, TPIDR_EL0          ; thread pointer, read once in the prologue
357d4dc0: ldr  x25, [x22, x23]         ; pre-switch shadow read (correct thread)
357d4e10: bl   fiber_activation_record::resume()   ; contains ::swapcontext()
357d4e54: b.eq 0x357d4ed4              ; force_unwind -> cold throw block
357d4ee0: str  xzr, [x22, x23]         ; faults: x22 is the stale thread pointer

x22 is provably not reloaded on that path: its only writes in the function are that prologue mrs and an epilogue ldp x22, x21, [sp,#0x40] which sits on the fall-through return path that the b.eq skips. The offsets resolve against the binary's own symbol table to __msan_param_tls, __msan_retval_tls and __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-gnu produces 30 fs: accesses and 0 mrs. 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-context fake_stack save 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:

Site Existing guard, and its synchronous counterpart
RemoteQueryExecutor::readAsync #if defined(OS_LINUX) || defined(OS_DARWIN), #else return read();
RemoteQueryExecutor::sendQueryAsync same, #else sendQuery(); return -1;
the hedged branch building HedgedConnections #if defined(OS_LINUX), falls through to MultiplexedConnections
ConnectionPoolWithFailover::tryGetEntry's asynchronous block #if defined(OS_LINUX) plus if (async_callback), synchronous ConnectionEstablisher beside it
distributedIndexAnalysis's connection and read selectors plain if (use_hedged_requests) / if (use_async_reading) with the synchronous variants beside them

No mechanism is invented; each of the five conditions is widened, and every #else branch already runs today on non-Linux builds. processParallelReplicaPacketIfAny is guarded too because it dereferences read_context unconditionally and read_context is never created without the asynchronous path.

Note for the last row: the selectors are gated, not establishConnectionsAsync/executeRemoteAnalysisAsync's own #ifs, whose #else throws LOGICAL_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 applySettingsQuirks because a settings-level scheme is bypassable: Context::setSettings, setSettingWithLock and resetSettingsToDefaultValue never call it, and InterpreterSetQuery::executeForCurrentContext applies changes and then resets defaults, so SETTINGS async_socket_for_remote = DEFAULT restores the compiled default after any quirk ran. One of the six fiber construction sites (ConnectionPoolWithFailover.cpp) is gated on async_callback rather 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, DEFAULT reset 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.

  • The mechanism is witnessed directly: a checker over the generated assembly of the unmodified boost header reports 3 stale-thread-pointer uses at exactly the instructions that fault in CI, and 0 for a control build.
  • CH_FIBERS_SUPPORTED and CH_REMOTE_ASYNC_IO were 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.
  • On aarch64 with MemorySanitizer, all four fiber constructor references disappear from the objects (2+1+1 to 0+0+0) and are retained in every other configuration.
  • Reverting any one of the six guards individually makes the constructor it dominates reappear, so no guard is decorative.
  • For every configuration where CH_REMOTE_ASYNC_IO is 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.
  • The synchronous fallbacks were exercised end to end on a real binary with the predicate forced on locally: correct results, no hangs, SuspendSendingQueryToShard stays 0, and the four tests that set these settings explicitly pass.
  • The new header costs 0 preprocessed lines in all six affected translation units (base/defines.h is already in their closures). 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.
  • Every translation unit that touches fibers compiles clean for aarch64-linux-gnu -fsanitize=memory with 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_progress needs the [[maybe_unused]] this pull request adds (dropping it is a hard -Wunused-private-field error on that configuration), while read_packet_type_separately needs 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_threads is serialized. Measured on a real binary, SELECT sleep(1.5) FROM remote('127.{1..10}', system.one) at --max_threads 1 --max_distributed_connections 10 takes 15.15 s instead of 1.65 s. 01602_max_distributed_connections and 01514_distributed_cancel_query_on_error would fail if that lane ran stateless tests. It does not. arm_msan has 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_test collects 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 is allow_failure regardless. 01602 costs 600 s of one stress worker's time budget when it does run (its two retry loops each spend 30 attempts at timeout 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:

bool is_sync_remote = table_expression_data.isRemote() && !settings[Setting::async_socket_for_remote];

readAsync is 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 today readAsync returns synchronously while async_socket_for_remote is still true and no compensation engages. The control measurement confirms the mechanism: with async_socket_for_remote = 0 the 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. swapcontext changing 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 e24b1b25e334 is true — and the signature fired anyway. Both are needed.

`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — 1 blocker and 1 major raised, both declined with evidence; 1 nit noted

An independent model reviewed this change against the resulting tree, then a second reviewer
adjudicated its findings. Recorded here so the reasoning is auditable rather than implicit.

❌ Blocker — declined: the synchronous fallback is invisible to planner thread accounting

When CH_REMOTE_ASYNC_IO is zero, readAsync calls blocking read even while
async_socket_for_remote remains true. Both analyzers use only that setting to identify blocking
remote reads, so max_threads = 1 produces one blocking stream. Incorporate the build capability
into both is_sync_remote checks.

The mechanism is real and is disclosed in the description with the measurement (15.15 s vs 1.65 s)
and the control that isolates it (async_socket_for_remote = 0 gives 1.60 s on both binaries,
so synchronous remote reads are not slow — synchronous reads while the setting claims asynchronous
are). The finding is declined for four reasons.

It is not introduced here. is_sync_remote is byte-identical to master, and this pull request
touches neither src/Planner/ nor InterpreterSelectQuery.cpp. readAsync is already
#if defined(OS_LINUX) || defined(OS_DARWIN) with #else return read(); while the planner is
platform-blind, so a FreeBSD, SunOS or Android build of master today takes the blocking path with
the setting still true and no compensation. This change widens that pre-existing condition by
exactly one configuration.

The proposed remedy was reviewed and rejected — three times, at three successively larger
designs.
Making is_sync_remote build-aware raises both the stream limit and the whole-plan
thread limit, replacing limits chosen by local storage; 02845_threads_count_in_distributed_queries
asserts the bounded behaviour the setting is supposed to give, so adopting it would require
weakening an existing regression test. Two larger shapes then failed as well: a step-local thread
increase is unconditionally re-clamped by the query plan, and the candidate ReadFromRemote sites
are not the complete carrier set once pipelines are composed. The shape that survives requires
defining thread-accounting composition semantics for unions, joins, selectors and completed
pipelines. That is why it is a separate follow-up with its own review surface, and I will link it
here when it opens. A second independent pass raised the same finding on byte-identical code and
downgraded it from blocker to major; it added one correct observation, that
01514_distributed_cancel_query_on_error can also observe the wrong shard failing first, which is
already measured (127.3 on the control, 127.2 without fibers) and already named in the
description.

The finding's CI argument does not hold. It rests on 01602_max_distributed_connections
failing. arm_msan has exactly one job in the whole configuration, Stress test (arm_msan); on it
run_func_test collects each worker's return code into a list it uses only as a completion counter
and its caller discards the return value, so a stateless failure cannot redden the job. Neither
01602 nor 01514 is in that job's smoke check or hung check, and no query can reach the
hung-check threshold because the test kills each at timeout 10.

One correction of my own, found while checking that argument. The description previously said
only that arm_msan has one job. The arm_msan binary does reach stateless tests through a second
door — Bugfix validation (functional tests, aarch64) runs each ARM build type in turn — which
cannot surface this cost (it runs only the tests a pull request changes, this one changes none, and
it is allow_failure), but the sentence was too strong and now names it.

⚠️ Major — declined: no live regression evidence that every fiber path is eliminated

No test or build check was added for the new capability or its six guards. Provide generated-code
evidence for the target configuration, with controls showing the guarded paths remain present
elsewhere.

The review noted it had no AArch64 MemorySanitizer object available. All four requested artefacts
exist and were re-derived independently during adjudication: both macros are 0 on the target and
1 across six other configurations, asserted with the real build flags; the fiber constructor
references disappear on aarch64 + MemorySanitizer and are measured as retained in every other
configuration; and reverting each of the six guards individually makes the constructor it dominates
reappear, with a clean unmutated control first — including reverting the macro definition, so the
single source is itself load-bearing. That last suite is exactly the "deterministically fail if one
guard is reverted" property the finding asks for.

Adjudication added the build-viability half: all eleven translation units that touch fibers compile
for aarch64-linux-gnu -fsanitize=memory with the real flags and -Weverything -Werror, zero
diagnostics, with a positive control proving those invocations are not vacuous. That result is now
summarized in the description.

An automated check is not available for this defect: arm_msan has no unit-test job, and the crash
needs a live fiber teardown on an aarch64 + MemorySanitizer build, which no functional or
integration test can express. The description says so, including that a single green
Stress test (arm_msan) run is not proof and that the durable check is the signature count over
three or more weeks.

A second independent pass over the same code raised both findings again, and added the claim that
04093_msan_fiber_distributed_false_positive "can no longer reach the fiber path on its declared ARM
MSan target". That one is measurably false, and it is worth stating why: there is no arm_msan
stateless job anywhere in the configuration, so that test has never run on an arm_msan binary,
before or after this change. Of the twenty stateless paramsets the only ARM ones are
arm_binary, parallel and arm_binary, sequential, and the only MemorySanitizer ones are
amd_msan, WasmEdge, parallel and amd_msan, WasmEdge, sequential; the single arm_msan paramset
in the tree belongs to the stress job, which does not run this test. Where the test does run,
CH_REMOTE_ASYNC_IO is 1 — re-measured — so it keeps its full fiber coverage and its padding-shadow
oracle is untouched. The header comment naming ARM MemorySanitizer describes the configuration the
defect was found in, not a job that exists.

💡 Nit — noted, not blocking: one field's build survives by accident

read_packet_type_separately did not get the [[maybe_unused]] its sibling packet_in_progress
received here, and under CH_REMOTE_ASYNC_IO == 0 both fields lose every read. It builds only
because its constructor initializer is a function call, which clang counts as a use — a field
initialized from a literal in the same position is a hard -Wunused-private-field error, and
dropping the annotation from packet_in_progress reproduces exactly that. So the asymmetry is an
incidental suppression rather than a designed one: simplifying that initializer would stop this
configuration building, with a diagnostic that reads as unrelated. The tree builds clean today, so
this is recorded in the description rather than changed.

Session id: cron:clickhouse-review-slot-48:20260727-130500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? For the mechanism, yes and deterministically: a checker over the generated assembly of the unmodified contrib/boost header (clang++-21 --target=aarch64-linux-gnu -O2 -fsanitize=memory -DBOOST_USE_UCONTEXT -DBOOST_USE_MSAN) reports 3 stale-thread-pointer uses at exactly the instructions that fault in CI, and 0 for a control build. For the crash itself, no local repro is possible: it needs an aarch64 plus MemorySanitizer build and a fiber teardown, and no functional test can express that. Stated as a limitation rather than glossed over; the fix's oracle is the object-level assertion suite in (e).
b Root cause explained? Yes, at instruction level on the exact failing CI binary (Build ID b337b381a47106833eee64c02435cbed21e2b920, matching the build id: in fatal.log). boost::context::fiber::resume() && reads the thread pointer once in its prologue (mrs x22, TPIDR_EL0), calls fiber_activation_record::resume() which runs ::swapcontext() and lands on a different OS thread, then on the force_unwind throw path executes str xzr, [x22, x23] using the now-stale x22. x22's only writes in the function are that prologue mrs and an epilogue ldp on the fall-through return path the b.eq skips. The offsets resolve against the binary's symbol table to __msan_param_tls, __msan_retval_tls and __msan_va_arg_tls. Arch-exclusive: the same TU at --target=x86_64-linux-gnu has 30 fs: accesses and 0 mrs, because x86-64 MSan TLS is segment-relative and resolved per access.
c Fix matches root cause? Yes. It removes the precondition — a fiber resumed on a foreign thread — in the only configuration where the hazard exists, by widening five build guards that already choose between an asynchronous and a synchronous path. It does not guard the crash site, suppress a sanitizer, widen a bound, or reduce data. Three alternatives were measured and rejected: asm volatile("" ::: "memory") barriers in contrib/boost (caller-side, callee-side and the explicit mrs + opaque-input idiom all still yield 3 violations, because LLVM treats the AArch64 thread pointer as a rematerializable leaf, not memory); __attribute__((no_sanitize("memory"))) on fiber::resume() (silences the codegen but drops 12 __msan_warning checks and covers no other suspended frame, while a frame-shaped probe shows any instrumented frame live across a suspend has the same hazard); and scheduler thread affinity (cannot cover the forced-unwind path all 16 CIDB hits take, since cancelBefore and destroyFiber resume on the calling thread, bypassing any queue). The compiler behaviour itself is disclosed as unfixed and belongs upstream in LLVM.
d Test intent preserved / new tests added? No test is weakened, removed, retagged, or given a wider bound; no no-random-* tag is added. No new test file, and none is possible: the defect requires an aarch64 plus MemorySanitizer build. The regression guard is the object-level assertion suite described in (e) — predicate correctness across 7 configurations, a no-fiber-symbol structural check, and a per-site mutation matrix.
e Both directions demonstrated? Yes, twice over, at object level. Structural: on aarch64 with MemorySanitizer all four fiber constructor references disappear from the objects (2+1+1 to 0+0+0) and are retained in all four other configurations, measured against master's own content for the same configurations so "retained" is not assumed. Mutation: with a clean unmutated control first (fiber constructor references = none), reverting each of the six guards individually makes the constructor it dominates reappear — including reverting the CH_REMOTE_ASYNC_IO definition itself, so the single source the guards are written in terms of is also load-bearing. Every file was restored and sha256-verified. Additionally the predicate was asserted 7/7 across configurations with the real build flags, so it cannot be silently always-1.
f Fix is general across code paths? Yes. The carrier sweep covers all construction forms (grep -rn "ConnectionEstablisherAsync|PacketReceiver|RemoteQueryExecutorReadContext|HedgedConnectionsFactory|HedgedConnections\b" src/), not just make_unique — a make_unique-only grep misses two carriers. Six construction sites tree-wide, all dominated by the five guards; grep -rn "public AsyncTaskExecutor" src/ = exactly 3 subclasses, so there is no fourth; grep -rn "boost/coroutine" src/ is empty. Three candidates were checked and excluded: QueryPipeline/DistributedPlanExecutor.cpp together with Server/DistributedQuery/ExchangeConnections.h (0 fiber references — their OS_LINUX || OS_DARWIN guards select the streaming-exchange port config and pending-stream cleanup), Common/checkStackSize.cpp (reads the current fiber's bounds, constructs none), and distributedIndexAnalysis's asynchronous read path (raw Epoll, no fibers — gated anyway because its #else throws). The condition itself is single-source: grep -rn "defined(OS_LINUX) || defined(OS_DARWIN)" src/QueryPipeline/ src/Common/ shows the async-remote-IO condition exactly once, in the new header; the remaining hits are EventFD/Epoll/TimerDescriptor and unrelated platform APIs, which exist regardless of fibers.
g Fix generalizes across inputs (params/datatypes/wrappers)? Inputs are irrelevant by construction: the guard is compile-time, so no setting value, SET, statement-level SETTINGS, DEFAULT reset, profile, or tests/clickhouse-test randomizer can produce a fiber in this build. That is precisely why this layer was chosen over applySettingsQuirks, which is bypassable (Context::setSettings, setSettingWithLock and resetSettingsToDefaultValue never call it, and InterpreterSetQuery::executeForCurrentContext applies changes then resets defaults). One of the six construction sites (ConnectionPoolWithFailover.cpp) is gated on async_callback rather than on any setting, so no settings-level scheme could ever have covered it. Setting values are left untouched, so 02324_compatibility_setting.sh and 02995_new_settings_history.sh are unaffected by construction.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry is required — that file is not in the change set and no DECLARE or default is touched. No serialization, wire-format or on-disk change. On every configuration ClickHouse ships, CH_REMOTE_ASYNC_IO is 1 and the generated code is identical to master, measured across 24 translation-unit-by-configuration combinations with a control proving the comparison can detect a real difference. The new header also costs 0 preprocessed lines in all six affected translation units, and because both macros are always defined as 0 or 1, a dropped include becomes a build failure under -Werror,-Wundef rather than a silently disarmed guard. Build viability on the target was then checked rather than assumed: all eleven translation units that touch fibers compile for aarch64-linux-gnu -fsanitize=memory with the real build flags and -Weverything -Werror, zero diagnostics, with a positive control proving those invocations are not vacuous. Compiling out a code path can strand a private member, and one is: packet_in_progress needs the [[maybe_unused]] added here, while read_packet_type_separately survives only incidentally, because its constructor initializer is a function call.
i Invariants and contracts preserved? Each of the five widened guards already had a working synchronous counterpart on its #else side, exercised today by non-Linux builds: readAsync to read(), sendQueryAsync to sendQuery(); return -1;, the hedged branch to MultiplexedConnections, tryGetEntry to the synchronous ConnectionEstablisher, and in distributedIndexAnalysis the synchronous variants beside the selectors. One deliberate asymmetry: in distributedIndexAnalysis I gated the selectors, not establishConnectionsAsync/executeRemoteAnalysisAsync's own #ifs, whose #else throws LOGICAL_ERROR "Hedged connections are not supported on this platform" — gating the implementations would have converted a crash into an exception. processParallelReplicaPacketIfAny is guarded because it dereferences read_context unconditionally while read_context is never created without the asynchronous path; packet_in_progress, use_hedged_requests and use_async_reading become [[maybe_unused]] since their only readers are compiled out. Verified on a real binary with the predicate forced on: correct results, no hangs, SuspendSendingQueryToShard stays 0, and the four tests that set these settings explicitly all pass. The one behavioural consequence — serialized multi-shard reads at low max_threads, caused by a pre-existing master defect where the planner keys stream parallelism on the setting rather than on whether the read blocks — is measured (15.15 s versus 1.65 s), disclosed in the PR description with its control, and is being fixed separately.

Session id: cron:clickhouse-review-slot-48:20260727-130500

@groeneai

Copy link
Copy Markdown
Collaborator Author

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 RemoteQueryExecutorReadContext fiber segfault that hits Stress test (arm_msan) weekly becomes unreachable; every other configuration is byte-identical, and the disclosed cost plus its pre-existing planner cause are in the description.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e116c8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
00084_external_aggregation FAIL cidb
Integration tests (arm_binary, distributed plan, 2/4) FAIL
test_storage_s3_queue/test_system_stop.py::test_stopped_table_releases_hash_ring_slot FAIL cidb
test_storage_s3_queue/test_system_stop.py::test_refresh_survives_unready_dependencies FAIL cidb

AI Review

Summary

This PR compiles the fiber-backed remote query send/read and hedged-connection paths out of the aarch64 + MemorySanitizer build by routing those sites to their existing synchronous fallbacks. I reviewed the current head, the full PR discussion, the changed call sites in RemoteQueryExecutor, ConnectionPoolWithFailover, and distributed index analysis, and the green Praktika report, and I did not find a correctness, compatibility, or CI-only regression that still warrants a review finding.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 27, 2026
groeneai added 2 commits July 27, 2026 19:04
`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.
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.20% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 39/40 (97.50%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6e116c8

CI fully finished on this head (Finish Workflow success, 174 check-runs, 0 queued/in progress).
Every failure below has an owner.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, distributed plan, 2/4) / test_system_stop.py::test_stopped_table_releases_hash_ring_slot + ::test_refresh_survives_unready_dependencies Server abort (signal 6, libcxx verbose_abort) in ObjectStorageQueueSource::FileIterator::next on the out-of-bounds read in the compaction block; confirmed in this job's own report, which carries the FileIterator::next and verbose_abort frames plus Crash in instance. hash_ring_slot is the crasher, refresh_survives_unready_dependencies is collateral and fails at its first query (DROP TABLE IF EXISTS at helpers/s3_queue_common.py:230) with Code: 210 Connection reset by peer against the already dead server, so both rows are one event and one line. #108977 (ours, open, approved 2026-07-26)
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 00084_external_aggregation Code: 241 MEMORY_LIMIT_EXCEEDED, "would use 313.90 MiB, maximum: 286.10 MiB" on the second aggregation query, i.e. the test's own max_memory_usage = 300000000 leaving only a few percent of headroom over the spilling peak. The runner's rerun passed, so it is not deterministic here. #112054 (external, open)

Not caused by this pull request: the diff is ConnectionPoolWithFailover.cpp, Fiber.h, RemoteAsyncCapability.h, distributedIndexAnalysis.cpp and RemoteQueryExecutor.{cpp,h}, with nothing under src/Storages/ObjectStorageQueue/ and no change to 00084_external_aggregation.sql or to aggregation memory accounting. Neither owner PR is merged, so git show origin/master:src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp | grep -c compact_file_metadatas is still 0 and the recurrence on this head is expected rather than a failed fix; there is nothing to pick up by merging master.

Session id: cron:our-pr-ci-monitor:20260728-070000

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

Are you sure we need this after #111656 ?

Cc @Algunenano

UPD: although it is about darwin...

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

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 src/Common/StackTraceServiceSignal.h (added by #111656) and 6 occurrences of asynchronous_stack_unwinding in StackTrace.cpp, and both pin contrib/boost at e24b1b25e334 (the bumped pin). Stack in both is identical to the pre-#111656 hits, at fiber_ucontext.hpp:530 boost::context::fiber::resume().

On the contrib/boost bump specifically, since that is the one part of #111656 that is not Darwin-only. It contains two commits. The AArch64 MSan one ("Unpoison fiber stack after context switch on AArch64", boost PR 46) was merged at 806cec1c whose second parent is 24df31b3 - i.e. it was already in the pre-bump pin, so #111656 did not add it. What the bump adds is boost PR 47, str xzr, [x0, #0x90] in make_fcontext, zeroing the saved frame-pointer terminator. Its own comment says it is "harmless on Linux, which unwinds via CFI"; it makes a frame-pointer walker stop cleanly, which is exactly the macOS backtrace() path #111656 targets.

Different mechanism. #111656 repairs a stack walk that reads off the fiber stack. This one is a store: on AArch64 with -fsanitize=memory clang materialises the thread pointer into a callee-saved register and keeps it live across the fiber stack switch, so the next MSan shadow-TLS store uses the previous thread's pointer. Disassembled in the exact failing binary (Build ID b337b381a47106833eee64c02435cbed21e2b920): x22 is written only by the prologue mrs x22, TPIDR_EL0 and by an epilogue ldp on the fall-through return that the b.eq skips. The fault address is TPIDR_EL0-relative and outside MSan's allocator band, so it is not a fiber-stack overflow. Nothing in it involves unwinding.

Different platform, as you noted in your UPD. All 17 CIDB hits over 100 days are Stress test (arm_msan), aarch64 Linux; none on any Darwin check.

File sets do not intersect either: #111656 touches QueryProfiler.cpp, SignalHandlers.{cpp,h}, StackTrace.cpp, StackTraceServiceSignal.h, StorageSystemStackTrace.{cpp,h}, contrib/boost; this PR touches ConnectionPoolWithFailover.cpp, Fiber.h, RemoteAsyncCapability.h, distributedIndexAnalysis.cpp, RemoteQueryExecutor.{cpp,h}.

For completeness: merged #110152 (mine) does not fix this one either - it addresses the padding-shadow defect, and the crashing binary already contains it.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh clickhouse-gh Bot unassigned azat Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026

This branch has not been deployed

No deployments
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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants