Repository navigation
Support the query/memory profiler and trace_log symbolization on macOS - #109825
Conversation
… (backtrace-based unwinding)
…m/OSCPUVirtualTime)
…lated on macOS now)
|
Workflow [PR], commit [e042ed7] Summary: ✅
AI ReviewSummaryThis PR enables the query profiler, memory and trace profilers, Findings
Final Verdict
|
…l at nearest deadline
…stead of libunwind
…-safe-unwind # Conflicts: # src/Common/setThreadName.h
…tration CPU poll cadence
…instead of the crashing default
…to macos-async-signal-safe-unwind
|
@azat Sorry for all the noise. It's ready for review now |
| * - macOS: always true, unwinding uses frame-pointer `backtrace` which never calls | ||
| * `dl_iterate_phdr`, so no cache is needed. |
| { | ||
| 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 |
There was a problem hiding this comment.
What means "by dropping the sample"?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Yes, the question was only related to wording, it can be hard to understand for others.
| #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. |
There was a problem hiding this comment.
Can you clarify this please (in the code in comments)
|
|
||
| /// (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) |
There was a problem hiding this comment.
Looks too short, maybe "registerThread" would be better?
| { | ||
| /// 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; |
There was a problem hiding this comment.
In case threadCPUNs() returns 0 (on error) we may have overflow here.
| for (const auto & [key, reg] : registrations) | ||
| sleep_ns = std::min(sleep_ns, reg.next_deadline_ns > now ? reg.next_deadline_ns - now : UInt64(0)); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 83/97 (85.57%) · Uncovered code |
d5207d2
…al-safe-unwind Support the query/memory profiler and trace_log symbolization on macOS
Enable the sampling query profiler, the memory/trace profilers, and
system.trace_logsymbolization 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-freedl_iterate_phdrcache is installed"; macOS returns true because it unwinds via frame-pointerbacktrace(nodl_iterate_phdr, no loader lock). This starts theTraceCollectoron macOS, which the synchronous memory/ProfileEventtrace sources need.timer_create/SIGEV_THREAD_ID, so a single background sampler thread delivers the pause signal to each profiled thread viapthread_kill(the centralized equivalent of the per-thread Linux POSIX timer). Real (wall-clock) and CPU (via Machthread_info) are both supported. The signal handler andStackTracecapture are unchanged. The first fire is randomized like the Linux timers' initialit_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/periodchance of sampling a query shorter than the period. The poll cadence is per-registration, so a short period on one thread does not forcethread_infoon coarse (e.g. the default 10s global) profilers.system.stack_tracesignal on macOS: moved fromSIGUSR1toSIGVTALRM. macOS has no real-time signals, sostack_tracehad fallen back toSIGUSR1, which now collides with the query profiler; the profiler keepsSIGUSR1/SIGUSR2on all platforms.system.trace_logsymbolization on macOS: wireTraceLogto the existing Mach-O/dSYM paths inSymbolIndex/Dwarf, sosymbolsandbuild_idare populated from the binary's symbol table. Source-linelinesresolution needs DWARF, which on Mach-O lives in a separate.dSYMbundle the standard build does not produce (unlike ELF, which embeds DWARF in the binary), so it is populated only when a dSYM is present.RUsageCountersreads Machthread_infoinstead of the unavailablegetrusage(RUSAGE_THREAD), populatingUserTimeMicroseconds/SystemTimeMicrosecondsandOSCPUVirtualTimeMicroseconds(the Mach user+system time is not the exact same quantity as Linux taskstats' scheduler on-CPU time, but is the closest available equivalent).prof_backtracehook (experimental.hooks.prof_backtrace) that uses the systembacktrace()- 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_addresswalk faults on frames without a set-up frame pointer. This is a pre-existing crash the new symbolization/profiler load exposes.system.stack_traceon 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 andsystem.stack_traceshare 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.ci/defs/darwin.skip;03150is split into a portable build_id/symbols test and ano-darwinsource-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_idall pass 20/20 runs.Changelog category (leave one):
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.