Skip to content

feat(profiling): add opt-in Linux CPU timer stack profiler - #18724

Draft
taegyunkim wants to merge 95 commits into
mainfrom
taegyunkim/prof-14213-timer-create
Draft

taegyunkim wants to merge 95 commits into
mainfrom
taegyunkim/prof-14213-timer-create

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Note

Thorough manual review is still in progress.

Description

Adds an opt-in Linux CPU timer path for the stack profiler on standalone, GIL-enabled CPython 3.12+. Enable it with _DD_PROFILING_STACK_CPU_TIMER_ENABLED=true; the default interval is 10 ms and the feature remains off by default. Embedded interpreters, including uWSGI, retain wall-sampled CPU time because the host process owns the signal handlers.

Each Python thread receives a timer_create per-thread CPU timer that delivers SIGPROF through SIGEV_THREAD_ID. The signal handler validates that the signal came from this profiler, captures bounded raw frame and task identity data into a preallocated per-thread SPSC ring, and returns without allocating or locking. The sampler thread drains the rings, validates copied CPython data, and emits cpu-time samples with asyncio task or greenlet ancestry when the captured identity can be matched safely.

Wall sampling continues independently. When CPU timer mode is configured, wall samples stop reporting CPU time so the process does not mix accounting methods if the timer later disables itself.

Safety and lifecycle handling includes:

  • forwarding foreign SIGPROF signals to the previous handler
  • guarded CPython memory reads through the existing fault-recovery mechanism
  • permanent disable on incompatible signal masks, handler replacement, repeated capture failures, or unsupported platforms
  • thread discovery, thread churn, fork, shutdown, and one-shot restart handling, including keeping the alternate signal stack that the forking thread still has installed in the child
  • private diagnostics for dropped samples, timer overruns, capture failures, and disable reasons
  • on CPython 3.14+, reading the running asyncio task at the offset published in CPython's AsyncioDebug table
  • on CPython 3.14+, validating code object generations before each drain, so the drain does not resolve a reused code object address through stale cached frames

PROF-14213

Testing

Latest main merge (e0ef38abe3, origin/main at 69a914db1d):

  • Clean merge with no conflicts and no CPU timer changes needed:
  • Stack, CPU timer, and asyncio tests through scripts/run-tests after a native rebuild:
    • CPython 3.12, with faulthandler and fast-copy tests: 224 passed, 27 skipped, and 8 expected failures for both command variants.
    • CPython 3.14: 217 passed, 10 skipped, 8 expected failures, and 1 failure, the pre-existing test_cpu_timer_postfork_from_worker_keeps_inherited_altstack.
  • CPython 3.14 standalone native build: all 91 stack tests and 26 dd_wrapper tests passed, including main's new test_task_links.

Previous main merge (85ab528e1d, merged in 25bfe9e603, origin/main at ec346212b5):

  • Resolved conflicts in stack/CMakeLists.txt, sampler.cpp, and stack.cpp:
  • refactor(profiling): key native span links by execution unit #21621 keys span links by execution unit. render_cpu_sample_begin now uses get_active_span(SpanLinkKey::thread(...)), matching main's other call sites.
  • Stack, CPU timer, and asyncio tests through scripts/run-tests after a native rebuild:
    • CPython 3.12, with faulthandler and fast-copy tests: 221 passed, 27 skipped, and 8 expected failures for both command variants.
    • CPython 3.14: 213 passed, 10 skipped, 8 expected failures, and 1 failure, the pre-existing test_cpu_timer_postfork_from_worker_keeps_inherited_altstack described below.
  • fix(profiling): read Python 3.14 asyncio task offsets from the runtime #21278 reads Python 3.14 asyncio offsets from the runtime because they move between 3.14 patch releases. The CPU timer signal handler now reads asyncio_running_task at the offset from the same AsyncioDebug table instead of its compile-time offset. Until the table is found, CPU samples carry no running-task identity, matching how the task lists are skipped.
    • Native tests (86 passed on CPython 3.14): the parser rejects an out-of-bounds or misaligned running-task offset, and discovery through the real _asyncio module returns offsetof(_PyThreadStateImpl, asyncio_running_task).
    • New test_cpu_timer_reads_asyncio_running_task_offset_from_runtime_table: the offset is published from the runtime table on 3.14 and stays 0 before 3.14. CPython 3.14 CPU timer and asyncio tests: 113 passed, with only the pre-existing postfork failure. CPython 3.12 CPU timer tests: 28 passed for both command variants.
    • Not covered: running a wheel built on one 3.14 patch release on another, where the offsets actually differ.
  • scripts/lint cformat passed.

Previous main merge (23d472aa45, origin/main at c78138ab81):

  • Clean merge with no textual conflicts (140f6d4884). Three follow-up changes adapt the CPU timer to main:
    • fix(profiling): keep stack sampler state alive through uWSGI exit #21330 keeps stack sampler singletons alive through process exit, because uWSGI can exit without running the atexit hooks that stop the sampler. CpuTimer::Engine::get() now follows the same pattern, since the sampling thread drains it.
    • Main now runs the suites on Python 3.15 and relies on the unpinned protobuf profile row to cover it. This PR had split that row into explicit 3.9 to 3.11 and 3.12 to 3.14 lists, so 3.15 was added to the row that runs with and without the CPU timer.
    • fix(profiling): invalidate stale Echion frames on Python 3.14+ #19641 clears the frame identity caches on Python 3.14+ when a code object generation changes, but only inside the wall sampling cycle. The CPU timer drain runs on its own deadline and reads the same caches. The interpreter snapshot and generation check now run once per loop iteration, before both the drain and the wall sample. Wall sampling still skips the cycle when the snapshot is incomplete; the drain still runs, since the caches were cleared and skipping would let the rings fill.
  • Native build on CPython 3.14 with no warnings in the merged files.
  • Stack and CPU timer tests (-k "cpu_timer or stack") through scripts/run-tests after a native rebuild:
    • CPython 3.12: 131 passed, 9 skipped, and 6 expected failures for both command variants.
    • CPython 3.14: 131 passed, 8 skipped, 6 expected failures, and 1 failure.
    • CPython 3.15 (CPU timer tests only): 26 passed, 1 skipped, 1 expected failure, and 1 failure.
  • The failure on 3.14 and 3.15 is test_cpu_timer_postfork_from_worker_keeps_inherited_altstack: in the child, the inherited alt stack is counted as an application alt stack. It fails the same way at the pre-merge head 153b71e03f, so it is not a regression from this merge, and it still needs a fix. It passes on 3.12.
  • scripts/lint cformat, scripts/lint suitespec-check, and scripts/lint suitespec-duplicates passed.

Previous main merge (153b71e03f, origin/main at 5d92793a3b):

  • Clean merge with no conflicts. The native stack change from main is refactor(profiling): read asyncio task-list head offsets from the sampler #21187, which moves the Python 3.14 asyncio task-list head offsets into EchionSampler. The CPU timer does not walk those lists in the signal handler; it reads only asyncio_running_task, which is not one of the moved offsets, so no CPU timer change was needed.
  • CPython 3.12 profiling suite through scripts/run-tests after a native rebuild: 532 passed, 45 skipped, and 3 expected failures for both command variants, including 44 CPU timer test passes and 2 gevent skips. The two additional passes are new scheduler tests from main.

Previous main merge (198e00f81e, origin/main at c9ceaa6a7b):

  • Clean merge with no conflicts. The only native stack change from main is refactor(profiling): make the asyncio task-set pointers atomic #21215, which makes echion's asyncio task-set pointers atomic behind the existing accessors; the CPU timer reads them only through those accessors.
  • CPython 3.12 profiling suite through scripts/run-tests after a native rebuild: 530 passed, 45 skipped, and 3 expected failures for both command variants, including 44 CPU timer test passes and 2 gevent skips.

Previous main merge and fork alt-stack fix (b72870b0bd, origin/main at 1cb9f945a5):

  • Merged origin/main at 1cb9f945a5 (8af359af29). Resolved conflicts in sampler.hpp, sampler.cpp, and stack.cpp:
    • kept main's register_fork_cleanup() alongside the PyThreadState* parameter on Sampler::register_thread
    • kept main's SIGSEGV/SIGBUS handler-ownership log messages and still disable the CPU timer before falling back to the syscall copy
    • kept main's preservation of the asyncio loop and uvloop flag when a living thread is registered again
    • kept main's lone-surrogate-safe thread name encoding alongside the same-thread PyThreadState check
  • Fixed a dangling alternate signal stack after fork, reported in review. Engine::postfork_child() identified the forking thread by its parent TID, which changes across fork, so the child unmapped the alt stack that thread still had installed. The child now finds the in-use mapping from the inherited sigaltstack setting, keeps it mapped, and hands it to the thread's new capture state when it registers again. Mappings no longer in use are still released.
  • Added test_cpu_timer_postfork_from_worker_keeps_inherited_altstack, which forks from a profiled worker thread, delivers an SA_ONSTACK signal in the child, and checks that the child keeps CPU timer sampling without mistaking the inherited stack for an application one. Without the fix, the test fails because the child reuses the freed mapping as an application alt stack. A crash is not guaranteed, since the child's own allocations can land on the freed range, which later signals then overwrite. The existing fork test forks from the main thread, whose alt stack is echion's and was never unmapped, so it did not cover this.
  • CPython 3.12 profiling suite through scripts/run-tests after a native rebuild: 530 passed, 45 skipped, and 3 expected failures, including both CPU timer command variants (44 CPU timer test passes, 2 gevent skips).
  • scripts/lint cformat and scripts/lint style on the changed files passed. Both new commits are signed and verified.

Previous main merge validation (e16880aa58, origin/main at a1bcb762e9):

  • Preserved upstream SIGSEGV/SIGBUS chaining semantics alongside CPU timer fault recovery. Accepted removal of riotfile.py, retaining CPU-timer-enabled runs in tests/profiling/suitespec.yml.
  • The signed merge is pushed and GitHub reports its signature as verified.
  • CPython 3.12 RelWithDebInfo standalone build: all 51 native stack tests passed, including the new signal-chaining tests.
  • Rebuilt native extensions and ran targeted CPU timer, native syscall hazard, and profiling configuration tests through scripts/run-tests:
    • Python 3.12: default and CPU-timer-enabled runs each reported 66 passed, 1 skipped, and 1 expected failure.
    • Python 3.14: the same two runs each reported 66 passed, 1 skipped, and 1 expected failure.
    • Python 3.12 with gevent: 67 passed and 1 expected failure, including CPU timer greenlet attribution.
    • Total across five runs: 331 passed, 4 skipped, and 5 expected failures. The skips are gevent coverage in environments without gevent; the expected failures are the existing raw ppoll interruption reproducer. This was targeted validation, not a full profiling-suite run.
  • Local container blockers were resolved with an ignored UID-matched image/Compose override and isolated uv/bytecode caches. No tracked source changes were needed for the test environment.
  • scripts/lint cformat, scripts/lint profiling-native-check, scripts/lint checks, and whitespace checks relative to origin/main passed. Benchmark discovery found no matching suite for the resolved fault-handler source.

Earlier build repair and main refresh (8663153a7d):

  • Fixed Unix native builds after python_headers.hpp was removed by replacing the stale include in cpu_timer.hpp with the direct CPython include and compatibility guard.
  • Merged origin/main at 9379ddd518, preserving both CPU timer sampling and the new native frame-limit propagation.
  • Built the CPython 3.12 wheel successfully with uv build --wheel and rebuilt the CPython 3.13 _stack CMake target with warnings treated as errors.
  • Ran both CPU timer profiling variants on CPython 3.12 through scripts/run-tests: 52 passes total, 2 skips, and 2 expected failures.
  • scripts/lint cformat, full scripts/lint checks, and git diff --check passed.

Earlier main refresh (03d23af35d):

  • Release C++ builds and all native stack tests passed on CPython 3.10.12 (31 tests) and 3.14.5 (32 tests), using the existing local Rust native library.
  • Retained malformed asyncio-list rejection and source-local snapshot rollback, cross-source wall-task deduplication, GC-frame scopes, and main's sampler-start race fix.
  • Preserved CPU-timer-enabled full-suite coverage in the migrated uv matrix for Python 3.12, 3.13, and 3.14; scripts/run-tests --dry-run confirms both runs reuse the existing dependency locks.
  • scripts/lint checks and git diff --check origin/main passed.
  • Mosaic request 13657704944520646691 showed deterministic worker crashes in the CPU-timer-enabled uWSGI tests on Python 3.12 through 3.14; the matching normal profiling runs passed.
  • Reproduced the Python 3.14 uWSGI worker crash locally and under GDB. The child received SIGSEGV during Python fork callbacks after CPU timer profiling installed its signal handlers.
  • Disabled CPU timer profiling in embedded interpreters using the existing embedded-runtime safety gate for fast stack copying. A local Python 3.14 uWSGI diagnostic with CPU timers disabled emitted wall profiles for the master and both original workers without respawns.
  • Targeted local validation through scripts/run-tests was attempted, but the required native rebuild failed when the linker received SIGBUS with only 2 GB of disk space left. Mosaic request 9276649356139908723 passed, including all 23 profiling shards, all five uWSGI profiling shards, the CPU-timer-enabled Python 3.12 through 3.14 runs, the Python 3.15 base virtualenv build, and downstream system tests.
  • Staging Rapid Test Drive prof-14213-cpu-timer is ready for rapid_python_http_smoke_test from dd-source commit cb189b915f1c, using the integration wheel and _DD_PROFILING_STACK_CPU_TIMER_ENABLED=true. Deployment request 233155852796473320 passed. Runtime diagnostics confirm the 10 ms CPU timer remains active with no capture failures, overruns, or health disablement. No samples were dropped during an 18-second CPU-heavy burst; one worker reported 170 ms of earlier startup ring-buffer drops. In a stable one-minute bucket, Python CPU time was 0.828 cores versus 0.817 container cores.
  • Repeated staging validation on signal-bundler with the latest PR head 8663153a7d, integration wheel aecedeca6e, and dogweb artifact v137405555-88becf86. Conductor run 5b0930c0-cbf6-472c-9f4b-14b4f3e27c18 completed successfully. All 25 active service pods became ready with zero restarts and published Python 3.12 profiles from ddtrace 4.15.0rc2, including CPU-time stacks in normal message-processing paths. Service logs contained no CPU timer, profiler failure, fatal Python, or segmentation fault messages during rollout.
  • Follow-up CI caught Python 3.15 removing FRAME_OWNED_BY_CSTACK; the CPU timer now uses the same version guard as the existing Echion frame reader. scripts/lint cformat passed, and benchmark discovery found no matching suite for this compile-only guard.
  • scripts/lint fmt -- ddtrace/internal/settings/profiling.py, scripts/lint checks, targeted style and spelling checks, and git diff --check passed.
  • Benchmark discovery found no matching suites for the changed task-traversal source.

Coverage includes:

  • native tests for the SPSC sample ring and lazy lock-free TID table
  • integration tests for CPU sample emission, thread discovery/churn, fork/restart, signal ownership, handler replacement, and fault recovery
  • asyncio attribution and parent-task stitching across CPython 3.12, 3.13, and 3.14
  • greenlet attribution and logical parent stitching
  • syscall hazard reproducers for ppoll, read/readv, and nanosleep variants
  • the profiling suite with CPU timer sampling enabled under the default fast-copy configuration, plus focused fast-copy-disabled coverage
  • scripts/lint cformat, scripts/lint profiling-native-check, scripts/lint checks, and git diff --check
  • latest-main validation with CPython 3.10 and 3.12 native builds, linked-parent greenlet tests, CPU timer ring/TID-table tests, and CPU timer gevent attribution
  • post-[PROF-15591] feat(profiling): reservoir sampling for tasks #19428 validation with a complete CPython 3.10 native build and native sampling-cycle, ring, and TID-table tests
  • task-visitor validation with CPython 3.10 and 3.14 native builds and hundreds of correctly attributed, parent-stitched Python 3.14 asyncio CPU samples across repeated checks
  • latest-main validation at b16f02e665 with CPython 3.10 and 3.14 release native builds, all 29 native stack tests, and 251 correctly attributed, parent-stitched Python 3.14 asyncio CPU samples
  • latest-main validation at 5a9dafde4d with a CPython 3.12 RelWithDebInfo standalone build and all 34 native stack tests after adopting the native span-link manager rename

On a CPython 3.12 workload with 501 asyncio tasks, selective task reconstruction reduced median CPU timer drain cost from about 2.82 seconds to 0.249 seconds, a 91% reduction, while preserving attribution and wall-sample recovery.

Risks

This path depends on asynchronous signals and version-specific CPython frame layouts. It is Linux-only, private, opt-in, disabled by default, and disabled in embedded interpreters. Unsupported or unsafe runtime conditions disable CPU timer sampling rather than falling back to mixed CPU accounting.

A pending SIGPROF can interrupt a native extension syscall that neither masks the signal nor retries EINTR. CPython's PEP 475 paths retry affected syscalls, and the test suite documents the remaining raw ppoll limitation with an expected-failure reproducer.

Additional Notes

Signature-only history update: fd976174d3 is now signed as fdc9363203, and its ten descendants were re-signed. Every rewritten commit retains its original file tree, message, authorship, dates, and merge relationships.

#19428 now bounds the number of leaf task and greenlet samples emitted by each wall-sampling cycle. CPU timer samples remain outside that reservoir because each signal sample matches at most one captured task or greenlet and emits one CPU sample.

PRs spun out from this work

Span-to-profile correlation is covered by the separate span-attribution chain spun out from this work. It keeps correlation working for physical thread stacks, asyncio task stacks, and greenlet stacks:

Prerequisites already merged into main:

Open max-frame prerequisite:

Cache sizing is intentionally outside this stack. This branch already retains the fixed 1024-entry frame cache and contains none of #20351's dynamic cache-scaling changes. Evaluate #20351 after #19085 and the rest of the stack have merged; it is not a prerequisite.

Independent test hardening already merged into main:

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jun 24, 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/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/CMakeLists.txt                 @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/__init__.py                    @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/__init__.pyi                   @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/_stack.pyi                     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/cpython/asyncio_debug.h  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/danger.h         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h        @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/cpu_sample_ring.hpp    @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/cpu_timer.hpp          @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/cpu_timer_tid_table.hpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/sampler.hpp            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/cpu_timer.cpp              @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/asyncio_debug.cc    @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc           @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/threads.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/internal/datadog/profiling/stack/src/stack_renderer.cpp         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_asyncio_debug.cpp    @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_cpu_sample_ring.cpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_cpu_timer_tid_table.cpp  @DataDog/profiling-python
ddtrace/internal/settings/profiling.py                                  @DataDog/profiling-python
ddtrace/profiling/collector/stack.py                                    @DataDog/profiling-python
releasenotes/notes/prof-14213-cpu-timer-profiler.yaml                   @DataDog/apm-python
tests/profiling/cpu_timer_native_syscall_hazard_app.py                  @DataDog/profiling-python
tests/profiling/native_cpu_timer_syscall_hazards.c                      @DataDog/profiling-python
tests/profiling/suitespec.yml                                           @DataDog/profiling-python
tests/profiling/test_cpu_timer.py                                       @DataDog/profiling-python
tests/profiling/test_cpu_timer_native_syscalls.py                       @DataDog/profiling-python
tests/profiling/test_profiling_config.py                                @DataDog/profiling-python

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Jun 24, 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: 873009c | Docs | View more details | Give us feedback!

@pr-commenter

pr-commenter Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-18 19:18:14

Comparing candidate commit 873009c in PR branch taegyunkim/prof-14213-timer-create with baseline commit 71ab428 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 625 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 [-504.484ns; +894.003ns] or [-4.727%; +8.376%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-28.470ns; +44.155ns] or [-4.438%; +6.883%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1379.917ns; +2261.618ns] or [-6.947%; +11.385%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1747.470ns; +1738.279ns] or [-9.019%; +8.972%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-229.419ns; +481.411ns] or [-5.385%; +11.299%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-91.360ns; +348.878ns] or [-3.464%; +13.229%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-84.583ns; +96.648ns] or [-6.109%; +6.980%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4422.313ns; +4506.813ns] or [-9.036%; +9.209%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-841.552ns; +972.458ns] or [-8.243%; +9.525%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-42.505µs; +69.387µs] or [-7.380%; +12.047%]

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

@r1viollet

r1viollet commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

@taegyunkim do you need help reviewing on this PR ?

@taegyunkim taegyunkim left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@r1viollet I'd want to make more changes to this PR. Will let you know when review is needed!

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 9, 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

@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-timer-create branch from 351ca0e to 3ebcfb0 Compare July 13, 2026 17:19
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jul 13, 2026
## Description

Pure refactor of existing stack sampler internals, with no intended behavior or internal contract changes, in preparation for timer_create based cpu time profiling in #18724 

Specifically:

- Extracts the existing task/greenlet/thread-stack rendering branch in `ThreadInfo::sample()` into a local `render_unwound_stacks()` helper.
- Extracts duplicate one-time thread registration failure logging in `Sampler::register_thread()` into a local helper.

This does not introduce CPU timer profiling, new configuration, new native bindings, or changes to thread registration semantics.

## Testing

- `scripts/lint cformat`

Attempted a targeted profiling test run from the worktree, but the test runner failed during riot venv setup before executing tests due the worktree using `/home/bits/project/.riot`, which was not writable/available in that context.

## Risks

Low. This is intended to be behavior-preserving refactoring only.

## Additional Notes

No changelog needed, internal refactor only.


Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
taegyunkim and others added 5 commits July 13, 2026 20:15
Explain why ThreadAltStack adopts a pre-existing alternate signal stack
instead of replacing it: the application, CPython's faulthandler, or
libdatadog's crashtracker (which by default creates and owns a larger alt
stack) may have installed it, and the destructor must never disable or free
an alt stack this object did not allocate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add a native gtest for ThreadAltStack: an adopted (pre-existing) alternate
signal stack must not be disabled on thread-local cleanup, while a stack this
helper allocated is disabled and freed. The adopted-stack case fails without
the owns_mapping guard, so it locks in this PR's behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…d it

ThreadAltStack's destructor disabled whatever alternate signal stack was
installed on the thread whenever it owned a mapping, without checking that the
installed stack was still the one it installed. If another component (for
example libdatadog crashtracker) replaced the thread's alt stack after we
installed ours, teardown would strip that replacement, degrading the other
owner's fault handling. Only disable the alt stack when it is still ours
(cur.ss_sp == mem); free our own mapping regardless.

Adds a regression test (DestructorDoesNotDisableReplacedAltStack) that fails
without this guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jul 14, 2026
## Description

The profiling safe-copy helper uses a per-thread alternate signal stack for its `SIGSEGV` and `SIGBUS` handlers. When an alternate stack was already installed by the application, CPython's faulthandler, or crashtracker, `ThreadAltStack` reused it but still disabled it during thread-local teardown. That could leave the original owner without its alternate stack and weaken its fault handling.

Track whether `ThreadAltStack` allocated the mapping itself. Teardown now disables and unmaps only profiler-owned stacks, while adopted stacks remain installed for their original owner. The installation failure path also unmaps a profiler allocation when `sigaltstack()` fails.

A release note documents the fault-handling fix.

## Testing

- Passed locally: `ddtrace/internal/datadog/profiling/build_standalone.sh -- RelWithDebInfo stack_test`
  - 4/4 native CTests passed
  - verifies that an adopted alternate stack remains installed after `ThreadAltStack` teardown
  - verifies that a profiler-owned alternate stack is disabled during teardown
- `scripts/lint cformat`

## Risks

Low. The change narrows teardown to resources owned by the profiler and does not alter public APIs or configuration. Profiler-owned alternate stacks retain their existing cleanup behavior.

## Additional Notes

Stacked out from the CPU timer profiler work, #18724, to keep this native safety fix independently reviewable.

Follow-up PR #19026 handles the complementary case where another component replaces a profiler-owned alternate stack after the profiler installs it.

[PROF-14213](https://datadoghq.atlassian.net/browse/PROF-14213)


[PROF-14213]: https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
@taegyunkim taegyunkim changed the title feat(profiling): add Linux CPU timer stack profiler feat(profiling): add opt-in Linux CPU timer stack profiler Sep 9, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-timer-create branch from d4cc4b0 to 12a80a9 Compare September 9, 2026 19:11
…-timer-create

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/__init__.pyi
#	ddtrace/internal/datadog/profiling/stack/_stack.pyi
#	ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h
#	ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc
#	ddtrace/internal/datadog/profiling/stack/src/stack.cpp
#	ddtrace/profiling/collector/stack.py
…-timer-create

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Sep 15, 2026
## Description

The CPU timer profiler work in #18724 needs to scan lightweight asyncio task identities before constructing `TaskInfo` only for the sampled task and its parents. Today, task-source traversal constructs every `TaskInfo` directly, so it cannot be reused for that path.

This PR separates task-address discovery from snapshot construction behind a private visitor. It does not add CPU timer behavior, configuration, or public API.

### Structure

Before this change, each Python-version-specific task source constructed `TaskInfo` snapshots directly:

```text
task source -> TaskInfo::create() -> loop filter -> wall task list
```

After this change, task sources report addresses through `for_each_task_address()`. Its callback returns `Result<void>`. `get_all_tasks()` supplies the existing wall-sampling materialization and filtering logic, while future sampling paths can supply a lightweight identity callback:

```text
                                      /-> TaskInfo::create() -> loop filter -> wall task list
task source -> task-address visitor -|
                                      \-> future lightweight identity scan
```

### Traversal semantics

- Callback failures stop traversal immediately and propagate through `Result<void>` without exceptions.
- Wall sampling preserves best-effort handling of individually unreadable tasks by returning success from its callback when `TaskInfo::create()` fails.
- Python 3.14 circular-list traversal returns addresses from `get_task_addresses_from_linked_list()` only after the complete list passes the consistency checks from #19798.
- A malformed Python 3.14 linked-list snapshot publishes no addresses and is treated as an empty source, allowing discovery to continue with other sources.

### Preserved invariants

- Task sources, source order, and source availability checks are unchanged.
- Python 3.14 per-thread and per-interpreter lists are visited only when both `tstate` and `tstate_addr` are available.
- Validated linked-list addresses retain their original order.
- Wall sampling retains its existing event-loop filtering and Python 3.14 cross-source deduplication policy.
- Pre-Python 3.14 behavior is unchanged, including its existing lack of cross-source deduplication.

## Testing

- Based on `origin/main` at `1474aa5746`.
- Built and ran the standalone native `stack_test` target in `RelWithDebInfo` mode with warnings as errors against:
  - CPython 3.10.12, 22/22 tests passed.
  - CPython 3.14.5, 26/26 tests passed, including malformed-list publication, callback error propagation and early termination, and cross-source deduplication coverage.
- Ran `scripts/lint cformat`.
- Ran `scripts/lint profiling-native-check`.
- Ran `scripts/lint checks`.
- An earlier CPython 3.10 wall-profiler benchmark with 500 suspended tasks and fixed 1 ms sampling showed no measurable regression, with baseline and candidate medians overlapping around 0.44 CPU seconds.

## Risks

Low. The extraction is private and retains the existing wall-sampling construction and filtering path. Python 3.14 linked-list traversal temporarily stores task addresses before invoking the visitor so malformed sources cannot expose partial results. The vector is bounded by the existing 65,536-node traversal limit and stores pointers rather than `TaskInfo` snapshots.

## Additional Notes

No release note is needed because this is an internal, behavior-preserving refactor.


Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
Adopt main's Result-returning task address visitor and expanded native traversal tests. Adapt CPU timer task identity collection and the renamed stack unwind safety limit.

Validation: full scripts/lint checks; 34 CPython 3.12.13 and 37 CPython 3.14.5 native stack tests passed. Python integration runner remains blocked by container worktree/cache permissions. Benchmark discovery found no matching suite.
const pid_t current_tid = raw_gettid();
for (auto& item : g_state.live_by_thread_id) {
CaptureState& state = *item.second;
if (current_tid == static_cast<pid_t>(state.native_tid)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

this check will not work as the thread id is different in child

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

#!/usr/bin/env python3
"""Reproduce ddtrace's dangling alternate signal stack after fork on Linux."""

import faulthandler
import os
import signal
import threading
import time


# These must be set before importing ddtrace.
os.environ["DD_PROFILING_OUTPUT_PPROF"] = "/tmp/ddtrace-postfork-altstack"
os.environ["_DD_PROFILING_STACK_ADAPTIVE_SAMPLING_ENABLED"] = "0"
os.environ["_DD_PROFILING_STACK_CPU_TIMER_ENABLED"] = "1"
os.environ["_DD_PROFILING_STACK_CPU_TIMER_INTERVAL_MS"] = "1"

from ddtrace.profiling import profiler


faulthandler.register(signal.SIGUSR1)

p = profiler.Profiler()
p.start()
result = []


def fork_from_profiled_worker():
    # Give the sampler time to discover this worker and install its stack.
    deadline = time.thread_time() + 0.1
    while time.thread_time() < deadline:
        pass

    pid = os.fork()
    if pid == 0:
        # ddtrace's at-fork hook unmapped the still-registered alt stack.
        signal.raise_signal(signal.SIGUSR1)
        os._exit(0)
    result.append(os.waitpid(pid, 0)[1])


thread = threading.Thread(target=fork_from_profiled_worker)
thread.start()
thread.join()
p.stop()

assert os.waitstatus_to_exitcode(result[0]) == -signal.SIGSEGV, result[0]
print(f"wait status={result[0]} core={os.WCOREDUMP(result[0])}")
print("reproduced: SA_ONSTACK signal crashed the fork child with SIGSEGV")

…-timer-create

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/include/sampler.hpp
#	ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
#	ddtrace/internal/datadog/profiling/stack/src/stack.cpp
…after fork

The child's postfork handler identified the forking thread by its parent TID,
which changes across fork, so it unmapped the alt stack that thread still had
installed. Later SA_ONSTACK signals then ran on freed memory, either crashing
or corrupting whatever the child mapped there next.

Identify the in-use alt stack by the inherited sigaltstack setting instead,
keep that mapping, and hand it to the thread's new CaptureState when it
registers again in the child.
…changes

Keep the CPU timer engine alive through exit like the other stack sampler
singletons, since the sampling thread can still drain it when uWSGI exits
without running the atexit hooks.

Add Python 3.15 to the unpinned protobuf row that runs with and without the
CPU timer, so that row keeps covering 3.15 as main now expects.
… drain

On Python 3.14+, the sampler clears the frame identity caches when a code
object generation changes, but only did so inside the wall sampling cycle.
The CPU timer drain runs on its own deadline and reads the same caches, so
it could resolve a reused code object address to a stale cached frame.

Snapshot interpreters and validate code object generations once per loop
iteration, before either the drain or the wall sample. Wall sampling still
skips the cycle when the snapshot is incomplete. The drain still runs, since
the caches were cleared and skipping would let the rings fill.
…-timer-create

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/CMakeLists.txt
#	ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
#	ddtrace/internal/datadog/profiling/stack/src/stack.cpp
… table

On Python 3.14, the CPU timer signal handler read asyncio_running_task at
its compile-time offset in _PyThreadStateImpl. That offset can differ from
the running 3.14 patch release, which loses task identity for CPU samples.

Take it from CPython's AsyncioDebug table, together with the task-list head
offsets. Until the table is found, CPU samples carry no running-task
identity, matching how the task lists are skipped.
…tself

On CPython 3.13+, threading._after_fork() calls _set_native_id() on the
forking thread, so the child registers it twice. The second registration
took our own alt stack for an application one, and retiring the first
state then unmapped it. Hand the stack to the replacing state instead.
…-timer-create

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/src/echion/danger.cc
#	ddtrace/internal/datadog/profiling/stack/src/sampler.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants