Skip to content

chore(profiling): add conditional span link cleanup - #19377

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 1 commit into
mainfrom
taegyunkim/profiling-span-link-cleanup-primitives
Jul 29, 2026
Merged

gh-worker-dd-mergequeue-cf854d[bot] merged 1 commit into
mainfrom
taegyunkim/profiling-span-link-cleanup-primitives

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

@datadog-prod-us1-6

datadog-prod-us1-6 Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

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

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-span-link-cleanup-primitives branch from 59f73eb to 9bc3860 Compare July 29, 2026 17:38
@taegyunkim taegyunkim changed the title feat(profiling): add conditional span link cleanup chore(profiling): add conditional span link cleanup Jul 29, 2026
@taegyunkim taegyunkim added the Profiling Continous Profling label Jul 29, 2026
@taegyunkim
taegyunkim marked this pull request as ready for review July 29, 2026 17:54
@taegyunkim
taegyunkim requested a review from a team as a code owner July 29, 2026 17:54
@taegyunkim
taegyunkim requested a review from gyuheon0h July 29, 2026 17:54

@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: 9bc3860420

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@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 19:24:05 UTC ℹ️ Start processing command /merge


2026-07-29 19:24:10 UTC ℹ️ MergeQueue: pull request added to the queue

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


2026-07-29 20:04:53 UTC 🚨 MergeQueue: This merge request is in error

mergequeue build completed successfully, but the github api returned an error while merging the pr

Details

Error: PUT https://api.github.com/repos/DataDog/dd-trace-py/pulls/19377/merge: 403 Merging stacked PRs via this API is not supported. Use the web interface instead. [] (Request ID: BE2C:4AF1B:327C96:B14B38:6A6A5CDC)
Please check if you have the right permissions to perform this operation.

FullStacktrace:
activity error (type: github.GithubService_MergePullRequest, scheduledEventID: 50, startedEventID: 51, identity: 1@github-worker-7657f45496-2n6pv@): PUT https://api.github.com/repos/DataDog/dd-trace-py/pulls/19377/merge: 403 Merging stacked PRs via this API is not supported. Use the web interface instead. [] (Request ID: BE2C:4AF1B:327C96:B14B38:6A6A5CDC)
Please check if you have the right permissions to perform this operation. (type: GitForbidden, retryable: false): PUT https://api.github.com/repos/DataDog/dd-trace-py/pulls/19377/merge: 403 Merging stacked PRs via this API is not supported. Use the web interface instead. [] (type: ErrorResponse, retryable: true)

@taegyunkim

Copy link
Copy Markdown
Contributor Author

/merge -f --reason "it passed all the CI in the merge branch but seems like our mergequeue doesn't support merging one PR from a stacked PRs"

@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:07:03 UTC ℹ️ Start processing command /merge -f --reason "it passed all the CI in the merge branch but seems like our mergequeue doesn't support merging one PR from a stacked PRs"


2026-07-29 20:07:08 UTC ℹ️ MergeQueue: pull request added to the queue

The expected merge time in main is approximately 0s (p90).


2026-07-29 20:07:23 UTC 🚨 MergeQueue: This merge request is in error

mergequeue build completed successfully, but the github api returned an error while merging the pr

Details

Error: PUT https://api.github.com/repos/DataDog/dd-trace-py/pulls/19377/merge: 403 Merging stacked PRs via this API is not supported. Use the web interface instead. [] (Request ID: F34F:1ACD37:361855:BE463D:6A6A5D71)
Please check if you have the right permissions to perform this operation.

FullStacktrace:
activity error (type: github.GithubService_MergePullRequest, scheduledEventID: 65, startedEventID: 66, identity: 1@github-worker-7657f45496-zss8k@): PUT https://api.github.com/repos/DataDog/dd-trace-py/pulls/19377/merge: 403 Merging stacked PRs via this API is not supported. Use the web interface instead. [] (Request ID: F34F:1ACD37:361855:BE463D:6A6A5D71)
Please check if you have the right permissions to perform this operation. (type: GitForbidden, retryable: false): PUT https://api.github.com/repos/DataDog/dd-trace-py/pulls/19377/merge: 403 Merging stacked PRs via this API is not supported. Use the web interface instead. [] (type: ErrorResponse, retryable: true)

@taegyunkim

Copy link
Copy Markdown
Contributor Author

/merge -f --reason "it passed all the CI in the merge branch but seems like our mergequeue doesn't support merging one PR from a stack of PRs, retrying after unstacking"

@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:08:48 UTC ℹ️ Start processing command /merge -f --reason "it passed all the CI in the merge branch but seems like our mergequeue doesn't support merging one PR from a stack of PRs, retrying after unstacking"


2026-07-29 20:08:53 UTC ℹ️ MergeQueue: pull request added to the queue

The expected merge time in main is approximately 0s (p90).


2026-07-29 20:09:02 UTC ℹ️ MergeQueue: This merge request was merged

Warning

This change was merged without running any pre merge CI checks

Reason: it passed all the CI in the merge branch but seems like our mergequeue doesn't support merging one PR from a stack of PRs, retrying after unstacking

@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit 78c2a93 into main Jul 29, 2026
477 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the taegyunkim/profiling-span-link-cleanup-primitives branch July 29, 2026 20:09
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

ddtrace/internal/datadog/profiling/stack/_stack.pyi                     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/thread_span_links.hpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack.cpp                  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/thread_span_links.cpp      @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_thread_span_links.cpp  @DataDog/profiling-python

@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

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>
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

changelog/no-changelog A changelog entry is not required for this PR. Profiling Continous Profling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants