Repository navigation
fix(profiling): isolate gevent span attribution across lifecycles - #19420
taegyunkim wants to merge 5 commits into
Conversation
Codeowners resolved asResolved from the full PR diff against |
Circular import analysis
|
❌ ErrorsYour PR has failed checks. Please review the issues below and take necessary action before merging. 🚦 1 Pipeline job failed
|
dab384f to
afadd01
Compare
afadd01 to
1153d8b
Compare
ca6945c to
e50fe98
Compare
b47705e to
b7a5e6f
Compare
e50fe98 to
3584711
Compare
b7a5e6f to
971fd10
Compare
3584711 to
8bc4531
Compare
971fd10 to
82b9518
Compare
8bc4531 to
a974497
Compare
82b9518 to
6f4f30f
Compare
3082d9b to
53bded1
Compare
There was a problem hiding this comment.
💡 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".
ab8acda to
52802b4
Compare
563af7a to
2e2299a
Compare
52802b4 to
c4281a1
Compare
2e2299a to
c343ac0
Compare
c4281a1 to
08c344b
Compare
c343ac0 to
5ddab53
Compare
|
@codex review |
There was a problem hiding this comment.
💡 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".
| for greenlet_id in tuple(_tracked_greenlets): | ||
| _untrack_greenlet_by_id(greenlet_id) |
There was a problem hiding this comment.
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))) { |
There was a problem hiding this comment.
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 👍 / 👎.
| // 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); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
df6bb62 to
926aef9
Compare
ef5e83a to
a4974ca
Compare
1c3e1f2 to
46942c0
Compare
7cf747b to
9102269
Compare
9102269 to
eb10d15
Compare
46942c0 to
8acdcaa
Compare
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.
…profiling-logical-span-links
|
Closing along with #19736, which this was stacked on. The work is being redone in smaller PRs. |
Description
JIRA: PROF-16348
Review fixes
This branch has been merged with the latest #19737 head at
dbd926e119and pushed at89c8959e54, carrying the latestorigin/mainchanges through the full stack. The merge also restores thesysimport required by the gevent collector initialization path after main replaced its separate version check.gr_context, not the switch target's current Context. Unset and empty Contexts remain unattributed.unlink_greenlet_span(greenlet_id, expected_span_id)retracts stale publication without erasing a newer reentrant activation.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, andunlink_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:
(GeventGreenlet, greenlet_id)attribution beside each unwound greenlet stack and renders that exact snapshot.Testing
Latest main merge validation
The stack merge commit is SSH-signed.
scripts/run-tests: 54 passed, 1 skipped, covering span-link lifecycle and gevent endpoint attribution.sysimport inStackCollector._init; all seven gevent endpoint regressions passed after the merge fix.scripts/lint fmtpassed for the affected profiler and test files._gevent.py,_span_links.py, andcollector/stack.py.Asyncio naming follow-up validation
Focused asyncio, endpoint-attribution, and span-link lifecycle tests via
scripts/run-tests:--ddtraceon Python 3.13.13.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 checkspassed 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:
scripts/run-tests: 88 passed, 4 skipped.build_standalone.sh -- RelWithDebInfo stack_test: 32 stack tests and 23 wrapper tests passed.scripts/lint checks: passed.scripts/run-benchmarks --listfound no matching suites, so no benchmark results are claimed.The existing testing and staging results below predate this follow-up.
scripts/lint checksscripts/lint profiling-native-checkscripts/run-tests --venv 104eadd -- tests/profiling/collector/test_stack_span_links.py tests/profiling/test_gevent.pyddtrace/internal/datadog/profiling/build_standalone.sh -- RelWithDebInfo stack_testprofile-anyioregression: 1 passedRegressions 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:
Customer-facing release note:
releasenotes/notes/profiling-gevent-span-links-1f27a7e92d4b83c1.yaml.