Repository navigation
fix(profiling): sticky foreign SIGSEGV takeover across stop/restart - #21232
vlad-scherbich wants to merge 13 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Overlapping handler swaps and fork inheritance can still leave fast-copy sampling without recovery handlers.
3 open issues
What changed in this PR
This PR makes foreign signal-handler takeover persistent across profiler stop/restart cycles, preventing fast-copy recovery handlers from reclaiming ownership. It also adds takeover metadata and coordinates handler swaps with sampling pauses.
Changes:
- Preserve foreign-takeover state and export it in profiling metadata.
- Update handler release/reinstallation and faulthandler/crashtracker coordination.
- Add regression tests for takeover, restart, disable/re-enable, and handler-swap failures.
| File | Description |
|---|---|
| tests/profiling/test_main.py | Clarifies an existing regression-test comment. |
| tests/profiling/test_faulthandler.py | Tests refusal to enable after a pause timeout. |
| tests/profiling/collector/test_copy_memory_stats.py | Adds takeover, metadata, and restart regressions. |
| tests/crashtracker/test_crashtracking_handler_swap.py | Tests reinstall-before-resume ordering. |
| ddtrace/profiling/_faulthandler.py | Skips enable and handler changes after pause timeout. |
| ddtrace/internal/datadog/profiling/stack/src/stack.cpp | Applies sticky takeover to fast-copy and handler operations. |
| ddtrace/internal/datadog/profiling/stack/src/sampler.cpp | Records takeover and publishes its metadata. |
| ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc | Tracks handler release and absent dispositions. |
| ddtrace/internal/datadog/profiling/stack/include/sampler.hpp | Declares the takeover-marking helper. |
| ddtrace/internal/datadog/profiling/stack/echion/echion/vm.h | Adds sticky state and gates handler operations. |
| ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h | Declares handler-state queries. |
| ddtrace/internal/datadog/profiling/dd_wrapper/src/profiler_stats.cpp | Preserves and serializes takeover metadata. |
| ddtrace/internal/datadog/profiling/dd_wrapper/include/profiler_stats.hpp | Defines the takeover metadata field and accessors. |
| ddtrace/internal/core/crashtracking.py | Pauses sampling around swaps and restores handlers in cleanup. |
Review effort: Balanced
a7dea40 to
eec5049
Compare
9186291 to
2f3e02f
Compare
Codeowners resolved asResolved from the full PR diff against |
Dependency direction analysis
|
BenchmarksBenchmark execution time: 2026-11-16 21:03:50 Comparing candidate commit cbf87b7 in PR branch Found 0 performance improvements and 0 performance regressions! Performance is the same for 628 metrics, 10 unstable metrics, 1 flaky benchmarks without significant changes.
|
2f3e02f to
dd8fe47
Compare
916a0bb to
ac8f88c
Compare
dd8fe47 to
0a920dd
Compare
🎉 All green!🧪 All tests passed 🔗 Commit SHA: cbf87b7 | Docs | View more details | Give us feedback! |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
A fork during foreign-handler takeover can leave the child using memcpy while the sticky flag suppresses recovery-handler checks, creating a process-crash path.
🤖 Bits Code Review · Commit 541bb36
Cancel a stack sampling pause when KeyboardInterrupt lands during crashtracking/faulthandler handler swaps, and take handler_swap_lock inside native set_fast_copy so reclaim after stop cannot install between another swap uninstall and enable.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1144033a80
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
There was a problem hiding this comment.
The PR makes foreign-handler takeover sticky, serializes handler changes, and now cleans up interrupted pauses. Two issues remain: the existing P1 fork race can crash children using unprotected memcpy, and new P2 lock cleanup masks intended exceptions with SystemError; the fork fix remains outside this PR in #21233.
🤖 Bits Code Review · Commit 1144033
Save/restore the pending exception around handler_swap_lock release so RuntimeError/TypeError are not cleared into SystemError, and align the pause-timeout faulthandler test with resume-on-None cancellation.
|
This change is marked for backport to 4.17 and it does not conflict with that branch. |
|
This change is marked for backport to 4.15, but it conflicts with that branch. The command used to test backporting was |
|
This change is marked for backport to 4.16, but it conflicts with that branch. The command used to test backporting was |
There was a problem hiding this comment.
🔵 Needs a closer look
Native signal chaining and pause/swap locking require Linux/macOS runtime validation under concurrent swaps, restart, and fork, which was unavailable in this source-only review.
No open issues 🎉
2 resolved since last review
Review effort: Balanced
…up (#21230) Warmup clears `fast_copy_active` while our SIGSEGV handler is still installed. Handler install/uninstall/reclaim keyed off that flag, so `faulthandler.enable()` in the window took the handler unnoticed and the warmup deadline pinned the process to the syscall copy for life. This PR adds persistent `fast_copy_desired` (untouched by warmup), uses `fast_copy_handler_ops_enabled()` for those handler ops, and publishes `fast_copy_memory_desired` in internal metadata. It also pins the mid-warmup fork path: a child re-runs the warmup decision instead of inheriting `fast_copy_active == false` for life (gunicorn/celery prefork). * new unit tests (faulthandler during warmup; fork during warmup) None. Stack: **1/3** (includes mid-warmup fork pin). Next: sticky foreign takeover (#21232). https://datadoghq.atlassian.net/browse/PROF-15995 - [ ] The changes have been tested in real services in staging - [ ] The PR does not result in new crashes Co-authored-by: vlad.scherbich <vlad.scherbich@datadoghq.com> (cherry picked from commit c1198df)
…up (#21230) Warmup clears `fast_copy_active` while our SIGSEGV handler is still installed. Handler install/uninstall/reclaim keyed off that flag, so `faulthandler.enable()` in the window took the handler unnoticed and the warmup deadline pinned the process to the syscall copy for life. This PR adds persistent `fast_copy_desired` (untouched by warmup), uses `fast_copy_handler_ops_enabled()` for those handler ops, and publishes `fast_copy_memory_desired` in internal metadata. It also pins the mid-warmup fork path: a child re-runs the warmup decision instead of inheriting `fast_copy_active == false` for life (gunicorn/celery prefork). * new unit tests (faulthandler during warmup; fork during warmup) None. Stack: **1/3** (includes mid-warmup fork pin). Next: sticky foreign takeover (#21232). https://datadoghq.atlassian.net/browse/PROF-15995 - [ ] The changes have been tested in real services in staging - [ ] The PR does not result in new crashes Co-authored-by: vlad.scherbich <vlad.scherbich@datadoghq.com> (cherry picked from commit c1198df)
taegyunkim
left a comment
There was a problem hiding this comment.
Reviewing PRs that touch vm.h is quite difficult for me, and I'd like to suggest few edits to the variable/metadata key names to make it easier to understand in general.
What do you think? The suggestions probably be better to be done in a separate PR.
There was a problem hiding this comment.
IMHO, the variable names and comments in this file are not very clear and hard to follow, and makes it harder to understand and review PRs like this, also the variables don't really match with the metadata key variables in the profiler_stats.hpp, and that also adds a little confusion as well.
Why don't we first go over the variable names, and the comments around them to make them clearer in general?
| Old variable | Old key | New name (variable and key) | Meaning |
|---|---|---|---|
safe_memcpy_initialized |
fast_copy_memory_capable |
fast_copy_init_ok |
Our handlers installed at startup. Fixed after init, and stays true after a foreign takeover. |
fast_copy_active |
fast_copy_memory_enabled |
fast_copy_in_use |
safe_copy points at safe_memcpy right now. "Enabled" is easy to read as a user setting. |
fast_copy_user_disabled |
fast_copy_memory_user_disabled |
fast_copy_turned_off |
Off because of the env var, embedded Python, or set_fast_copy(False). Not all of these are user choices. |
fast_copy_desired |
fast_copy_memory_desired |
fast_copy_wanted() |
fast_copy_init_ok && !fast_copy_turned_off. In use now, or will be after warmup. Stays true after a foreign takeover. The key could be dropped since it adds nothing. |
fast_copy_foreign_takeover |
fast_copy_memory_foreign_takeover |
fast_copy_blocked_by_foreign_handler |
Another library replaced our SIGSEGV/SIGBUS handler, so fast copy is off for the rest of the process and its forks. Never cleared. |
| (none) | (none) | fast_copy_available() |
fast_copy_wanted() && !fast_copy_blocked_by_foreign_handler. Whether fast copy may be used now. A function only; it needs no key since the other keys give it. |
fast_copy_syscall_fallback |
fast_copy_memory_syscall_fallback |
fast_copy_ever_fell_back |
Fell back to the syscall copy at least once, for any reason. Never cleared. |
fast_copy_handler_ops_enabled() |
none | may_manage_segv_handlers() |
(fast_copy_wanted() || fast_copy_in_use) && !fast_copy_blocked_by_foreign_handler. Whether we may install or remove our handlers. Same logic as the PR. |
mark_fast_copy_foreign_takeover() |
none | mark_fast_copy_blocked_by_foreign_handler() |
Matches the flag. |
| #define copy_type_p(addr, dest) (copy_memory(mach_task_self(), addr, sizeof(*dest), dest)) | ||
| #define copy_generic(addr, dest, size) (copy_memory(mach_task_self(), (void*)(addr), size, (void*)(dest))) | ||
|
|
||
| inline kern_return_t (*safe_copy)(vm_map_read_t, |
There was a problem hiding this comment.
safe_copyis the function pointer to the copy method either
safe_memcpy_wrapperprocess_vm_readv/mach_vm_read_overwrite
"safe" is used for both safe_copy and safe_memcpy_wrapper and safe_memcpy_wrapper is also called as "fast copy"
| #endif | ||
|
|
||
| // Whether safe_copy is currently set to the memcpy-based wrapper. | ||
| inline bool fast_copy_active = false; |
There was a problem hiding this comment.
This seems fine as is, but profiler_stats.hpp refer to this as fast_copy_memory_enabled
| } | ||
|
|
||
| // Set at init; survives toggling fast_copy_active. | ||
| inline bool safe_memcpy_initialized = false; |
There was a problem hiding this comment.
profiler_stats.hpp calls this as fast_copy_memory_capable
| // User opted out via _DD_PROFILING_STACK_FAST_COPY, embedded Python, or | ||
| // set_fast_copy(false). Cleared again by set_fast_copy(true). Orthogonal to | ||
| // desired: desired also requires safe_memcpy_initialized. | ||
| inline bool fast_copy_user_disabled = false; |
There was a problem hiding this comment.
This means safe_memcpy is explicitly turned off by either of the following
- turned off by env var
- embedded python
- or
set_fast_copy(false)
| // Sticky foreign-takeover: sampling thread writes; uninstall/reinstall reads. | ||
| inline std::atomic<bool> fast_copy_foreign_takeover{ false }; |
There was a problem hiding this comment.
| // Sticky foreign-takeover: sampling thread writes; uninstall/reinstall reads. | |
| inline std::atomic<bool> fast_copy_foreign_takeover{ false }; | |
| // Another library replaced our SIGSEGV/SIGBUS handler. When this is set, we shall never install ours again in this process or its forks. | |
| inline std::atomic<bool> fast_copy_foreign_takeover{ false }; |
I don't think current comment clearly delivers what this variable is for
| // set_fast_copy_enabled finishes clearing active — keep ops enabled so a | ||
| // coordinated uninstall can still drop a live recovery handler. | ||
| inline bool | ||
| fast_copy_handler_ops_enabled() |
There was a problem hiding this comment.
I think the name handler_ops is a vague, and don't think this clearly delivers what it does.
| @@ -69,21 +69,26 @@ | |||
| // Sticky: fell back to syscall copy (init failure, foreign handler, warmup miss). | |||
| inline bool fast_copy_syscall_fallback = false; | |||
There was a problem hiding this comment.
After this PR nothing reads this excepts the profiler_stats.cpp, this is only a metric.
@taegyunkim Good points, checking these now. If these renames touch old code outside of this PR, let's indeed perform them separately (as a base PR that this one is rebased onto). |


Description
This PR improves the current signal handler takeover process:
fast_copy_foreign_takeoversticksset_fast_copy(True)→ restartIt also coordinates faulthandler/crashtracker pauses with handler ops under one forksafe
handler_swap_lock(pause is not nested).Testing
Unit coverage for
is_availableso start does not treat a dead extension as a pause timeout.Risks
Pre-review checklist