Skip to content

fix(profiling): sticky foreign SIGSEGV takeover across stop/restart - #21232

Draft
vlad-scherbich wants to merge 13 commits into
mainfrom
vlad/fastcopy-3-sticky-foreign-takeover
Draft

vlad-scherbich wants to merge 13 commits into
mainfrom
vlad/fastcopy-3-sticky-foreign-takeover

Conversation

@vlad-scherbich

@vlad-scherbich vlad-scherbich commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR improves the current signal handler takeover process:

  • after a foreign SIGSEGV/SIGBUS owner appears, fast_copy_foreign_takeover sticks
  • across stop → set_fast_copy(True) → restart
  • so we never reclaim over that owner.

It also coordinates faulthandler/crashtracker pauses with handler ops under one forksafe handler_swap_lock (pause is not nested).

Testing

Unit coverage for

  • sticky takeover + metadata
  • crashtracker↔stack pause/swap/resume ordering and the shared lock,
  • faulthandler path updates.
  • Crashtracker failure-reinstall stub aligned with is_available so start does not treat a dead extension as a pause timeout.

Risks

  • Once sticky takeover latches, this process does not reclaim SIGSEGV/SIGBUS for the rest of its life. This is intentional, since we prefer syscall copy (or stop sampling) over a handler cycle.
  • The shared lock is required because a nested resume would clear the other component's pause mid-uninstall.

Pre-review checklist

  • The changes have been tested in real services in staging
  • The PR does not result in new crashes

@vlad-scherbich vlad-scherbich added the changelog/no-changelog A changelog entry is not required for this PR. label Oct 23, 2026
@vlad-scherbich
vlad-scherbich requested a balanced review from Copilot October 23, 2026 18:18
@vlad-scherbich vlad-scherbich added the Profiling Continous Profling label Oct 23, 2026
@vlad-scherbich vlad-scherbich removed the changelog/no-changelog A changelog entry is not required for this PR. label Oct 23, 2026

Copilot AI left a comment

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.

🟡 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

Comment thread ddtrace/internal/core/crashtracking.py Resolved
@vlad-scherbich
vlad-scherbich force-pushed the vlad/fastcopy-2-warmup-fork branch from a7dea40 to eec5049 Compare October 23, 2026 18:45
@vlad-scherbich
vlad-scherbich force-pushed the vlad/fastcopy-3-sticky-foreign-takeover branch from 9186291 to 2f3e02f Compare October 23, 2026 18:45
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/internal/core/crashtracking.py                                  @DataDog/profiling-python @DataDog/apm-core-python
ddtrace/internal/datadog/profiling/dd_wrapper/include/profiler_stats.hpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/dd_wrapper/src/profiler_stats.cpp    @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/_handler_swap_lock.py          @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/vm.h             @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/sampler.hpp            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc           @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/sampler.cpp                @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack.cpp                  @DataDog/profiling-python
ddtrace/profiling/_faulthandler.py                                      @DataDog/profiling-python
mypy.ini                                                                @DataDog/python-guild @DataDog/apm-core-python
releasenotes/notes/profiling-fast-copy-sticky-foreign-takeover-7a2c9e1f4b8d6035.yaml  @DataDog/apm-python
tests/crashtracker/test_crashtracker.py                                 @DataDog/profiling-python
tests/crashtracker/test_crashtracking_handler_swap.py                   @DataDog/profiling-python
tests/profiling/collector/test_copy_memory_stats.py                     @DataDog/profiling-python
tests/profiling/test_faulthandler.py                                    @DataDog/profiling-python
tests/profiling/test_main.py                                            @DataDog/profiling-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 69 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 69 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=120)
ddtrace.llmobs._integrations.google_adk -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.langchain -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.mcp -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._telemetry -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@pr-commenter

pr-commenter Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-16 21:03:50

Comparing candidate commit cbf87b7 in PR branch vlad/fastcopy-3-sticky-foreign-takeover with baseline commit f6fa194 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 628 metrics, 10 unstable metrics, 1 flaky benchmarks without significant changes.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-634.078ns; +796.804ns] or [-5.946%; +7.472%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-40.826ns; +29.274ns] or [-6.246%; +4.479%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1734.384ns; +1971.755ns] or [-8.664%; +9.850%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1838.161ns; +1649.645ns] or [-9.607%; +8.621%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-358.484ns; +366.168ns] or [-8.375%; +8.554%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-202.089ns; +236.480ns] or [-7.519%; +8.798%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-77.149ns; +93.248ns] or [-5.696%; +6.885%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4791.175ns; +4133.248ns] or [-9.866%; +8.511%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-1012.046ns; +813.138ns] or [-9.829%; +7.897%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-50.914µs; +60.233µs] or [-8.709%; +10.302%]

Known flaky benchmarks

These benchmarks are marked as flaky and will not trigger a failure. Modify FLAKY_BENCHMARKS_REGEX to control which benchmarks are marked as flaky.

Known flaky benchmarks without significant changes:

  • scenario:packagespackageforrootmodulemapping-cache_off

@vlad-scherbich
vlad-scherbich force-pushed the vlad/fastcopy-3-sticky-foreign-takeover branch from 2f3e02f to dd8fe47 Compare October 24, 2026 18:45
@vlad-scherbich
vlad-scherbich force-pushed the vlad/fastcopy-2-warmup-fork branch from 916a0bb to ac8f88c Compare October 26, 2026 00:49
@vlad-scherbich
vlad-scherbich force-pushed the vlad/fastcopy-3-sticky-foreign-takeover branch from dd8fe47 to 0a920dd Compare October 26, 2026 00:49
@vlad-scherbich
vlad-scherbich requested review from a team and gyuheon0h and a balanced review from Copilot October 26, 2026 00:50
@vlad-scherbich
vlad-scherbich requested a balanced review from Copilot and removed request for Copilot October 26, 2026 00:51

Copilot AI left a comment

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.

🟡 Changes recommended

The shared lock is not reset after fork and can permanently block handler operations in child processes.

1 open issue
3 resolved since last review

Review effort: Balanced

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: cbf87b7 | Docs | View more details | Give us feedback!

@vlad-scherbich
vlad-scherbich removed the request for review from Copilot October 26, 2026 01:05
@vlad-scherbich
vlad-scherbich requested a review from a team November 14, 2026 18:31
@vlad-scherbich
vlad-scherbich requested a review from a team as a code owner November 14, 2026 18:31
@vlad-scherbich
vlad-scherbich requested review from juanjux and removed request for a team November 14, 2026 18:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T20:44:40.891455Z cbf87b7 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 Bot left a comment

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.

Bits Code Review: FAIL

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.

Open Bits AI session

🤖 Bits Code Review · Commit 541bb36

Copilot AI left a comment

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.

🟡 Changes recommended

A handler-swap race can create a cyclic fault-handler chain, and an interrupt during the native pause can leave sampling paused if the application catches it.

2 open issues

Review effort: Balanced

Comment thread ddtrace/internal/core/crashtracking.py Resolved
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.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread tests/profiling/test_faulthandler.py Resolved

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 Bot left a comment

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.

Bits Code Review: FAIL

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.

Open Bits AI session

🤖 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.
@github-actions

Copy link
Copy Markdown
Contributor

This change is marked for backport to 4.17 and it does not conflict with that branch.
The command used to test backporting was

git fetch origin 4.17 && git checkout origin/4.17 && git checkout -b backport-21232-to-4.17 && git cherry-pick -x --mainline 1 f7df1ecd32acfc44faf2646a6d6cf1763a1c139d

@github-actions

Copy link
Copy Markdown
Contributor

This change is marked for backport to 4.15, but it conflicts with that branch.
Attempting to cherrypick this change to 4.15 yielded the following error:

Auto-merging ddtrace/internal/core/crashtracking.py
CONFLICT (content): Merge conflict in ddtrace/internal/core/crashtracking.py
Auto-merging ddtrace/internal/datadog/profiling/dd_wrapper/include/profiler_stats.hpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/dd_wrapper/include/profiler_stats.hpp
Auto-merging ddtrace/internal/datadog/profiling/dd_wrapper/src/profiler_stats.cpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/dd_wrapper/src/profiler_stats.cpp
Auto-merging ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h
Auto-merging ddtrace/internal/datadog/profiling/stack/echion/echion/vm.h
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/echion/echion/vm.h
Auto-merging ddtrace/internal/datadog/profiling/stack/include/sampler.hpp
Auto-merging ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc
Auto-merging ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
Auto-merging ddtrace/internal/datadog/profiling/stack/src/stack.cpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/src/stack.cpp
Auto-merging ddtrace/profiling/_faulthandler.py
CONFLICT (content): Merge conflict in ddtrace/profiling/_faulthandler.py
Auto-merging mypy.ini
CONFLICT (content): Merge conflict in mypy.ini
Auto-merging tests/crashtracker/test_crashtracker.py
CONFLICT (content): Merge conflict in tests/crashtracker/test_crashtracker.py
Auto-merging tests/profiling/collector/test_copy_memory_stats.py
CONFLICT (content): Merge conflict in tests/profiling/collector/test_copy_memory_stats.py
Auto-merging tests/profiling/test_faulthandler.py
Auto-merging tests/profiling/test_main.py
error: could not apply f7df1ecd32... Merge cbf87b70bea0d265df844851fccedc8545620937 into 5ff25e9719357a7ad729c51e1ea557dc505143e8

The command used to test backporting was

git fetch origin 4.15 && git checkout origin/4.15 && git checkout -b backport-21232-to-4.15 && git cherry-pick -x --mainline 1 f7df1ecd32acfc44faf2646a6d6cf1763a1c139d

@github-actions

Copy link
Copy Markdown
Contributor

This change is marked for backport to 4.16, but it conflicts with that branch.
Attempting to cherrypick this change to 4.16 yielded the following error:

Auto-merging ddtrace/internal/core/crashtracking.py
CONFLICT (content): Merge conflict in ddtrace/internal/core/crashtracking.py
Auto-merging ddtrace/internal/datadog/profiling/dd_wrapper/include/profiler_stats.hpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/dd_wrapper/include/profiler_stats.hpp
Auto-merging ddtrace/internal/datadog/profiling/dd_wrapper/src/profiler_stats.cpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/dd_wrapper/src/profiler_stats.cpp
Auto-merging ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h
Auto-merging ddtrace/internal/datadog/profiling/stack/echion/echion/vm.h
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/echion/echion/vm.h
Auto-merging ddtrace/internal/datadog/profiling/stack/include/sampler.hpp
Auto-merging ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc
Auto-merging ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
Auto-merging ddtrace/internal/datadog/profiling/stack/src/stack.cpp
CONFLICT (content): Merge conflict in ddtrace/internal/datadog/profiling/stack/src/stack.cpp
Auto-merging ddtrace/profiling/_faulthandler.py
CONFLICT (content): Merge conflict in ddtrace/profiling/_faulthandler.py
Auto-merging mypy.ini
Auto-merging tests/crashtracker/test_crashtracker.py
CONFLICT (content): Merge conflict in tests/crashtracker/test_crashtracker.py
Auto-merging tests/profiling/collector/test_copy_memory_stats.py
CONFLICT (content): Merge conflict in tests/profiling/collector/test_copy_memory_stats.py
Auto-merging tests/profiling/test_faulthandler.py
Auto-merging tests/profiling/test_main.py
error: could not apply f7df1ecd32... Merge cbf87b70bea0d265df844851fccedc8545620937 into 5ff25e9719357a7ad729c51e1ea557dc505143e8

The command used to test backporting was

git fetch origin 4.16 && git checkout origin/4.16 && git checkout -b backport-21232-to-4.16 && git cherry-pick -x --mainline 1 f7df1ecd32acfc44faf2646a6d6cf1763a1c139d

Copilot AI left a comment

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.

🔵 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

vlad-scherbich added a commit that referenced this pull request Nov 16, 2026
…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)
vlad-scherbich added a commit that referenced this pull request Nov 16, 2026
…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 taegyunkim left a comment

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.

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.

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.

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,

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.

safe_copyis the function pointer to the copy method either

  • safe_memcpy_wrapper
  • process_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;

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.

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;

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.

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;

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.

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)

Comment on lines +72 to +73
// Sticky foreign-takeover: sampling thread writes; uninstall/reinstall reads.
inline std::atomic<bool> fast_copy_foreign_takeover{ false };

ghost Nov 17, 2026

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.

Suggested change
// 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()

ghost Nov 17, 2026

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.

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;

ghost Nov 17, 2026

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.

After this PR nothing reads this excepts the profiler_stats.cpp, this is only a metric.

@vlad-scherbich

ghost commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants