Skip to content

fix(profiling): clear finished physical span links - #19529

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 12 commits into
mainfrom
taegyunkim/profiling-clear-finished-endpoint
Aug 13, 2026
Merged

gh-worker-dd-mergequeue-cf854d[bot] merged 12 commits into
mainfrom
taegyunkim/profiling-clear-finished-endpoint

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

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

Before

Screenshot 2026-08-06 at 10 15 34 AM

After

Screenshot 2026-08-06 at 10 15 24 AM

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Aug 5, 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: c5b6e97 | Docs | Datadog PR Page | Give us feedback!

@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: 82b9518ce8

ℹ️ 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".

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 6, 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.

No remaining files require a CODEOWNERS review.

@cit-pr-commenter-54b7da

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

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

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

Show existing cycles (showing 5 of 6 shortest)
ddtrace.appsec._common_module_patches -> ddtrace.appsec._listeners -> ddtrace.appsec._common_module_patches
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.llmobs -> ddtrace.llmobs._evaluators -> ddtrace.llmobs._evaluators.format -> ddtrace.llmobs._experiment -> ddtrace.llmobs
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

To see all cycles, download the cycles-base.json and cycles-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/cycles.py compare cycles-base.json cycles-pr.json

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 4899eaa to 941677e Compare August 7, 2026 03:47

@KowalskiThomas KowalskiThomas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Very nice!

Comment thread ddtrace/profiling/collector/stack.py Resolved
@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 256 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 256 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=134)
ddtrace.debugging._exception.replay -×-> ddtrace.trace  (product:debugging -> product:tracing, score=132)
ddtrace.profiling.collector.stack -×-> ddtrace.trace  (product:profiling -> product:tracing, score=132)
ddtrace.internal.ci_visibility.api._base -×-> ddtrace.trace  (product:ci_visibility -> product:tracing, score=132)
ddtrace.llmobs._integrations.vllm -×-> ddtrace.trace  (product:llmobs -> 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

Copy link
Copy Markdown
Contributor Author

@KowalskiThomas Thanks for reviewing. I have addressed all your comments. Please take another look

@taegyunkim
taegyunkim requested a balanced review from Copilot August 11, 2026 19:29
@taegyunkim

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: b5eb27b121

ℹ️ 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".

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds physical-thread span-link cleanup to prevent stale profiling attribution after spans finish.

Changes:

  • Adds reverse span-to-thread indexing and finish-time invalidation.
  • Registers activation and span-finish lifecycle listeners.
  • Adds native/integration tests, profile helpers, and a release note.

Reviewed changes

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

Show a summary per file
File Description
ddtrace/profiling/collector/stack.py Manages span-link listeners.
ddtrace/internal/datadog/profiling/stack/__init__.py Handles deactivation and finished spans.
ddtrace/internal/datadog/profiling/stack/__init__.pyi Types the finish callback.
ddtrace/internal/datadog/profiling/stack/_stack.pyi Types native unlinking.
ddtrace/internal/datadog/profiling/stack/include/thread_span_links.hpp Defines reverse-index storage.
ddtrace/internal/datadog/profiling/stack/src/thread_span_links.cpp Implements atomic link cleanup.
ddtrace/internal/datadog/profiling/stack/src/stack.cpp Exposes native finish invalidation.
ddtrace/internal/datadog/profiling/stack/test/test_thread_span_links.cpp Tests reverse invalidation and relinking.
tests/profiling/collector/test_stack_span_links.py Tests context deactivation.
tests/profiling/collector/test_stack_endpoint_labels.py Tests attribution lifecycle scenarios.
tests/profiling/collector/pprof_utils.py Adds profile inspection helpers.
releasenotes/notes/profiling-clear-finished-endpoint-e75147a1799ab41a.yaml Documents the customer-facing fix.

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

@KowalskiThomas KowalskiThomas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Makes sense to me -- one last suggestion but it's really minor.

I do believe this should be tested in staging if it hasn't though; leaving as comment (and not approval) until I have confirmation on that!

@taegyunkim

Copy link
Copy Markdown
Contributor Author

Makes sense to me -- one last suggestion but it's really minor.

I do believe this should be tested in staging if it hasn't though; leaving as comment (and not approval) until I have confirmation on that!

@KowalskiThomas OK I sent it to assistant_api, but if you have better suggestion let me know.

service:assistant_api env:staging version:v130587025-4527f6f is the one for both ebpf and python profiles. I'll wait a few hours to check the results

@KowalskiThomas KowalskiThomas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Staging seems to look good, thanks for validating.

@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit 8d8bc49 into main Aug 13, 2026
484 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the taegyunkim/profiling-clear-finished-endpoint branch August 13, 2026 12:19
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.

3 participants