Skip to content

Keep the stack when an async signal arrives during an MSan report - #112008

Merged
nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-msan-fiber-stack-amd
Nov 4, 2026
Merged

nickitat merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-msan-fiber-stack-amd

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

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

Bumped contrib/llvm-project so MemorySanitizer reports keep their stack trace when an asynchronous signal is delivered while the report is being printed. Affects MSan builds only.

Description

When an asynchronous signal lands on a thread that is printing a MemorySanitizer report, and its handler trips a second MSan check, the runtime prints MemorySanitizer: nested bug in the same thread, aborting. and exits. The report keeps only its header line: no stack, no origin, no SUMMARY. CIDB buckets these as MemorySanitizer: use-of-uninitialized-value (STID: None).

ScopedErrorReportLock is held for the whole report, which takes seconds because each frame is symbolized through an llvm-symbolizer subprocess. ClickHouse/llvm-project#118 (merged) blocks asynchronous signals for the duration of the report in PrintWarningWithOrigin, so the handler runs after the report instead of inside it. Synchronous signals stay unblocked, so a crash while reporting still aborts.

This PR points contrib/llvm-project at fa3910d6, the merge of ClickHouse/llvm-project#118 on ClickHouse/release-22.x. Its first parent is master's pin 140ad525, so the bump adds only #118 (msan.cpp and its lit test).

The main source of such signals was the sampling query profiler. #113107 compiled it out under MSan for this reason (src/Common/QueryProfiler.h). Since then the bucket has one row, on 26.7, which does not have #113107: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.7&sha=44b97ab05c6aa7cfe2f72588d9f6dc8651508b9a&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28amd_msan%29. With this runtime the re-entry described in that comment cannot happen.

Validation: the in-tree clang_rt_msan built from this tree with clang-22, against #118's lit test (compiler-rt/test/msan/Linux/nested_report_async_signal.cpp, which raises the signal from inside the report). With this runtime 30/30 runs pass FileCheck with a full stack and no nested abort; with the unpatched clang-22 runtime 30/30 abort with no frames. ClickHouse CI does not run that lit suite; this PR's CI shows the runtime builds and MSan jobs run with it.


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

Version info

  • Merged into: 26.11.1.1379-master (included in 26.11 and later)

Bump contrib/llvm-project to pick up a compiler-rt fix for MSan reports that
arrive with no stack at all:

    ==117==WARNING: MemorySanitizer: use-of-uninitialized-value
    MemorySanitizer: nested bug in the same thread, aborting.
    LLVM ERROR: IO failure on output stream: Broken pipe

Printing a report is slow, because it round-trips to the out-of-process
llvm-symbolizer. QueryProfiler arms a per-thread timer on every query thread, so
an async SIGUSR1/SIGUSR2 regularly lands in that window; if the handler touches
uninitialized memory, ScopedErrorReportLock sees same-thread reentrancy and
calls internal__exit without printing anything. The report that mattered is
gone, and CIDB buckets every such failure under the synthetic test name
"MemorySanitizer: use-of-uninitialized-value (STID: None)".

The runtime change blocks asynchronous signals for the duration of the report
funnel, keeping the synchronous signals deliverable so a real crash while
reporting still aborts.

This is an observability fix: it does not fix any of the uninitialized reads,
it makes them diagnosable. 11 of these landed in the last 30 days on x86_64
alone, none with a usable stack.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent model reviewed this change cold against the ClickHouse review skill, and a
separate reviewer pass enumerated the invariant carriers before reading the author's evidence.
Findings and verdicts:

# Finding Verdict
⚠️ The regression test could pass on a runtime without the guard: the timer armed the signal 300 us ahead of the outer report, and every assertion (WARNING, #0, #1, heap-origin line, SUMMARY) is satisfied identically by the handler's own heap UMR, so the degenerate "signal first" ordering never needed the guard. AGREE, fixed. The signal is now raised from inside the report through the weak __sanitizer_on_print hook (in-tree precedent: test/sanitizer_common/TestCases/onprint.cpp), and #0 is pinned to report_here, so no report other than the outer one can satisfy the file. Mutation-proved: the test fails with the guard removed.
⚠️ The description claimed this PR's own AST fuzzer (amd_msan) / Stress test (amd_msan) runs were the end-to-end proof. They are not: the signature fires in under 0.15% of MSan runs (23 hits over 7659 + 8613 runs in 30 days), so a green run says nothing about the guard. AGREE, fixed. The description now states what this PR's CI can and cannot show, and attributes the proof to the 50-run both-directions measurement on ClickHouse's own rebuilt runtime with a one-line mutation control.
❌ The gitlink names a submodule commit that ClickHouse/llvm-project does not serve, so a shallow submodule checkout cannot populate contrib/llvm-project. Verified in a fresh clone: git fetch --depth 1 origin 2e96bd5b722ea3 returned upload-pack: not our ref. AGREE, and it is why the library PR was opened first. GitHub serves an open fork PR's objects from the upstream repository, so the same fetch succeeds once that PR exists; the control fetch of an unrelated open fork PR's head from the same remote succeeded throughout. Re-verified after opening it, before this PR was created.
💡 Style, ClickHouse-facing text only: one em-dash in the validation-gate comment, and three f()-form function references where AGENTS.md asks for f. AGREE, fixed. The library-PR text keeps compiler-rt's own f() convention.

Checked and found correct, so noted rather than changed: the mask covers every UMR report
(all eight PrintWarningWithOrigin call sites, single ReportUMR caller), sits after the
msan_expect_umr early return, and is deliberately not extended over the caller's Die:
ScopedErrorReportLock releases inside ReportUMR, so the same-thread branch is already
unreachable there, and masking SIGABRT across Abort would be wrong. The SANITIZER_LINUX
gate is load-bearing rather than cosmetic: sanitizer_linux.h's own guard is the broader
FREEBSD || LINUX || NETBSD || SOLARIS || HAIKU, and ClickHouse links the in-tree compiler-rt on
FreeBSD too, where BlockSignals has no synchronous-signal exemptions and would mask SIGSEGV.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and deterministic by construction rather than by timing: the new lit test raises the signal from a __sanitizer_on_print override, which the runtime calls for every line it prints, so it always lands while the report lock is held. not %run against a runtime with the guard removed aborts 50/50 with nested bug in the same thread and zero frames; with the guard present, all 50 runs show the nested report was genuinely attempted (a second, handler-rooted report appears in every run) while the outer report survives intact. No ClickHouse server or binary needed.
b Root cause explained? Yes. ScopedErrorReportLock::Lock records the reporting thread in reporting_thread_ and clears it only in Unlock. ReportUMR holds it across stack->Print, DescribeOrigin and ReportErrorSummary, all of which round-trip to the out-of-process llvm-symbolizer. QueryProfiler arms a per-thread timer with SIGEV_THREAD_ID/SIGUSR1(SIGUSR2) on every query thread; a signal landing in that window whose handler reads uninitialized memory re-enters the lock, takes the same-thread branch at sanitizer_symbolizer_report.cpp:319 and calls internal__exit without printing. The abandoned symbolizer pipe adds the LLVM ERROR: ... Broken pipe line.
c Fix matches root cause? Yes. It prevents the nested entry, which is the cause. Suppressing the print instead cannot work: __msan_warning_noreturn calls Die unconditionally after the funnel returns, so report #1 would still be truncated.
d Test intent preserved / new tests added? New lit test compiler-rt/test/msan/Linux/nested_report_async_signal.cpp in the library PR, mutation-proved live and proved discriminating: it pins the surviving frame to report_here, so the degenerate interleaving where the signal lands before the report even starts cannot satisfy it. Checked that directly, by building that interleaving and running it on a runtime without the guard: it prints a clean handler-rooted report, which name-free frame assertions would have accepted. No existing test weakened or removed. Note honestly: ClickHouse CI does not build or run compiler-rt's lit suite, so that test guards the fork and is runnable by hand. The guard itself is proven by the 50-run both-directions measurement on ClickHouse's own runtime with the one-line mutation control (row e), NOT by this PR's MSan CI: the signature fires in under 0.15% of MSan runs (23 hits over 7659 AST fuzzer (amd_msan) plus 8613 Stress test (amd_msan) runs in 30 days), so a green run here shows only that the bumped runtime builds and that MSan jobs behave normally with the mask in place. No SQL test: there is no SQL-visible behaviour to assert.
e Both directions demonstrated? Yes, on ClickHouse's own rebuilt clang_rt_msan, 50 runs each: guard present 0/50 aborts and 1600 stack frames (full stack + origin chain + SUMMARY); guard removed 50/50 aborts and 0 frames, failing on the #0 .*report_here frame assertion. The mutation changed exactly one line, and the restore was verified real (archive md5 returned to its pre-mutation value, committed diff byte-identical to the validated patch). Fixed and mutated binaries carry distinct Build IDs.
f Fix is general across code paths? Yes. Every UMR report funnels through PrintWarningWithOrigin: __msan_warning, __msan_warning_noreturn, __msan_warning_with_origin, __msan_warning_with_origin_noreturn, the MSAN_MAYBE_WARNING_* path, __msan_check_mem_is_initialized, and the interceptor path. Fixed at the funnel, not at the abort site. ReportUMRInsideAddressRange prints before the funnel and is not masked; measured safe (0 nested aborts, full stack) rather than assumed. Deliberately out of scope: the ASan/TSan/UBSan funnels (this signature appears only on msan checks), nesting from a different thread (correctly serialized by the lock), and non-Linux platforms (unchanged).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The input axis is which async signal, and BlockSignals masks all of them while exempting the synchronous set, so nothing is keyed to SIGUSR1/SIGUSR2. Verified with an in-report raise(SIGUSR1), a SIGEV_SIGNAL timer, a SIGEV_THREAD_ID timer, and pthread_kill of SIGSEGV/SIGABRT. Type wrappers are N/A (sanitizer runtime C++, no ClickHouse types).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no serialization format, no SettingsChangesHistory.cpp entry. Blast radius is MSan builds only, since clang_rt_msan is built only under SANITIZE=memory; release, debug, ASan, TSan and UBSan builds are unaffected. The behaviour change is strictly additive observability.
i Invariants and contracts preserved? Yes. New invariant: no async signal is delivered while reporting_thread_ names this thread. The mask is RAII-scoped to the report body and released on every path including early return, before the caller's Die, by which point ScopedErrorReportLock has already cleared reporting_thread_, so the same-thread branch is unreachable and extending the mask over Die is unnecessary. Synchronous-crash delivery is preserved: a SIGSEGV raised inside the window still produces a deadly-signal report and aborts (3/3), and a helper thread hammering SIGSEGV/SIGABRT through the whole window still kills the process (3/3 each). SIGSYS and SIGSETXID stay unblocked, avoiding the documented seccomp-trap and setuid-hang hazards, and KeepUnblocked never widens delivery for a signal the caller had blocked. No new state, no TLS, no counters: ScopedBlockSignals is MSan's existing helper for this, already used by MsanTSDDtor and the pthread_create interceptor, with its own unit test.

Session id: cron:clickhouse-impl-slot-5:20260727-021900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @rschu1ze - could you review this? It bumps contrib/llvm-project for a compiler-rt change that stops MSan from throwing away a report's stack when an asynchronous profiler signal lands mid-report, which is why 23 MSan failures in the last 30 days arrived with zero frames and STID: None. The library PR is ClickHouse/llvm-project#118, and the pin currently points at its head so CI can validate it before that PR merges.

@thevar1able thevar1able self-assigned this Jul 27, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9140a42]

Summary: ✅


AI Review

Summary

This PR advances contrib/llvm-project to preserve MSan report stacks when asynchronous signals arrive during reporting. At PR head 9140a421e2c6f1b809c81f3553b77a73cf948aa9, the existing finding about signal-mask inheritance remains unresolved: temporary report protection becomes permanent in a lazily launched symbolizer subprocess. Request changes.

Missing context / blind spots
  • ⚠️ The current head's Build (amd_msan) and Build (arm_msan) checks remain queued. The runtime was not rebuilt locally because this checkout has an unpopulated LLVM submodule and no compiler toolchain; the reported mutation-test results were not independently rerun.
Findings

⚠️ Majors

  • [P2] contrib/llvm-project:1 — Restore the original signal mask in the symbolizer child. In the pinned runtime, PrintWarningWithOrigin blocks asynchronous signals before ReportUMR prints the stack. First-time symbolization can launch llvm-symbolizer through StartSubprocess, which calls internal_fork and internal_execve without restoring the child's mask. Both preserve the mask, so the child keeps SIGINT and SIGTERM blocked after the parent's report ends. Slow or stuck symbolization therefore cannot be interrupted or terminated normally, and cleanup must escalate to SIGKILL. Preserve the pre-report mask and restore it in the child before executing the symbolizer, while keeping the reporting thread protected; update the dependency pin to include that fix. The existing inline finding remains applicable and was not duplicated.
Tests
  • ⚠️ Add a focused regression that launches the external symbolizer for the first time during an MSan report and checks that the child preserves the pre-report signal mask. The added nested_report_async_signal.cpp verifies that the outer report survives SIGUSR1, but does not check the subprocess's mask.
Final Verdict

⚠️ Request changes — Restore the symbolizer child's pre-report signal mask, add the startup regression, and update contrib/llvm-project to the corrected commit.

@clickhouse-gh clickhouse-gh Bot added pr-ci submodule changed At least one submodule changed in this PR. labels Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bc44d00

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica 1 for unknown stream + the accompanying Server died trunk bug in the parallel-replicas reading coordinator (the abort kills the shard, so Server died is the same event, not an independent failure) #111689 (ours, open)
Stress test (arm_asan_ubsan, s3) / UndefinedBehaviorSanitizer (STID 0250-4a9f) — toStartOfInterval.cpp:293:80 signed integer overflow: -9223372036854775808 + -3600000000000 trunk bug: origin + offset overflows at the Int64 minimum in the origin overload of toStartOfInterval #112045 (external, open)
Stateless (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 04257_text_index_lazy_profile_events flaky, not PR-caused — result differs only in the final aggregate row, where the last two tagged queries report 0 instead of 1. 5 hits / 5 distinct PRs over the last 12 days across two lanes. a fix task is created (investigating at full effort — fixing-PR link to follow here)

Not PR-caused: this PR's diff is a single contrib/llvm-project submodule gitlink bump, which
cannot affect the parallel-replicas coordinator, toStartOfInterval arithmetic, or text-index
ProfileEvent accounting.

Session id: cron:our-pr-ci-monitor:20260727-120000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 04257_text_index_lazy_profile_events created: #112263

The counters are incremented on whichever replica reads the granule, and remote ProfileEvents are not merged into the initiator's system.query_log row, so under parallel replicas they land on secondary rows that the assertion's current_database = currentDatabase() predicate excluded. The fix selects the rows that own the events instead, leaving every assertion and the expected output unchanged.

@nickitat

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Dear @thevar1able, 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.

…m-project#118

The only conflict was the contrib/llvm-project gitlink: this branch pinned
the head of ClickHouse/llvm-project#118 (2e96bd5b722e), master moved its pin
to daf4510ca312. ClickHouse#118 is now merged on ClickHouse/release-22.x as
fa3910d62714, which contains both, so the gitlink is resolved to it.

Relative to master's pin this brings in ClickHouse#118 (compiler-rt/lib/msan) and
ClickHouse#140 (libc++ `_LIBCPP_DISALLOW_PRINTING_POINTERS`, a no-op unless the macro
is defined).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread contrib/llvm-project
@@ -1 +1 @@
Subproject commit daf4510ca312fc47275c01813424b2e7362acf56
Subproject commit fa3910d62714b59592f64dfd33e9e3d0dc5926e4

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.

[P2] Restore the original signal mask in the symbolizer child

The new ScopedBlockSignals also covers the lazy startup of the external symbolizer: ReportUMR calls stack->Print, which can reach SymbolizerProcess::StartSymbolizerSubprocess. At this pin, StartSubprocess uses internal_fork followed by internal_execve without restoring the child’s signal mask. Both operations preserve the mask, so llvm-symbolizer starts with SIGINT and SIGTERM blocked. Restoring the mask in the reporting thread does not restore it in that child.

Consequently, the temporary report protection becomes permanent in the symbolizer, preventing normal interruption/termination of slow or stuck symbolization and forcing timeout cleanup to escalate to SIGKILL. Please preserve the pre-report mask and restore it in the symbolizer child before executing it, while keeping the reporting thread protected. Add a focused startup regression that checks the child’s mask; the current in-report SIGUSR1 test does not exercise this boundary.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 43fe907

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff / LogClusterNotReady: the endpoint never became ready CI infra, not from this PR (it changes only the contrib/llvm-project pin): the CI logs cluster rejects the readiness probe, so the job never compares anything. Every Build profile diff run since 2026-10-26 22:00Z is red the same way (75 runs on 72 PRs, 0 green) #126200 (mine, open)
Stateless tests (amd_debug, sequential) / 05218_text_index_substreams_opened_lazily flaky, not from this PR: in_range_above_threshold 1 -> 0; the runner's random-settings diagnosis isolates use_columns_cache = 1 (19/19 fail with the draw, 20/20 pass without). The fix merged at 01:19Z and is absent from the merge commit this job built #127781 (mine, merged)
Stress test (amd_msan) / Logical error: Cannot write to canceled buffer (STID: 4158-2b4c) not from this PR: the server's embedded client (ClientEmbedded) renders INSERT progress into its canceled terminal buffer (ClientBase::onProgress to ProgressIndication::writeProgress), the exact stack the fix describes #127834 (external, open)
Mergeable Check, PR praktika rollups of the rows above #126200, #127781 and #127834 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-043011

@nickitat

nickitat commented Nov 2, 2026

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

The only conflict was the contrib/llvm-project gitlink: master moved its
pin to 140ad525c086, this branch pins fa3910d62714 (the merge of
ClickHouse/llvm-project#118), whose first parent is 140ad525c086. The
resolution keeps fa3910d62714, which contains both sides.

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

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Resolved the conflict in 9140a42: contrib/llvm-project stays at fa3910d6, whose first parent is master's pin 140ad525, so the PR diff is still that one gitlink.

@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9140a421e with master a13fd8172 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@nickitat
nickitat added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit 8c57ab8 Nov 4, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
PedroTadim pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 6, 2026
Move `contrib/llvm-project` to a cherry-pick of
llvm/llvm-project#175849 directly on top of the
previous pin `daf4510ca312`, so this change no longer pulls in the
`ClickHouse/release-22.x` commits that master does not pin yet. Those
stay with ClickHouse#112008.

Related: ClickHouse#127601
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-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI 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.

5 participants