Skip to content

fix(profiling): preserve propagated span metadata - #19378

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 3 commits into
mainfrom
taegyunkim/profiling-propagated-span-metadata
Jul 29, 2026
Merged

gh-worker-dd-mergequeue-cf854d[bot] merged 3 commits into
mainfrom
taegyunkim/profiling-propagated-span-metadata

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-span-link-cleanup-primitives branch from 59f73eb to 9bc3860 Compare July 29, 2026 17:38
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-propagated-span-metadata branch from d059b96 to 7a0d380 Compare July 29, 2026 17:38
@taegyunkim
taegyunkim marked this pull request as ready for review July 29, 2026 17:54
@taegyunkim
taegyunkim requested review from a team as code owners July 29, 2026 17:54
@taegyunkim
taegyunkim marked this pull request as draft July 29, 2026 17:54
@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: a12926e | Docs | Datadog PR Page | Give us feedback!

@taegyunkim
taegyunkim marked this pull request as ready for review July 29, 2026 18:07
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jul 29, 2026
## Description

The stack profiler stores trace metadata in a native map keyed by Python thread ID. Later attribution fixes need two distinct cleanup operations:

- remove an entry only when it still contains an expected span ID;
- clear the current thread entry unconditionally when its execution context is known to be invalid.

This PR adds those internal primitives without changing when span links are published or removed:

```text
unlink_span(expected_span_id)  -> compare and erase atomically
clear_span()                   -> erase the current thread entry
```

The expected-ID check and erase occur under the existing `ThreadSpanLinks` mutex, preventing an older execution context from deleting a newer span link on the same physical thread.

Python-facing mutations continue to release the GIL before waiting for the profiler mutex, preserving the thread-pool deadlock protection from #14852.

This is the first prerequisite in the PROF-14213 span-attribution stack. It has no user-visible behavior until called by the later cleanup PRs.

## Testing

- Standalone native `ThreadSpanLinks` suite: `3 passed`.
- The new regression verifies that a non-matching expected span ID preserves the entry and a matching ID removes it.
- clang-format 18.
- `git diff --check`.
- The cumulative stacked tip passed the full Python 3.14 gevent profiling suite: `398 passed, 13 skipped, 2 xpassed`.

## Risks

Low. This adds internal methods and bindings but does not call them from existing attribution paths. Both operations use the existing mutex and expected O(1) map lookup/erase behavior.

## Additional Notes

- Next stacked PR: #19378
- No release note is needed because this PR does not change customer-visible behavior.
- 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-span-link-cleanup-primitives to main July 29, 2026 20:09

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

LGTM I assume unlink_span is currently dead code because we are using it in the stacked PR?

@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

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

ddtrace.trace -> ddtrace._trace.tracer -> ddtrace.internal.debug -> ddtrace.trace
ddtrace -> ddtrace.trace -> ddtrace._trace.tracer -> ddtrace.internal.debug -> ddtrace
ddtrace -> ddtrace.trace -> ddtrace._trace.tracer -> ddtrace.internal.debug -> ddtrace.internal.runtime.runtime_metrics -> ddtrace

@taegyunkim

Copy link
Copy Markdown
Contributor Author

LGTM I assume unlink_span is currently dead code because we are using it in the stacked PR?

@gyuheon0h correct, but it's actually from this PR's previous PR #19377, and it's now merged. This PR is rebased to latest main, and should have a smaller set of diffs.

@taegyunkim

Copy link
Copy Markdown
Contributor Author

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-07-29 20:20:50 UTC ℹ️ Start processing command /merge


2026-07-29 20:20:56 UTC ℹ️ MergeQueue: waiting for PR to be ready

This pull request is not mergeable according to GitHub. Common reasons include pending required checks, missing approvals, or merge conflicts — but it could also be blocked by other repository rules or settings.
It will be added to the queue as soon as checks pass and/or get approvals. View in MergeQueue UI.
Note: if you pushed new commits since the last approval, you may need additional approval.
You can remove it from the waiting list with /remove command.


2026-07-29 20:54:07 UTC ℹ️ MergeQueue: merge request added to the queue

The expected merge time in main is approximately 48m (p90).


2026-07-29 21:28:17 UTC ℹ️ MergeQueue: This merge request was merged

@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit 8e55021 into main Jul 29, 2026
460 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the taegyunkim/profiling-propagated-span-metadata branch July 29, 2026 21:28
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

ddtrace/internal/datadog/profiling/stack/__init__.py                    @DataDog/profiling-python
releasenotes/notes/profiling-preserve-propagated-span-metadata-87f838a2df042602.yaml  @DataDog/apm-python
tests/profiling/collector/test_stack_propagated_context.py              @DataDog/profiling-python
tests/profiling/collector/test_stack_threadpool.py                      @DataDog/profiling-python

brettlangdon pushed a commit that referenced this pull request Aug 3, 2026
## Description

The stack profiler stores trace metadata in a native map keyed by Python thread ID. Later attribution fixes need two distinct cleanup operations:

- remove an entry only when it still contains an expected span ID;
- clear the current thread entry unconditionally when its execution context is known to be invalid.

This PR adds those internal primitives without changing when span links are published or removed:

```text
unlink_span(expected_span_id)  -> compare and erase atomically
clear_span()                   -> erase the current thread entry
```

The expected-ID check and erase occur under the existing `ThreadSpanLinks` mutex, preventing an older execution context from deleting a newer span link on the same physical thread.

Python-facing mutations continue to release the GIL before waiting for the profiler mutex, preserving the thread-pool deadlock protection from #14852.

This is the first prerequisite in the PROF-14213 span-attribution stack. It has no user-visible behavior until called by the later cleanup PRs.

## Testing

- Standalone native `ThreadSpanLinks` suite: `3 passed`.
- The new regression verifies that a non-matching expected span ID preserves the entry and a matching ID removes it.
- clang-format 18.
- `git diff --check`.
- The cumulative stacked tip passed the full Python 3.14 gevent profiling suite: `398 passed, 13 skipped, 2 xpassed`.

## Risks

Low. This adds internal methods and bindings but does not call them from existing attribution paths. Both operations use the existing mutex and expected O(1) map lookup/erase behavior.

## Additional Notes

- Next stacked PR: #19378
- No release note is needed because this PR does not change customer-visible behavior.
- 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>
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>
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.

3 participants