Skip to content

fix(profiling): isolate gevent span attribution across lifecycles - #19420

Closed
taegyunkim wants to merge 5 commits into
taegyunkim/profiling-anyio-span-linksfrom
taegyunkim/profiling-logical-span-links
Closed

taegyunkim wants to merge 5 commits into
taegyunkim/profiling-anyio-span-linksfrom
taegyunkim/profiling-logical-span-links

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

JIRA: PROF-16348

Review fixes

This branch has been merged with the latest #19737 head at dbd926e119 and pushed at 89c8959e54, carrying the latest origin/main changes through the full stack. The merge also restores the sys import required by the gevent collector initialization path after main replaced its separate version check.

  • Lazy origin discovery reads the origin greenlet's saved gr_context, not the switch target's current Context. Unset and empty Contexts remain unattributed.
  • Greenlet activation and both seeding helpers validate source lifetime and profiler generation. Conditional native unlink_greenlet_span(greenlet_id, expected_span_id) retracts stale publication without erasing a newer reentrant activation.
  • Regressions cover context ownership, finish/stop/restart during lookup and publication, and real pprof output after concurrent finish, including preservation of newer attribution.

Stacked on #19737.

Echion already unwinds each gevent greenlet independently, but span attribution previously used only the physical thread ID. Concurrent greenlets sharing that thread could therefore borrow another greenlet's span and endpoint.

This PR extends the private native span-link storage introduced in #19736 with a greenlet domain and explicit greenlet operations such as link_greenlet_span, get_active_span_from_greenlet_id, and unlink_greenlet_span. The common domain-qualified storage remains an implementation detail. No generic logical-span API or exported domain constants are exposed to Python.

The gevent integration then:

  • Registers the current tracked greenlet as the greenlet span-link source while gevent profiling hooks are active.
  • Seeds tracked greenlets from the profiler's configured tracer or their inherited profiler context.
  • Clears native mappings when greenlets are untracked or gevent profiling is unpatched.
  • Snapshots (GeventGreenlet, greenlet_id) attribution beside each unwound greenlet stack and renders that exact snapshot.
  • Preserves explicit unattributed-greenlet state instead of falling back to an unrelated physical-thread span.
  • Gives an active asyncio task precedence when asyncio runs over gevent, then falls back to greenlet and physical-thread attribution.
  • Rebuilds tracking across profiler restarts and forks while republishing the surviving active span.
  • Preserves another installed greenlet tracer when the profiler patches and unpatches gevent.

Testing

Latest main merge validation

The stack merge commit is SSH-signed.

  • Python 3.11 profiling environment with gevent via scripts/run-tests: 54 passed, 1 skipped, covering span-link lifecycle and gevent endpoint attribution.
  • The first post-merge run exposed the missing sys import in StackCollector._init; all seven gevent endpoint regressions passed after the merge fix.
  • scripts/lint fmt passed for the affected profiler and test files.
  • Targeted typing passed for _gevent.py, _span_links.py, and collector/stack.py.

Asyncio naming follow-up validation

Focused asyncio, endpoint-attribution, and span-link lifecycle tests via scripts/run-tests:

  • Python 3.12.13 with uvloop: 41 passed, 2 skipped.
  • Python 3.13.13: 40 passed, 3 skipped.
  • Python 3.14.5: 40 passed, 3 skipped.
  • Both naming cases also passed with --ddtrace on Python 3.13.13.
  • Removing coroutine-name preservation temporarily made both new naming cases fail, confirming the regression check remains effective.
  • The asyncio span-link test file passed on the restacked gevent tip: 13 passed.
  • scripts/lint checks: passed.

These are local validation results. New remote CI results are pending after the stack push.

Native CI follow-up validation

The allocation-failure test was rebuilt and run through CTest on Linux with Clang 19.1.7 in three configurations: ASan/LSan/UBSan, Valgrind 3.24.0, and ordinary RelWithDebInfo. All three passed on both #19736 and the restacked gevent tip. Valgrind reported zero errors and no leaks. scripts/lint checks passed on both branches. This validates the failing test locally, not the entire new remote CI pipeline; CI is rerunning after the push.

Restacked validation

On Python 3.12.13, with a freshly rebuilt native extension:

  • Focused profiling suite via scripts/run-tests: 88 passed, 4 skipped.
  • AnyIO regression on the top of the stack: 1 passed.
  • Native build_standalone.sh -- RelWithDebInfo stack_test: 32 stack tests and 23 wrapper tests passed.
  • scripts/lint checks: passed.
  • The new regression selection produced 14 failures with the pre-fix Python code restored; the final focused run passed.
  • scripts/run-benchmarks --list found no matching suites, so no benchmark results are claimed.

The existing testing and staging results below predate this follow-up.

  • scripts/lint checks
  • scripts/lint profiling-native-check
  • scripts/run-tests --venv 104eadd -- tests/profiling/collector/test_stack_span_links.py tests/profiling/test_gevent.py
    • Python 3.12 profiling suite with gevent: 461 passed, 18 skipped, 2 xpassed
  • ddtrace/internal/datadog/profiling/build_standalone.sh -- RelWithDebInfo stack_test
    • 30 native tests passed, including greenlet lifecycle and runtime-key isolation
  • Descendant Python 3.12 profile-anyio regression: 1 passed
  • Benchmark discovery found no matching benchmark suites

Regressions cover concurrent endpoint isolation, finished inherited spans, profiler restart, immediate post-fork work, lazy origin discovery, configured-tracer isolation, asyncio-over-gevent precedence, physical-thread fallback, provider registration, and native cleanup during unpatch.

Risks

Span activation and finish maintain additional native links only while the greenlet provider is active. The map is mutex-protected, and provider failures fall back from asyncio task to greenlet to physical-thread routing. Renderer fallback changes only when the sampled stack is known to belong to a tracked greenlet.

Fork and restart handling must preserve the active span while dropping inherited mappings. Standalone and real gevent-fork regressions cover this lifecycle, and the full gevent profiling suite passes.

Additional Notes

Review this stack in order:

Order PR Purpose
1 #19736 Centralize span-link lifecycle handling and attribute asyncio task samples
2 #19737 Propagate attribution into AnyIO worker threads
3 #19420 Attribute gevent samples and protect greenlet span-link lifecycle

Customer-facing release note: releasenotes/notes/profiling-gevent-span-links-1f27a7e92d4b83c1.yaml.

@taegyunkim taegyunkim added the changelog/no-changelog A changelog entry is not required for this PR. label Jul 30, 2026
@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 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/docs/Standalone.md                   @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/stacks.h         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/sampler.hpp            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/span_links.hpp         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/stack_renderer.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/span_links.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_loop_registration.cpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_span_links.cpp       @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_span_links_alloc.cpp  @DataDog/profiling-python
ddtrace/profiling/_asyncio.py                                           @DataDog/profiling-python
ddtrace/profiling/_span_links.py                                        @DataDog/profiling-python
ddtrace/profiling/collector/stack.py                                    @DataDog/profiling-python
releasenotes/notes/profiling-asyncio-endpoint-isolation-b47f8d86e916cf43.yaml  @DataDog/apm-python
tests/profiling/collector/test_asyncio_span_links.py                    @DataDog/profiling-python
tests/profiling/collector/test_stack_asyncio_endpoint_labels.py         @DataDog/profiling-python
tests/profiling/collector/test_stack_span_links.py                      @DataDog/profiling-python
tests/profiling/collector/test_stack_threadpool.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 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

@datadog-prod-us1-3

datadog-prod-us1-3 Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 1 Pipeline job failed

DataDog/apm-reliability/dd-trace-py | build macos amd64: [3.12 3.13 3.14] — 🔄 Retry may pass, looks flaky

View more details · View in GitLab

⚠️ Warnings

❄️ 1 New flaky test detected

↳ test_stack_does_not_resurrect_span_finished_during_greenlet_publication[1][py3.13] from test_stack_gevent_endpoint_labels.py

View in Flaky Test Management

ℹ️ Info

No other issues found (see more)

🧪 All tests passed

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 89c8959 | Docs | View more details | Give us feedback!

@taegyunkim taegyunkim added the Profiling Continous Profling label Jul 30, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from dab384f to afadd01 Compare August 5, 2026 17:01
@taegyunkim taegyunkim added changelog/no-changelog A changelog entry is not required for this PR. and removed changelog/no-changelog A changelog entry is not required for this PR. labels Aug 5, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from afadd01 to 1153d8b Compare August 5, 2026 17:13
@taegyunkim taegyunkim changed the title feat(profiling): add logical span link infrastructure refactor(profiling): add logical span link infrastructure Aug 5, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch 2 times, most recently from ca6945c to e50fe98 Compare August 5, 2026 17:56
@taegyunkim taegyunkim changed the title refactor(profiling): add logical span link infrastructure refactor(profiling): add common logical span link helpers Aug 5, 2026
@taegyunkim
taegyunkim changed the base branch from main to taegyunkim/profiling-clear-finished-endpoint August 5, 2026 17:57
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from b47705e to b7a5e6f Compare August 5, 2026 20:22
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from e50fe98 to 3584711 Compare August 5, 2026 20:22
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from b7a5e6f to 971fd10 Compare August 5, 2026 20:48
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 3584711 to 8bc4531 Compare August 5, 2026 20:48
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 971fd10 to 82b9518 Compare August 5, 2026 20:55
@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-clear-finished-endpoint branch from 82b9518 to 6f4f30f Compare August 6, 2026 00:32
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch 3 times, most recently from 3082d9b to 53bded1 Compare August 6, 2026 18:30
@taegyunkim
taegyunkim marked this pull request as ready for review August 20, 2026 03:41

@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: 563af7ac53

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

Comment thread ddtrace/profiling/_gevent.py Resolved
Comment thread ddtrace/profiling/_gevent.py Resolved
Comment thread ddtrace/profiling/_gevent.py Resolved
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from ab8acda to 52802b4 Compare August 20, 2026 15:44
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 563af7a to 2e2299a Compare August 20, 2026 15:44
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from 52802b4 to c4281a1 Compare August 20, 2026 15:59
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 2e2299a to c343ac0 Compare August 20, 2026 15:59
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from c4281a1 to 08c344b Compare August 20, 2026 16:01
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from c343ac0 to 5ddab53 Compare August 20, 2026 16:01
@taegyunkim

Copy link
Copy Markdown
Contributor Author

@codex review

@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: 24aafa174a

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

Comment on lines +54 to +55
for greenlet_id in tuple(_tracked_greenlets):
_untrack_greenlet_by_id(greenlet_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve suspended greenlets when invalidating restart links

When a tracked greenlet remains blocked across Profiler.stop()/start(), this new invalidation loop removes its native frame record, and only the currently running greenlet is re-registered below. Because lazy discovery happens only when that suspended greenlet participates in another switch, it disappears entirely from wall-time profiles for the potentially long interval before it resumes; the added restart regression resumes the greenlet immediately and therefore misses this loss. Invalidate its span link/Python routing state without removing the surviving native stack entry, or otherwise retain enough object state to re-register every live greenlet.

Useful? React with 👍 / 👎.

if (!PyArg_ParseTuple(args, "K", &greenlet_id))
return nullptr;

if (Sampler::get().is_greenlet_tracked(static_cast<uintptr_t>(greenlet_id))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Release the GIL while checking native greenlet tracking

On every span activation under gevent, _current_greenlet_span_target() calls this function while holding the GIL, but Sampler::is_greenlet_tracked() waits on greenlet_info_map_lock. The sampling thread holds that mutex while walking every tracked greenlet and constructing parent chains, so applications with many greenlets can stall all Python execution on the tracing hot path until the snapshot completes; the adjacent track, untrack, link, and switch wrappers all release the GIL around the same mutex for this reason. Store the result while the GIL is released, then construct the Python boolean afterward.

AGENTS.md reference: AGENTS.md:L16-L16

Useful? React with 👍 / 👎.

Comment on lines +784 to +787
// Snapshot attribution with the frame pointers so deferred rendering cannot observe a newer span activation.
stack_info->span_context.use_task_attribution = true;
stack_info->span_context.span = Datadog::SpanLinks::get_instance().get_active_span_from_logical_id(
Datadog::SpanLinkDomain::GeventGreenlet, snap.greenlet_id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Snapshot greenlet frames and attribution atomically

The frame snapshots are copied while holding greenlet_info_map_lock, but this span lookup occurs only after that lock has been released. The application can therefore resume a suspended greenlet and activate a different span between those operations, causing the sampler to render the old suspended stack with the newer span and endpoint; rapid greenlet switching can thus recreate the cross-request misattribution this change is intended to prevent. Capture the logical span into GreenletSnapshot while the corresponding frame and parent chain are still protected by the greenlet lock.

Useful? React with 👍 / 👎.

Comment thread ddtrace/profiling/_gevent.py Outdated
Comment on lines +63 to +66
greenlet_id = t.cast(int, thread.get_ident(gevent.getcurrent()))
if not stack.is_greenlet_tracked(greenlet_id):
return None
return _span_links.LogicalSpanTarget(_span_links.SpanLinkDomain.GEVENT_GREENLET, greenlet_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require active switch tracing before routing to a greenlet

Native map membership does not guarantee that the current greenlet can be rendered: patch() installs greenlet_tracer only in the native thread that performs the patch (the repository's ensure_greenlet_context_switch() likewise explicitly installs tracing in the current native thread). If another real OS thread runs its own gevent hub, the global spawn wrappers register its greenlets with FRAME_NOT_SET, but no profiler switch callback updates their frames. This check then routes that thread's span activations to logical links even though unwind_greenlets() skips those entries and falls back to the physical stack, whose link was not updated, so trace and endpoint labels are lost. Install the profiler switch tracer in each gevent-running native thread or make this provider verify that the current entry has a renderable frame.

Useful? React with 👍 / 👎.

@emmettbutler
emmettbutler marked this pull request as draft August 26, 2026 15:20

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

Marked as draft because the base branch isn't main. Please mark as ready and re-request review when this is ready to merge to main.

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from df6bb62 to 926aef9 Compare September 15, 2026 20:57
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from ef5e83a to a4974ca Compare September 15, 2026 21:11
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from 1c3e1f2 to 46942c0 Compare September 16, 2026 16:20
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 7cf747b to 9102269 Compare September 16, 2026 16:20
@taegyunkim taegyunkim changed the title fix(profiling): isolate gevent span links fix(profiling): attribute gevent greenlet samples to inherited spans Sep 16, 2026
@taegyunkim taegyunkim changed the title fix(profiling): attribute gevent greenlet samples to inherited spans fix(profiling): isolate gevent span attribution across lifecycles Sep 18, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 9102269 to eb10d15 Compare September 18, 2026 15:09
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from 46942c0 to 8acdcaa Compare September 18, 2026 15:09
Read lazy origin attribution from the origin greenlet Context rather than the switch target. Treat unset Contexts as empty.

Validate greenlet publication across finish and lifecycle transitions, using conditional native unlinking to preserve newer reentrant activations. Cover the races with unit, native, and pprof regressions.
@taegyunkim

Copy link
Copy Markdown
Contributor Author

Closing along with #19736, which this was stacked on. The work is being redone in smaller PRs.

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.

4 participants