Skip to content

fix(profiling): isolate gevent span links - #19379

Closed
taegyunkim wants to merge 2 commits into
taegyunkim/profiling-logical-span-linksfrom
taegyunkim/profiling-gevent-span-links
Closed

taegyunkim wants to merge 2 commits into
taegyunkim/profiling-logical-span-linksfrom
taegyunkim/profiling-gevent-span-links

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR is stacked on #19420 and follows the merged physical cleanup in #19529.

Fixes trace and endpoint attribution for gevent by associating each native-tracked greenlet with its own copied span metadata instead of applying one physical-thread link to every greenlet stack.

Routing and rendering

  • Registers gevent as a logical provider for the shared activation router.
  • Returns a gevent logical target only when the native sampler confirms that the greenlet is renderable.
  • Routes tracing activations to the current greenlet domain and ID.
  • Snapshots greenlet-keyed span metadata beside each frame snapshot before deferred rendering.
  • Leaves a known greenlet unattributed when its mapping is missing. It never falls back to the physical-thread span.
  • Keeps untracked implicit main greenlets on physical-thread routing.

Lifecycle handling

  • Seeds a newly created traced greenlet from its captured tracing Context because installing that Context in TracingMixin.run does not dispatch a tracing activation.
  • Prevents lazy discovery of an already-running greenlet from restoring stale construction-time context over a newer activation.
  • Treats native registration as authoritative and clears logical attribution when a greenlet is untracked.
  • Handles tracked Hubs as logical targets.
  • Clears Python integration bookkeeping after fork, while the shared child hook clears native mappings.

For this fix, creation seeding continues to read the private greenlet.trace_context field maintained by the tracing integration. Replacing that coupling with a core greenlet lifecycle event is intentionally deferred to a follow-up.

Testing

Added coverage for:

  • two concurrently suspended greenlets under different endpoints;
  • inherited attribution while the parent is active, followed by cleanup after the parent finishes;
  • no logical routing before authoritative native registration;
  • lazy discovery not overwriting a newer publication;
  • post-fork Python integration reset;
  • untracked main-greenlet physical routing;
  • gevent import without active logical execution.

Validation completed:

  • Python 3.12 gevent profiling suite after integrating the latest task-reservoir changes: 407 passed, 15 skipped, 2 xfailed
  • Python 3.13 gevent-focused profiling run: 32 passed
  • scripts/lint checks
  • scripts/lint typing -- ddtrace/profiling/_gevent.py
  • scripts/lint cformat
  • scripts/lint profiling-native-check
  • native stack compilation with warnings treated as errors
  • git diff --check

scripts/run-benchmarks --list found no matching benchmark suite for the changed files.

Risks

  • Greenlet creation, activation, and cleanup perform expected O(1) mapping operations while profiling is enabled.
  • The sampler copies scalar and string attribution metadata while taking the existing span-link mutex.
  • Greenlet trace callbacks remain exception-safe. Attribution failures cannot escape and uninstall the callback.
  • Numeric IDs and copied metadata do not retain greenlets, tracing Contexts, or Spans.
  • The conservative failure mode is missing attribution, never another greenlet's physical-thread attribution.

Additional Notes

@datadog-official

datadog-official Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 455a394 | Docs | Datadog PR Page | Give us feedback!

@taegyunkim taegyunkim added the Profiling Continous Profling label Jul 29, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 3eefb90 to 1694041 Compare July 29, 2026 18:23
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jul 29, 2026
## Description

This PR is stacked on the native cleanup primitives prerequisite.

### Problem

When tracing crosses an execution boundary without sharing the live parent `Span`, ddtrace passes a detached `ddtrace.trace.Context` containing the trace ID and current parent span ID. For example, the futures integration copies this Context when submitting work to a thread-pool worker, and that active Context can later be inherited by a child greenlet.

A child span created from this detached Context has the correct parent span ID but no live parent `Span` object. Copied profiler metadata on the Context carries the original local-root span ID and span type needed for endpoint correlation.

The profiler previously copied that local-root metadata into `threading.local()` storage during Context activation. That works for a simple thread-pool worker, but gevent greenlets share a physical thread. One greenlet could therefore overwrite the detached Context metadata needed by another greenlet.

### Fix

For a span created with `child_of=Context`, read the copied profiler metadata directly from `span._parent_context` instead of physical-thread-local side state.

Conceptually:

```text
detached tracing Context:
    current span ID:        200
    copied local-root ID:   100
    copied span type:       web

child span:
    span ID:                300
    profiling local root:   100
```

The Context remains the source of truth across both thread and greenlet execution boundaries. If profiler metadata is absent, the Context's span ID remains the fallback local-root ID.

## Testing

Fresh Python 3.14 gevent profiling environment:

- Context without profiler metadata falls back to its span ID;
- Context with profiler metadata preserves the copied local-root ID and span type;
- a greenlet child span retains the local root copied from its detached parent Context.

Result: `3 passed`.

Also validated with targeted formatting, `git diff --check`, and the cumulative full Python 3.14 profiling suite at the final stack tip: `398 passed, 13 skipped, 2 xpassed`.

## Risks

Low. The change removes physical-thread-local side state and reads scalar/string metadata already attached to the detached Context. It does not retain a parent Span or alter tracing propagation.

## Additional Notes

- Previous PR: #19377.
- Next stacked PR: #19379.
- A customer-facing profiling fix release note is included.
- Jira: [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>
Base automatically changed from taegyunkim/profiling-propagated-span-metadata to main July 29, 2026 21:28
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against taegyunkim/profiling-logical-span-links 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/__init__.pyi                   @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/_stack.pyi                     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/sampler.hpp            @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/profiling/_gevent.py                                            @DataDog/profiling-python
releasenotes/notes/profiling-gevent-span-links-1f27a7e92d4b83c1.yaml    @DataDog/apm-python
tests/profiling/collector/test_stack_gevent_endpoint_labels.py          @DataDog/profiling-python
tests/profiling/test_gevent.py                                          @DataDog/profiling-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

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

ddtrace.contrib.internal.django.patch -> ddtrace.contrib.internal.django.response -> ddtrace.contrib.internal.django.patch
ddtrace.contrib.internal.pytorch._distributed -> ddtrace.contrib.internal.pytorch._rank_root -> ddtrace.contrib.internal.pytorch._distributed
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
ddtrace.llmobs -> ddtrace.llmobs._evaluators -> ddtrace.llmobs._evaluators.format -> ddtrace.llmobs._experiment -> ddtrace.llmobs
ddtrace.appsec._asm_request_context -> ddtrace.appsec._iast._iast_request_context_base -> ddtrace.appsec._iast._iast_env -> ddtrace.appsec._iast.reporter -> ddtrace.appsec._exploit_prevention.stack_traces -> ddtrace.appsec._asm_request_context

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from fcbcdac to 6d882af Compare July 30, 2026 21:09
@taegyunkim taegyunkim changed the title fix(profiling): synchronize gevent span links fix(profiling): isolate gevent span links Jul 30, 2026
@taegyunkim
taegyunkim changed the base branch from main to taegyunkim/profiling-clear-finished-endpoint July 30, 2026 21:10
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 9a412ec to 6b72027 Compare July 30, 2026 21:30
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 6d882af to 30261ba Compare July 30, 2026 21:30
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 6b72027 to 658892c Compare July 30, 2026 21:31
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 30261ba to 5935786 Compare July 30, 2026 21:31
brettlangdon pushed a commit that referenced this pull request Aug 3, 2026
## Description

This PR is stacked on the native cleanup primitives prerequisite.

### Problem

When tracing crosses an execution boundary without sharing the live parent `Span`, ddtrace passes a detached `ddtrace.trace.Context` containing the trace ID and current parent span ID. For example, the futures integration copies this Context when submitting work to a thread-pool worker, and that active Context can later be inherited by a child greenlet.

A child span created from this detached Context has the correct parent span ID but no live parent `Span` object. Copied profiler metadata on the Context carries the original local-root span ID and span type needed for endpoint correlation.

The profiler previously copied that local-root metadata into `threading.local()` storage during Context activation. That works for a simple thread-pool worker, but gevent greenlets share a physical thread. One greenlet could therefore overwrite the detached Context metadata needed by another greenlet.

### Fix

For a span created with `child_of=Context`, read the copied profiler metadata directly from `span._parent_context` instead of physical-thread-local side state.

Conceptually:

```text
detached tracing Context:
    current span ID:        200
    copied local-root ID:   100
    copied span type:       web

child span:
    span ID:                300
    profiling local root:   100
```

The Context remains the source of truth across both thread and greenlet execution boundaries. If profiler metadata is absent, the Context's span ID remains the fallback local-root ID.

## Testing

Fresh Python 3.14 gevent profiling environment:

- Context without profiler metadata falls back to its span ID;
- Context with profiler metadata preserves the copied local-root ID and span type;
- a greenlet child span retains the local root copied from its detached parent Context.

Result: `3 passed`.

Also validated with targeted formatting, `git diff --check`, and the cumulative full Python 3.14 profiling suite at the final stack tip: `398 passed, 13 skipped, 2 xpassed`.

## Risks

Low. The change removes physical-thread-local side state and reads scalar/string metadata already attached to the detached Context. It does not retain a parent Span or alter tracing propagation.

## Additional Notes

- Previous PR: #19377.
- Next stacked PR: #19379.
- A customer-facing profiling fix release note is included.
- Jira: [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 force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 658892c to c500e46 Compare August 5, 2026 17:01
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 5935786 to 7dedde7 Compare August 5, 2026 17:01
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from c500e46 to 615d186 Compare August 5, 2026 17:13
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 7dedde7 to 1af3b14 Compare August 5, 2026 17:13
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 615d186 to e121905 Compare August 5, 2026 17:16
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 1af3b14 to e484a3a Compare August 5, 2026 17:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from e121905 to b47705e Compare August 5, 2026 17:56
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from e484a3a to 2341e81 Compare August 5, 2026 17:56
Base automatically changed from taegyunkim/profiling-clear-finished-endpoint to taegyunkim/profiling-logical-span-links August 5, 2026 17:56
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 8bc4531 to a974497 Compare August 5, 2026 20:55
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch 2 times, most recently from a3e300e to fddee66 Compare August 6, 2026 00:32
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch 2 times, most recently from 3082d9b to 53bded1 Compare August 6, 2026 18:30
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from fddee66 to 8fe9a8a Compare August 6, 2026 19:16
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 53bded1 to 6bf922c Compare August 7, 2026 03:47
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 8fe9a8a to 59befd9 Compare August 7, 2026 03:47
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 6bf922c to 2ea638f Compare August 11, 2026 18:53
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 59befd9 to 8c9f7d5 Compare August 11, 2026 18:53
@cit-pr-commenter-54b7da

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

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 255 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=134)
ddtrace.llmobs._integrations.pydantic_ai -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)
ddtrace.debugging._debugger -×-> ddtrace.trace  (product:debugging -> product:tracing, score=132)
ddtrace.internal.ci_visibility.recorder -×-> ddtrace.trace  (product:ci_visibility -> product:tracing, score=132)

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

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 2ea638f to e1bdc05 Compare August 12, 2026 15:04
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 8c9f7d5 to 42d2c8a Compare August 12, 2026 15:05
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from e1bdc05 to fee5719 Compare August 12, 2026 15:18
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 42d2c8a to 07c8274 Compare August 12, 2026 15:18
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Aug 13, 2026
## Description

This is the first PR in the span-attribution stack. It fixes stale endpoint and span attribution for physical thread stacks before the later PRs introduce logical asyncio and gevent targets.

### Problem

The stack profiler samples threads independently of application execution, so it keeps a native per-thread copy of the span metadata needed to label profile samples. That copy must follow the lifetime of the tracing context. Otherwise, work that runs after a span finishes can still be labeled with the finished span ID, local-root span ID, and endpoint.

Context activation events are necessary, but they are not sufficient to keep these copies accurate. Consider this sequence:

1. A worker thread activates a span and publishes a native span link.
2. Another thread finishes that span.
3. The worker continues running without performing another context activation.

Finishing the span does not produce an activation event on the worker. Without a separate finish-time cleanup path, its copied link remains stale and subsequent samples are incorrectly attributed to the finished trace.

A local root can also finish before one of its children. In that case the child is still valid and can continue producing profile samples, so cleanup for the root must not remove mappings whose current span is that unfinished child.

### Solution

This PR makes the native `ThreadSpanLinks` store own both directions of each physical association under one mutex:

- thread ID to copied span metadata;
- current span ID to every thread carrying a copy of that exact span.

It then uses two complementary lifecycle signals:

- `ddtrace.context_provider.activate` handles immediate state replacement on the current thread. Activating a span or propagated `Context` publishes its mapping, restoring a parent replaces it, and activating `None` or a `Context` without a span ID clears it.
- `trace.span_finish` performs global reverse invalidation for the exact span that finished. It removes every copied physical-thread mapping for that span, including mappings published on another thread that may never receive another activation. It deliberately preserves mappings for unfinished children when their local root finishes first.

Updating the forward and reverse indexes atomically prevents the two views from diverging. Re-linking a thread removes its previous reverse-index entries first, so a later finish event for an older span cannot erase the thread's newer attribution.

Listener registration occurs only after the collector completes fallible initialization, and both listeners are removed during shutdown. Fork handling reconstructs the native mutex and inherited indexes without traversing potentially inconsistent parent state.

### Review follow-up

Native lifecycle bookkeeping now records in-flight physical span publications before releasing the GIL. If a span finishes while publication is waiting on the native mutex, cleanup is deferred until the final publication completes. This preserves the GIL release introduced in #14852 to avoid thread-pool deadlocks.

## Testing

Added coverage for:

- immediate physical-link clearing on context deactivation;
- finished child-span cleanup across physical threads;
- cross-thread finish cleanup before the linked worker performs another activation;
- preservation of active child links when the local root finishes first;
- reverse-index replacement when a thread advances to a new span;
- nested child-to-parent restoration;
- cleanup on reused thread-pool workers.

Validation completed on the reordered physical-only PR:

- Python 3.13 profiling suite in normal and fast-copy modes: `359 passed, 35 skipped, 2 xfailed` per mode
- Python 3.13 focused cross-thread finish regression: `1 passed` in each mode
- Python 3.11 profiling suite after hardening the reused-worker assertion: `309 passed, 85 skipped, 2 xfailed` in both normal and fast-copy modes
- Reused-worker regression repeated 11 times in both modes: `22 passed`
- Control experiment with the span-finish listener disabled: the cross-thread regression failed in both modes because post-finish samples retained the endpoint, confirming activation alone is insufficient
- `scripts/lint checks`
- targeted style and typing checks
- `scripts/lint cformat`
- `scripts/lint profiling-native-check`
- rebased onto current `main` at `3efdcbe3af`
- `git diff --check`

## Risks

- Physical activation updates perform expected O(1) forward and reverse-index mutations under the existing span-link mutex.
- Finished-span cleanup visits only threads indexed by the exact span that finished.
- The reverse index adds bounded memory proportional to currently linked physical threads.
- The rollback is to disable stack profiling or revert this PR.

## Additional Notes

- Next, common logical stack helpers: #19420
- Gevent integration: #19379
- Asyncio integration: #19346
- Includes a customer-facing profiling fix release note.

Before

<img width="1732" height="905" alt="Screenshot 2026-08-06 at 10 15 34 AM" src="https://github.com/user-attachments/assets/d6a69ad3-1324-4328-b241-c3dc2fdf7cd5" />

After

<img width="1749" height="908" alt="Screenshot 2026-08-06 at 10 15 24 AM" src="https://github.com/user-attachments/assets/cef79a9e-ddc9-4299-b3ff-492126e13ad2" />








Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 07c8274 to a6e40b1 Compare August 13, 2026 15:08
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from fee5719 to 4ec3922 Compare August 13, 2026 15:08
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from a6e40b1 to a9006e0 Compare August 13, 2026 15:10
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 4ec3922 to c37ab94 Compare August 13, 2026 15:10
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from a9006e0 to 8b4ff9b Compare August 13, 2026 18:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from c37ab94 to 20bb68d Compare August 13, 2026 18:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-gevent-span-links branch from 8b4ff9b to 455a394 Compare August 13, 2026 19:44
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch 2 times, most recently from 9011aa1 to 9fe9005 Compare August 14, 2026 16:00
@taegyunkim

Copy link
Copy Markdown
Contributor Author

Superseded by #19420. I folded this gevent implementation into the shared logical span-link PR so the first PR in the revised stack now provides an end-to-end functional fix. The remaining review order is #19420, #19346, then #19556.

@taegyunkim taegyunkim closed this Aug 14, 2026
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.

1 participant