Skip to content

fix(profiling): preserve fault siginfo when ceding SIGSEGV/SIGBUS to the host (PROF-15342) - #19969

Closed
vlad-scherbich wants to merge 8 commits into
mainfrom
vlad/prof-segv-chainback-siginfo
Closed

vlad-scherbich wants to merge 8 commits into
mainfrom
vlad/prof-segv-chainback-siginfo

Conversation

@vlad-scherbich

@vlad-scherbich vlad-scherbich commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Description

The unarmed chain-back path in danger.cc restored the previously-installed SIGSEGV/SIGBUS handler, then called pthread_kill(pthread_self(), signo). That re-raise delivers si_code == SI_TKILL with no fault address and a PC inside our own handler, so a host that reads siginfo to classify the fault gets garbage.

The handler now cedes the signal and returns for kernel-generated faults (si_code > 0), so the faulting instruction re-executes and the new owner receives the real si_code, si_addr and PC. Injected signals (si_code <= 0) still get an explicit re-delivery, since no instruction would re-execute. A saved SIG_IGN becomes SIG_DFL, so returning into an ignored fault terminates instead of spinning.

Motivation is IR-59892: datadog-agent 7.83.0 release candidates crash-looped. The Agent embeds CPython; the profiler installed over the Go runtime's handlers, and this bug turned Go's recoverable nil-dereference panics fatal. The crash log showed sigcode=18446744073709551610 — -6 as unsigned 64-bit, i.e. SI_TKILL.

Continues #18798 (4.12 backport #18993). #19920 mitigates the Agent by disabling fast copy for embedded interpreters; this fixes the defect itself, which corrupts siginfo for any host that reads it — Go, the JVM, .NET, Python's own faulthandler.

Testing

New test_fault_chainback.cpp covers the ceded unarmed fault and the unchanged armed recovery. On this branch:

[ RUN      ] FaultChainback.CedesUnarmedFaultWithOriginalSiginfo
[       OK ] FaultChainback.CedesUnarmedFaultWithOriginalSiginfo (0 ms)

With main's danger.cc and only the new test applied:

[ RUN      ] FaultChainback.CedesUnarmedFaultWithOriginalSiginfo
test_fault_chainback.cpp:148: Failure
Expected equality of these values:
  report.si_addr
    Which is: NULL
  outcome.page
    Which is: 0x102ba8000
si_addr did not survive the handoff to the host
[  FAILED  ] FaultChainback.CedesUnarmedFaultWithOriginalSiginfo (0 ms)

Full native stack suite on macOS arm64: 21/22; ThreadAltStackOwnership.DestructorDisablesOwnAltStack fails identically with main's danger.cc restored (pre-existing macOS breakage).

Not run locally: the Linux path, and tests/profiling/test_faulthandler.py / tests/profiling/collector/test_copy_memory_stats.py, which need a full package build.

Risks

Confined to the unarmed path, which previously always handed off or terminated. Returning without re-raising relies on the faulting instruction re-executing, which holds only for si_code > 0; injected signals keep the old re-delivery.

Additional Notes

Out of scope: a probe that refuses to install over an existing handler. pytest enables faulthandler by default, so it would silently disable fast copy in every test run and for anyone calling faulthandler.enable(); telling it and crashtracker — chained intentionally — apart from torch/CUDA/abseil needs something like dladdr on the handler address.

Backports likely wanted; targets undecided, so no backport labels applied.

https://datadoghq.atlassian.net/browse/PROF-16018

…the host (PROF-14568)

The stack sampler installs SIGSEGV/SIGBUS handlers so safe_memcpy can recover from a
stale read. When a fault arrives that the sampler is not recovering, the handler used to
restore the previous disposition and re-raise via pthread_kill. That re-raise reports
si_code == SI_TKILL with no fault address and a PC inside the profiler's handler, so a
host that reads siginfo to classify the fault cannot recover: the Go runtime turns such a
signal into a fatal error instead of the nil-dereference panic it would otherwise raise.
That is how an embedded ddtrace crashed the Datadog Agent's cluster check runners.

Cede the signal and return instead. For a kernel-generated fault (si_code > 0) returning
re-executes the faulting instruction, so the new owner receives a genuine signal with the
original si_code, si_addr and fault PC. Signals that were injected rather than caused by
an instruction (si_code <= 0) still need an explicit re-delivery, since no instruction
will re-execute. A saved SIG_IGN disposition becomes SIG_DFL, because returning into an
ignored synchronous fault would spin instead of terminating.

This is independent of the embedded-interpreter gate: that gate stops us taking the
handler in a known-bad case, while this makes the handoff correct for every host,
including a plain python process that loads a library owning those signals.

The new test fails on main (si_addr arrives as NULL) and passes here.
…ease note

PROF-14568 is the closed shutdown-race ticket; the handler-ownership work this
change continues is tracked by PROF-15342. Also drops the "embeds CPython"
framing from the release note, since a corrupted siginfo breaks any host that
reads it, and lowercases the scope per docs/releasenotes.rst.
@vlad-scherbich vlad-scherbich added the Profiling Continous Profling label Aug 31, 2026
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 31, 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/datadog/profiling/stack/src/echion/danger.cc           @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_fault_chainback.cpp  @DataDog/profiling-python
releasenotes/notes/profiling-stack-sampler-fault-chainback-siginfo-0b72894583e6fc6b.yaml  @DataDog/apm-python
tests/profiling/collector/test_memalloc.py                              @DataDog/profiling-python
tests/profiling/test_profiler.py                                        @DataDog/profiling-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

There are 1 circular imports that already exist on the base branch and have not been changed by this PR.

ddtrace.errortracking._handled_exceptions.bytecode_injector -> ddtrace.errortracking._handled_exceptions.callbacks -> ddtrace.errortracking._handled_exceptions.collector -> ddtrace.errortracking._handled_exceptions.bytecode_reporting -> ddtrace.errortracking._handled_exceptions.bytecode_injector

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 219 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=133)
ddtrace.internal.ci_visibility.recorder -×-> ddtrace.trace  (product:ci_visibility -> product:tracing, score=131)
ddtrace.llmobs._integrations.crewai -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=131)
ddtrace.aiguard._api_client -×-> ddtrace.trace  (product:aiguard -> product:tracing, score=131)
ddtrace.internal.opentelemetry.trace -×-> ddtrace.trace  (product:opentelemetry -> product:tracing, score=131)

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

@datadog-official

datadog-official Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

✨ Unblock PR with BitsAI

⚠️ Warnings

❌ Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 2 Pipeline jobs failed

DataDog/apm-reliability/dd-trace-py | profiling_native: [3.12, valgrind] — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

DataDog/apm-reliability/dd-trace-py | profiling_native: [3.14, valgrind] — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

Useful? React with 👍 / 👎

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

@vlad-scherbich

Copy link
Copy Markdown
Contributor Author

@codex review

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.

Pull request overview

This PR fixes the native stack sampler’s SIGSEGV/SIGBUS “chain-back” behavior so that when the profiler cedes a fault it doesn’t corrupt siginfo (e.g., si_code, si_addr, and faulting PC) for the host runtime’s handler, addressing crash-loop scenarios in embedded/hosted environments.

Changes:

  • Adjustes danger.cc unarmed handler chain-back to restore the previous handler and return for kernel-generated faults, preserving original siginfo.
  • Adds a new native unit test (test_fault_chainback.cpp) validating that ceded unarmed faults reach the host with intact siginfo, and that armed recovery remains unchanged.
  • Wires the new test into the CMake native test suite and adds a release note entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.

File Description
releasenotes/notes/profiling-stack-sampler-fault-chainback-siginfo-0b72894583e6fc6b.yaml Release note describing the siginfo preservation fix.
ddtrace/internal/datadog/profiling/stack/test/test_fault_chainback.cpp New unit tests for unarmed fault cede behavior and unchanged armed recovery behavior.
ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt Adds the new test_fault_chainback target and includes/defines needed for platform-gated headers.
ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc Implements the revised chain-back logic to preserve original kernel fault siginfo.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines 95 to +99
if (t_in_unarmed_chain) {
// We are being re-entered while already chaining to a previous
// handler: the handler chain has cycled back to us. Restore the
// default disposition and re-raise to guarantee the process
// terminates instead of looping forever.
struct sigaction dfl
{};
dfl.sa_handler = SIG_DFL;
sigemptyset(&dfl.sa_mask);
dfl.sa_flags = 0;
sigaction(signo, &dfl, nullptr);
pthread_kill(pthread_self(), signo);
// We already ceded this signal on this thread, so something reinstalled us
// and the fault is not making progress. Force the default disposition to
// guarantee the process terminates instead of looping forever.
install_default_disposition(signo);

@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: c80624fb14

ℹ️ 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 on lines +99 to 100
install_default_disposition(signo);
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Re-deliver asynchronous signals after selecting SIG_DFL

When an asynchronously generated SIGSEGV/SIGBUS re-enters through a cyclic handler chain, returning here consumes that signal because there is no faulting instruction to execute again. The previous implementation called pthread_kill after installing SIG_DFL, guaranteeing termination; this change instead lets the process continue with the default disposition merely installed. Re-deliver the signal in this branch when info is null or has a nonpositive si_code.

Useful? React with 👍 / 👎.

Handle async and re-entry fault paths correctly: re-deliver injected
signals after installing SIG_DFL, preserve SIG_IGN for async deliveries,
and classify Linux async positive si_codes separately. Also fix release
note grammar, use runtime page size in the test, and use sig_atomic_t
for handler-to-thread fields.
Rename the test report field away from si_addr, which collides with the
siginfo_t macro, and silence the unused signo warning on non-Linux builds.
Profiler() must sample PYMEM_DOMAIN_MEM with no env/kwarg, and the
obj-only label test must not inherit a parent true.
Clarify the ownership comment after cede and add native tests for
pthread_kill re-delivery (si_code <= 0) and preserving SIG_IGN on
injected signals.
@vlad-scherbich

Copy link
Copy Markdown
Contributor Author

Superseded by #20518

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

Labels

Profiling Continous Profling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants