Skip to content

Support the query/memory profiler and trace_log symbolization on macOS - #109825

Merged
Algunenano merged 28 commits into
ClickHouse:masterfrom
Algunenano:macos-async-signal-safe-unwind
Jul 21, 2026
Merged

Algunenano merged 28 commits into
ClickHouse:masterfrom
Algunenano:macos-async-signal-safe-unwind

Conversation

@Algunenano

@Algunenano Algunenano commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Enable the sampling query profiler, the memory/trace profilers, and system.trace_log symbolization on macOS. These were Linux-only mostly because they were written against Linux-specific primitives, not because of any fundamental gap - the generic async infrastructure and the DWARF/Mach-O readers already work on macOS.

Changes:

  • hasPHDRCache → hasAsyncSignalSafeUnwind: rename the predicate to what it actually gates (async-signal-safe stack unwinding). On Linux it still means "the lock-free dl_iterate_phdr cache is installed"; macOS returns true because it unwinds via frame-pointer backtrace (no dl_iterate_phdr, no loader lock). This starts the TraceCollector on macOS, which the synchronous memory/ProfileEvent trace sources need.
  • Sampling query profiler on macOS: macOS has no timer_create/SIGEV_THREAD_ID, so a single background sampler thread delivers the pause signal to each profiled thread via pthread_kill (the centralized equivalent of the per-thread Linux POSIX timer). Real (wall-clock) and CPU (via Mach thread_info) are both supported. The signal handler and StackTrace capture are unchanged. The first fire is randomized like the Linux timers' initial it_value (a uniform [0, period]). For the CPU timer, jemalloc-style wall polling would halve the short-query sampling probability, so the sampler instead schedules each poll at the wall time the remaining CPU budget would elapse under full CPU use - reproducing Linux's ~duration/period chance of sampling a query shorter than the period. The poll cadence is per-registration, so a short period on one thread does not force thread_info on coarse (e.g. the default 10s global) profilers.
  • system.stack_trace signal on macOS: moved from SIGUSR1 to SIGVTALRM. macOS has no real-time signals, so stack_trace had fallen back to SIGUSR1, which now collides with the query profiler; the profiler keeps SIGUSR1/SIGUSR2 on all platforms.
  • system.trace_log symbolization on macOS: wire TraceLog to the existing Mach-O/dSYM paths in SymbolIndex/Dwarf, so symbols and build_id are populated from the binary's symbol table. Source-line lines resolution needs DWARF, which on Mach-O lives in a separate .dSYM bundle the standard build does not produce (unlike ELF, which embeds DWARF in the binary), so it is populated only when a dSYM is present.
  • Per-thread CPU accounting on macOS: RUsageCounters reads Mach thread_info instead of the unavailable getrusage(RUSAGE_THREAD), populating UserTimeMicroseconds/SystemTimeMicroseconds and OSCPUVirtualTimeMicroseconds (the Mach user+system time is not the exact same quantity as Linux taskstats' scheduler on-CPU time, but is the closest available equivalent).
  • jemalloc allocation profiler on macOS: install a prof_backtrace hook (experimental.hooks.prof_backtrace) that uses the system backtrace() - a validated frame-pointer walk that does not allocate, so it is safe inside the malloc hook. jemalloc's default backtraces crash there on macOS: libunwind's DWARF stepper null-derefs, and the __builtin_frame_address walk faults on frames without a set-up frame pointer. This is a pre-existing crash the new symbolization/profiler load exposes.
  • system.stack_trace on macOS: wrap its signal-handler async unwind in the same fault recovery as the query profiler, so a SIGBUS/SIGSEGV while unwinding a thread parked in frame-pointer-less libsystem code drops the trace instead of crashing the server. The profiler and system.stack_trace share one thread-local recovery buffer on macOS, so each handler masks the others' async-unwind signals (SIGUSR1/SIGUSR2/SIGVTALRM) to prevent a nested signal from clobbering it.
  • Removes the whole query-profiler/trace_log section from ci/defs/darwin.skip; 03150 is split into a portable build_id/symbols test and a no-darwin source-lines test.

FreeBSD/SunOS behavior is unchanged (they keep the Linux-only or "not supported" paths).

Verified on Apple arm64: 01473, 01569, 02494, 02818, 03761, 03221, 03150_trace_log_add_build_id all pass 20/20 runs.

Changelog category (leave one):

  • Improvement

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

Support the query profiler, memory/trace profilers, and trace_log symbolization on macOS.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e042ed7]

Summary: ✅


AI Review

Summary

This PR enables the query profiler, memory and trace profilers, system.stack_trace, and system.trace_log symbolization on macOS by replacing Linux-only timer and unwind pieces with Mach and pthread implementations and by hardening the Darwin async-unwind paths. The overall direction looks sound, but one CPU-profiler behavior still diverges from the Linux sampling contract, and one earlier dismissed regression test gap still leaves the build_id claim under-proven.

Findings

⚠️ Majors

  • [src/Common/QueryProfiler.cpp:378] The initial std::max(..., MIN_CPU_POLL_NS) clamp makes query-level CPU profiling miss every query shorter than 200us on macOS when the minimum query_profiler_cpu_time_period_ns (1ms) is used. Linux's CLOCK_THREAD_CPUTIME_ID timer still samples such queries with probability duration / period, so this no longer preserves the short-query sampling behavior that the code comment and PR description claim. Suggested fix: keep the floor out of the initial randomized CPU deadline and apply it only to later re-polls after the first CPU threshold is established.
  • [dismissed by author -- https://github.com/Support the query/memory profiler and trace_log symbolization on macOS #109825#discussion_r3578111087] [tests/queries/0_stateless/03150_trace_log_add_build_id.sql:12] still uses build_id IS NOT NULL, but build_id is a non-null string alias, so the assertion passes even when symbolization returns ''. The portable build_id contract this PR adds is therefore still not actually exercised by the regression test.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Jul 8, 2026
@azat azat self-assigned this Jul 8, 2026
Comment thread src/Common/QueryProfiler.cpp Resolved
Comment thread src/Common/QueryProfiler.cpp Resolved
Comment thread src/Common/QueryProfiler.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-build Pull request with build/testing/packaging improvement labels Jul 9, 2026
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Jul 9, 2026
Comment thread src/Interpreters/TraceLog.cpp Resolved
Comment thread src/Common/QueryProfiler.cpp Resolved
Comment thread src/Common/QueryProfiler.cpp Resolved
@Algunenano
Algunenano requested a review from azat July 14, 2026 13:01
@Algunenano

Copy link
Copy Markdown
Member Author

@azat Sorry for all the noise. It's ready for review now

Comment thread base/base/phdr_cache.h
Comment on lines +24 to +25
* - macOS: always true, unwinding uses frame-pointer `backtrace` which never calls
* `dl_iterate_phdr`, so no cache is needed.

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.

Interesting, good to know

Comment thread src/Common/SignalHandlers.cpp Outdated
{
if (asynchronous_stack_unwinding && sig == SIGSEGV)
/// A fault while asynchronously unwinding another thread's stack (the query profiler) must be
/// recovered by dropping the sample, not crash the server. On Linux a bad unwind faults with

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.

What means "by dropping the sample"?

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.

When unwinding the stack on the query profile, if we hit a SIGSEGV (or a SIGBUS in macOS) we've hit a misaligned address. In that case we siglongjmp back to asynchronous_stack_unwinding_signal_jump_buffer where we discard the capture and increase ProfileEvents::QueryProfilerErrors. I'll improve the wording

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.

Yes, the question was only related to wording, it can be hard to understand for others.

Comment thread src/Common/ThreadProfileEvents.h Outdated
#if defined(OS_SUNOS)
#if defined(OS_DARWIN)
/// macOS has no RUSAGE_THREAD; read per-thread user/system CPU time from the Mach kernel.
/// pthread_mach_thread_np does not add a port reference, so nothing needs to be deallocated.

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.

Can you clarify this please (in the code in comments)

Comment thread src/Common/QueryProfiler.cpp Outdated

/// (Re)arm a registration, mirroring the randomized initial `it_value` of the Linux POSIX timers
/// so a query shorter than the period can still be sampled.
void arm(Registration & reg, UInt64 period_ns)

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.

Looks too short, maybe "registerThread" would be better?

Comment thread src/Common/QueryProfiler.cpp Outdated
{
/// Fire once the thread has consumed `cpu_budget_ns` more CPU time (see arm()).
UInt64 cpu = threadCPUNs(reg.mach_thread);
UInt64 consumed = cpu - reg.last_cpu_ns;

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.

In case threadCPUNs() returns 0 (on error) we may have overflow 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.

Nice catch

Comment thread src/Common/QueryProfiler.cpp Outdated
Comment on lines +449 to +450
for (const auto & [key, reg] : registrations)
sleep_ns = std::min(sleep_ns, reg.next_deadline_ns > now ? reg.next_deadline_ns - now : UInt64(0));

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.

We can avoid second loop and calculate max deadline in the first one

std::condition_variable cond;
/// Keyed by (thread, signal): one thread can run both a Real (SIGUSR1) and a CPU (SIGUSR2)
/// profiler at once, so the signal must be part of the key or one would overwrite the other.
std::map<std::pair<uintptr_t, int>, Registration> registrations;

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.

Maybe we need a second index, i.e. std::set<std::tuple<UInt64 /*next_deadline_ns*/, uintptr_t /*thread*/, int /*signal*/>> to avoid extra scans? Though then we will need to update it on re-fire, maybe does not worth 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.

Hard to say. I would expect this to be used on small dev machines only (it's Darwin at the end of the day) with not a lot of registrations, and the expensive part isn't iterating over them, it's the actual syscalls/traps (thread_info and pthread_kill), so I'd expect that any work here is noise in comparison.

Another option would be to keep the registrations sorted and reinsert the triggered ones. Maybe worth it if the number of idle threads is much larger than the firing ones. But even then, all this work will probably cost way less than the syscalls.

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.

Indeed, but most of the time we do not need syscalls. But I agree that it does not worth it, the simpler it is the better.

Comment thread src/Common/ThreadProfileEvents.h Resolved
Comment thread src/Common/QueryProfiler.cpp Resolved
Comment thread src/Common/QueryProfiler.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.30% 78.20% -0.10%

Changed lines: Changed C/C++ lines covered: 83/97 (85.57%) · Uncovered code

Full report · Diff report

@Algunenano
Algunenano added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit d5207d2 Jul 21, 2026
519 of 524 checks passed
@Algunenano
Algunenano deleted the macos-async-signal-safe-unwind branch July 21, 2026 18:35
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…al-safe-unwind

Support the query/memory profiler and trace_log symbolization on macOS
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 submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants