Skip to content

Make system.stack_trace work on macOS - #98982

Merged
alexey-milovidov merged 5 commits into
masterfrom
system-stack-trace-macos
Mar 13, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
system-stack-trace-macos

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 8, 2026 •

Copy link
Copy Markdown
Member

Summary

  • The system.stack_trace table was previously Linux-only (guarded by #ifdef OS_LINUX) because it relied on rt_tgsigqueueinfo, real-time signals (SIGRTMIN), and the /proc filesystem
  • Added macOS support using Mach APIs (task_threads, pthread_from_mach_thread_np) for thread enumeration, pthread_kill with SIGUSR1 for signal delivery, and pthread_getname_np for thread names
  • On macOS, the trace column contains raw virtual addresses (resolvable with atos or lldb) because SymbolIndex depends on dl_iterate_phdr which is Linux-only

Test plan

  • Built and ran on macOS (arm64)
  • Verified SELECT count() FROM system.stack_trace returns all threads (757)
  • Verified all threads have non-empty stack traces
  • Verified thread_name, thread_id, query_id columns are populated correctly

Changelog category (leave one):

  • Improvement

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

The system.stack_trace table now works on macOS, allowing introspection of all server thread stack traces.

🤖 Generated with Claude Code


Note

Medium Risk
Adds macOS-specific thread enumeration and signal-handling paths to a low-level introspection table; errors here could cause missed traces, hangs/timeouts, or unintended signal interactions on macOS.

Overview
Enables system.stack_trace on macOS by adding Darwin-specific thread enumeration (Mach task_threads + pthread_from_mach_thread_np), signal delivery (pthread_kill/SIGUSR1), and thread-name retrieval (pthread_getname_np).

Updates synchronization/validation logic in the signal handler for macOS (thread identity checks instead of sigqueue payloads) and adjusts trace address handling to emit raw virtual addresses on macOS (Linux keeps SymbolIndex-based normalization).

Extends addressToSymbol to support macOS via dladdr when SymbolIndex isn’t available, and makes system.stack_trace table registration/header guards include OS_DARWIN.

Written by Cursor Bugbot for commit dc90ccd. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.632

The `system.stack_trace` table was previously Linux-only because it
relied on `rt_tgsigqueueinfo`, real-time signals (`SIGRTMIN`), and
the `/proc` filesystem. This commit adds macOS support using
platform-specific alternatives:

- Thread enumeration via Mach `task_threads` API instead of `/proc/self/task`
- Signal delivery via `pthread_kill` with `SIGUSR1` instead of `rt_tgsigqueueinfo` with `SIGRTMIN`
- Thread name retrieval via `pthread_getname_np` instead of `/proc/self/task/{tid}/comm`
- Signal handler identifies expected thread via `pthread_self` check instead of `si_value` payload
- Raw virtual addresses in trace column (macOS lacks `SymbolIndex` which depends on `dl_iterate_phdr`)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc90ccd]

Summary: ✅


AI Review

1) Summary

This PR adds system.stack_trace support on macOS by switching thread signaling/collection to pthread_kill + Mach thread enumeration, and adds Darwin support in addressToSymbol via dladdr. High-level verdict: the implementation is close, but there is one correctness race in macOS sequence matching that can return a stack trace from a different thread than the requested one.

2) Missing context (if any)

  • No dedicated macOS stress/concurrency test results for system.stack_trace were available in the PR context.
  • No benchmark or reliability data for delayed-signal behavior on busy macOS workloads.

3) Findings (by severity)

  • Blockers
    • None.
  • Majors
    • [src/Storages/System/StorageSystemStackTrace.cpp:157] In the macOS handler, notification_num is taken from sequence_num.load at handler execution time rather than from a per-request token fixed at send time. If a previous signal is delayed, it can be tagged with the current sequence and pass the wait check for a later request, potentially attributing thread A's stack trace to thread B.
    • Suggested fix: generate/store a per-request token before pthread_kill, pass/associate it with the expected responding thread, and validate the exact token in the handler and pipe path before accepting the trace.

4) Tests & Evidence

  • Coverage assessment: changed code has no corresponding new tests in this PR for macOS delayed-signal ordering; Linux behavior has existing mature path.
  • Negative/error-handling tests present: not observed for the new macOS race-sensitive path.
  • Additional tests to add:
    • A deterministic stress test for system.stack_trace that forces delayed delivery / timeout and verifies no cross-thread attribution.
    • A repeated polling test under thread churn (thread create/exit during reads) validating thread_id ↔ trace consistency.

5) ClickHouse Compliance Checklist (Yes/No + short note)

  • Data deletions logged? Yes — no deletion logic introduced.
  • Serialization formats versioned? Yes — no serialization format changes.
  • Experimental setting gate present? Yes — not a new feature requiring gate; platform enablement for existing system table.
  • Settings exposed for constants/thresholds? Yes — existing timeout setting reused.
  • Backward compatibility preserved? Yes — existing schema/behavior preserved on Linux.
  • SettingsHistory.cpp updated for new/changed settings? Yes — no settings changed.
  • Existing tests untouched (only additions)? Yes — no test deletions/relaxations in this diff.
  • Docs/user-facing notes updated? No — user-facing behavior expanded to macOS without doc update.
  • Core-area change got extra scrutiny? Yes — signal handling, thread enumeration, and stack collection were reviewed closely.

6) Performance & Safety Notes

  • Hot-path impact is limited to system.stack_trace query execution; normal query paths are unaffected.
  • Safety risk is correctness of attribution under delayed signal delivery on macOS.
  • Benchmarks are missing; minimal reproducible benchmark: repeatedly query system.stack_trace under high thread churn and injected delay to signal handling, then measure mismatches between expected thread and captured call-path signatures.

7) User-Lens Review

  • Feature is useful and intuitive (system.stack_trace now available on macOS), but current race can produce surprising/incorrect thread traces in edge timing conditions.
  • Error messages are generally actionable, but wrong attribution is silent and can mislead operators during incident analysis.

8) Final Verdict

  • Status: Request changes
  • Minimum required actions:
    1. Fix macOS request/response correlation to use a stable per-request token (not handler-time sequence_num.load).
    2. Add at least one regression test/stress validation for delayed-signal ordering to prevent cross-thread trace attribution.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 8, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Note: this is only moderately useful - just the first step to make this table working.

On Linux, `addressToSymbol` uses `SymbolIndex` which depends on
`dl_iterate_phdr` and ELF parsing. On macOS, use `dladdr` from
`<dlfcn.h>` instead - it resolves virtual addresses to symbol names
directly. This is slower than `SymbolIndex` but works without any
binary format parsing.

Combined with `demangle`, this enables fully symbolized stack traces
from `system.stack_trace` on macOS.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-feature Pull request with new product feature labels Mar 8, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Yes, it works:

SELECT * REPLACE arrayStringConcat(arrayMap(x -> demangle(addressToSymbol(x)), trace), '\n') AS trace FROM system.stack_trace

Unlike `rt_tgsigqueueinfo` (a syscall that sets `errno`),
`pthread_kill` returns error codes directly per POSIX. The previous
code checked `errno` which could hold a stale value, causing a
spurious exception instead of gracefully skipping finished threads.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

On Linux, `si_value.sival_int` is fixed at signal-send time, which
allows the handler to detect stale signals. On macOS, `sequence_num`
is read at handler execution time, creating a race window: if a
handler is delayed past the `wait` timeout and `sequence_num` is
incremented, the handler could read the new value and be mistaken
for a response from the next thread.

Fix by moving the `sequence_num` read and `expected_responding_thread`
re-check to after the `signal_latch` CAS. Since only one handler can
hold the latch at a time, this closes the window where these values
could change between the initial pre-check and actual use.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
errno = saved_errno;
return;
}
int notification_num = sequence_num.load(std::memory_order_acquire);

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.

On macOS this uses sequence_num.load at handler execution time, so a delayed signal can be stamped with the current sequence and pass wait for a later request. That can attribute thread A's stack trace to thread B when the previous signal arrives late. Please capture a per-request token before pthread_kill and verify that exact token in the handler/pipe payload.

@clickhouse-gh

clickhouse-gh Bot commented Mar 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.30% +0.00%

PR changed lines: PR changed-lines coverage: 94.78% (109/115)
Diff coverage report
Uncovered code

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Mar 13, 2026
@alexey-milovidov alexey-milovidov self-assigned this Mar 13, 2026
Merged via the queue into master with commit ac54d5f Mar 13, 2026
160 checks passed
@alexey-milovidov
alexey-milovidov deleted the system-stack-trace-macos branch March 13, 2026 00:38
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants