Skip to content

Add MSan support for fibers and fix dragonbox struct padding - #102158

Merged
alexey-milovidov merged 6 commits into
masterfrom
fix-msan-fiber-context
Apr 9, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
fix-msan-fiber-context

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Apr 9, 2026 •

Copy link
Copy Markdown
Member

Re-applies #101621 (which was reverted in #102005) with an updated understanding of the root cause.

BOOST_USE_MSAN for fiber context tracking: The boost fiber implementation has MSan annotations (__msan_start_switch_fiber/__msan_finish_switch_fiber) around every swapcontext call, but they were gated on BOOST_USE_MSAN which was never defined. Without them, MSan loses track of shadow memory across fiber context switches, causing false positives like STID 4179-5154.

Keep __msan_unpoison with a correct explanation: The original PR #101621 removed __msan_unpoison from FiberStack::allocate, which caused STID 4148-3044 and the revert. Investigation traced the origin to struct padding in return values (e.g. dragonbox's fp_t). Value-initializing the struct does not help: MSan tracks shadow per-field in LLVM IR, not per-byte of the padded representation. When any struct with padding is returned by value, the padding shadow is lost. This is a known unfixed LLVM limitation:

On the main thread stack this is harmless (OS zero-inits pages), but on heap-allocated fiber stacks the dirty padding shadow propagates via stack slot reuse, causing false positives. The __msan_unpoison in FiberStack::allocate is the correct workaround. Updated the comment to explain why.

A test is included that documents this MSan limitation.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102114&sha=5b68859e4e2e0023ace05c14f750a827f75ed7f5&name_0=PR&name_1=Stress%20test%20%28arm_msan%29
See also: #102114

Fixes: #101649

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):

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.695

alexey-milovidov and others added 5 commits April 9, 2026 01:11
The boost fiber implementation (`fiber_ucontext.hpp`) has MSan annotations
(`__msan_start_switch_fiber`/`__msan_finish_switch_fiber`) around every
`swapcontext` call. These annotations tell MSan about fiber stack switches
so it can properly save/restore shadow memory state. However, they are
gated on `BOOST_USE_MSAN`, which was never defined in the build.

Without these annotations, MSan loses track of shadow memory during fiber
context switches, causing false "use-of-uninitialized-value" reports for
values that were written inside fibers — such as `TryResult` fields set by
`ConnectionEstablisher::run` in the async connection path.

Fixes: #101649
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102114&sha=5b68859e4e2e0023ace05c14f750a827f75ed7f5&name_0=PR&name_1=Stress%20test%20%28arm_msan%29
See also: #102114

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Value-initialize `ret_value` in `dragonbox::compute_nearest` to zero the 4 bytes
of tail padding in `fp_t<double,false,false>`. Without this, the uninitialized
padding shadow propagates through stack slot reuse on fiber stacks and can
contaminate unrelated values — causing MSan to report false "use-of-uninitialized-
value" errors (e.g. in `shared_ptr` refcount decrements).

This was the root cause of STID 4148-3044, which triggered the revert of PR #101621.

The test verifies both the fix (padding is clean after `to_decimal`) and the
underlying mechanism (default-init leaves padding uninitialized at offset 12).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
With BOOST_USE_MSAN properly defined (fiber switch annotations) and the
dragonbox padding fix in place, the blanket __msan_unpoison on the fiber
stack is no longer needed. Removing it allows MSan to catch real
uninitialized-value bugs on fiber stacks.

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

clickhouse-gh Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [343615b]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) error

AI Review

Summary

This PR reintroduces MSan fiber support by defining BOOST_USE_MSAN for boost::context, restores __msan_unpoison in FiberStack::allocate, and adds a focused regression test documenting MSan padding-shadow behavior for return-by-value structs. Core logic is sound and aligned with the reported issue, but there is one user-facing wording mismatch in a changed comment that should be corrected for accuracy.

Findings

⚠️ Majors

  • [src/Common/Fiber.h:2] The comment says BOOST_USE_UCONTEXT is defined “for sanitizer builds”, but in this repo it is also defined when BOOST_USE_UCONTEXT=ON even without sanitizers (contrib/boost-cmake/CMakeLists.txt). This can mislead future debugging/config work.
    • Suggested fix: Rephrase to mention both sanitizer and explicit BOOST_USE_UCONTEXT build modes.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix the inaccurate BOOST_USE_UCONTEXT wording in src/Common/Fiber.h to reflect actual build conditions.

@clickhouse-gh clickhouse-gh Bot added pr-ci submodule changed At least one submodule changed in this PR. labels Apr 9, 2026
@alexey-milovidov
alexey-milovidov requested a review from azat April 9, 2026 02:57
@alexey-milovidov
alexey-milovidov marked this pull request as draft April 9, 2026 02:59
… values

Reverting the dragonbox change and restoring __msan_unpoison.

Investigation showed that value-initializing dragonbox's ret_value does NOT
fix the issue: MSan tracks shadow per-field in LLVM IR, not per-byte of the
padded struct representation. When a struct with padding is returned by value,
the padding bytes have no shadow entry and appear uninitialized in the caller
— regardless of how the callee initializes them.

This is a fundamental MSan limitation, not a dragonbox bug. Any struct with
padding returned by value will exhibit this. On the main thread stack it is
harmless (OS zero-inits pages), but on heap-allocated fiber stacks the dirty
padding shadow propagates via stack slot reuse, causing false positives.

The __msan_unpoison in FiberStack::allocate is the correct workaround.
Updated the comment to explain why.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/Fiber.h
#pragma once
/// defines.h should be included before fiber.hpp
/// BOOST_USE_ASAN, BOOST_USE_TSAN and BOOST_USE_UCONTEXT should be correctly defined for sanitizers.
/// BOOST_USE_ASAN, BOOST_USE_MSAN, BOOST_USE_TSAN and BOOST_USE_UCONTEXT are defined via CMake for sanitizer builds.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor wording issue: BOOST_USE_UCONTEXT is not only enabled for sanitizer builds. In contrib/boost-cmake/CMakeLists.txt, it is also defined when BOOST_USE_UCONTEXT=ON (even without sanitizers).

Could you rephrase this comment to avoid implying BOOST_USE_UCONTEXT is sanitizer-only?

Comment thread src/Common/FiberStack.cpp
Comment on lines +76 to +81
/// MSan doesn't track shadow for struct padding bytes through return values
/// (the LLVM IR shadow is per-field, not per-byte of the padded representation).
/// Any struct with padding returned by value will have uninitialized padding shadow
/// in the caller. On the main thread stack this is harmless (OS zero-inits pages),
/// but on heap-allocated fiber stacks the dirty shadow can propagate via stack slot
/// reuse and eventually trigger false positives in unrelated code.

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.

How it is possible?

We allocate stack with zero initialized memory and should not reuse it.

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.

As explained, returning a small (<=16 bytes) struct by value from a function, with some bytes belonging to padding.

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.

Why it does not triggered everywhere? There should be tons of such places.

On the main thread stack this is harmless (OS zero-inits pages),
but on heap-allocated fiber stacks the dirty shadow can propagate via stack slot
reuse and eventually trigger false positives in unrelated code.

And this part I also don't get, we initialize stack with aligned_alloc, it should be zero-initialized.

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.

If the stack memory happens to be zero-initialized (just by a chance of, e.g., using mmap), shouldn't matter for MSan. I also found that this "On the main thread stack this is harmless (OS zero-inits pages)" is pointless.

FP local{};
local.significand = 1;
local.exponent = -1;
EXPECT_EQ(__msan_test_shadow(&local, sizeof(local)), static_cast<intptr_t>(-1))

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.

This test is not reliable, it explicitly uses __msan_test_shadow

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.

It serves the purpose of explicitly checking what MSan has in the shadow memory, and what it does not have.



/// Demonstrates the MSan limitation: struct padding is uninitialized in return values.
TEST(DragonboxMSan, ReturnValuePaddingShadowIsLost)

@al13n321 al13n321 Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Does this test actually crash with msan error without the fix? Or are we taking claude's word that these EXPECT_EQ are representative of what happens in the real code? I asked claude to investigate the same (similar?) msan+fiber issue a week ago, and it came up with a similar supposed root cause and "fix", but couldn't produce a working test (without poking into msan api directly).

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.

It uses a function to check the MSan internals (is something belongs to "shadow"), without touching that memory.

@azat azat Apr 9, 2026 •

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.

+1, I was also trying to make a repro but failed to do so w/o using internal MSan API and I don't think that this is what happens here

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.

without poking into msan api directly

This is what it does. A strange test, but I'll take it :)

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 9, 2026
@thevar1able thevar1able added the post-approved Approved, but after the PR is merged. label Apr 9, 2026
alexey-milovidov added a commit that referenced this pull request Apr 9, 2026
…e positives

On AArch64, LLVM loses MSan shadow for struct-padding bytes in return values
(llvm/llvm-project#54476). On heap-allocated fiber stacks the dirty shadow
accumulates across context switches and propagates via stack-slot reuse,
triggering false positives in unrelated code (e.g. STID 1478-2063 in
`system.text_log`).

The one-time `__msan_unpoison` at fiber allocation is insufficient because
`BOOST_USE_MSAN` (added in #102158) now properly preserves shadow across
context switches — including the dirty padding shadow.

Fix by calling `__msan_unpoison` on the whole fiber stack after every
`__msan_finish_switch_fiber` on AArch64. This clears accumulated dirty
padding without affecting the main thread stack.

Fixes: #102241
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97744&sha=aa7dccac1cbacd8009ec368bdbf6045ff7bc3c29&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Apr 10, 2026
…on fibers

This test reproduces MemorySanitizer "use-of-uninitialized-value" errors
that occur on AArch64 in `vector::erase` called from
`PoolWithFailoverBase::getMany`, running on a fiber stack
(`AsyncTaskExecutor` → `boost::context`).

The root cause: on the fiber's heap-allocated stack, compiler-generated
temporaries from inlined functions leave dirty MSan shadow from struct
padding. This shadow persists across function calls on the fiber stack
and contaminates later stack allocations.

The test runs concurrent distributed queries via `remote()` which go
through `RemoteQueryExecutor` → `ConnectionPoolWithFailover` on fibers.

See also: #102158

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Onyx2406 added a commit to Onyx2406/ClickHouse that referenced this pull request Apr 17, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e positives

On AArch64, LLVM loses MSan shadow for struct-padding bytes in return values
(llvm/llvm-project#54476). On heap-allocated fiber stacks the dirty shadow
accumulates across context switches and propagates via stack-slot reuse,
triggering false positives in unrelated code (e.g. STID 1478-2063 in
`system.text_log`).

The one-time `__msan_unpoison` at fiber allocation is insufficient because
`BOOST_USE_MSAN` (added in ClickHouse#102158) now properly preserves shadow across
context switches — including the dirty padding shadow.

Fix by calling `__msan_unpoison` on the whole fiber stack after every
`__msan_finish_switch_fiber` on AArch64. This clears accumulated dirty
padding without affecting the main thread stack.

Fixes: ClickHouse#102241
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97744&sha=aa7dccac1cbacd8009ec368bdbf6045ff7bc3c29&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

post-approved Approved, but after the PR is merged. pr-ci pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MemorySanitizer: use-of-uninitialized-value (STID: 4179-5154)

5 participants