Repository navigation
fix(profiling): attribute copied-Context worker threads - #21329
taegyunkim wants to merge 13 commits into
Conversation
Dependency direction analysis
|
Codeowners resolved asResolved from the full PR diff against |
BenchmarksBenchmark execution time: 2026-11-09 20:44:26 Comparing candidate commit d7dc513 in PR branch Found 0 performance improvements and 0 performance regressions! Performance is the same for 625 metrics, 9 unstable metrics, 1 flaky benchmarks without significant changes.
|
❌ ErrorsYour PR has failed checks. Please review the issues below and take necessary action before merging. 🚦 2 Pipeline jobs failed
ℹ️ InfoNo other issues found (see more)🧪 All tests passed Useful? React with 👍 / 👎 This comment will be updated automatically if new data arrives.🔗 Commit SHA: d7dc513 | Docs | View more details | Give us feedback! |
…ministic Bind the entry's optional to a local before dereferencing it so bugprone-unchecked-optional-access can see the has_value() check. The contention test relied on two threads overlapping on the mutex, which valgrind's serialized scheduler never produced. Move the try-lock-then-hook logic into run_locked and test it with a mutex that another thread holds until the hook runs.
…finish Move the stack profiler's span link writes to the keyed table, and remove the native pending-link bookkeeping they replace. - publish() writes a unit's key with stack.link, then checks whether the span finished in the meantime. retarget_finished() moves a key whose span finished to the span's unfinished parent under the default context provider's rules, or to no span otherwise. - The span finish listener retargets the keys that hold the finished span, whichever thread finishes it. - On start, the collector opens the links and republishes the span that is already active on the current thread. On stop it closes them first. - context_meta.resolve() and span_info() turn the active item, a span or a propagated Context, into a link entry. inheritance_mode() tells whether the provider follows the default provider's active() rule. - Remove link_span, unlink_span, clear_span and unlink_finished_span from the extension, with the native code behind them.
The sampler can now label asyncio task and greenlet samples with the span linked to that task or greenlet, instead of the span of the thread they ran on. Nothing writes task or greenlet keys yet, and both per-domain switches are off by default, so rendering is unchanged. - LogicalSpanReader reads the domain's switch and birth_watermark() once before Echion unwinds a thread. Each task or greenlet key is looked up after that unit's frames are copied, and a key born after the watermark is ignored, so a new object at a reused address never labels an old one. - StackRenderer pushes span and origin-task labels once it knows whether the sample is a task or greenlet sample. An attributed sample gets only its own span, or none. Every sample keeps the origin-task labels. - set_logical_attribution(domain, enabled) turns attribution on or off for SPAN_LINK_DOMAIN_ASYNCIO_TASK or SPAN_LINK_DOMAIN_GREENLET.
…nt_loop The stack profiler only renders the tasks of a thread's configured loop, which set_event_loop, uvloop.new_event_loop or late attachment record. Loops that run without being set, such as asyncio.Runner(loop_factory=...) or a bare loop.run_until_complete(), were sampled as plain threads. Each native thread record now also has a running-loop slot, holding the plain asyncio loop (BaseEventLoop) whose run_forever runs on the thread. Echion reads effective_loop() and effective_uvloop() at every loop read site, including the choice of the logical attribution domain for a thread: the running loop when one is set, otherwise the configured loop. - Python 3.13+: hooks on BaseEventLoop._run_forever_setup and _run_forever_cleanup set and clear the slot. - Before 3.13: a hook on BaseEventLoop.run_forever does the same, guarded so that nested, closed or already-running calls do not touch the slot. - Late attachment on 3.13+ fills the running slot with an unowned entry and leaves the configured slot alone. Before 3.13, for uvloop, and for loop classes that override run_forever, it keeps the configured slot. It now also sets uvloop mode for a uvloop loop when uvloop support is on. - enter/exit take thread_info_map_lock with run_locked, the try_lock helper span links use, and the bindings pass ReleaseGilOnContention, so they release the GIL only on contention. - Two tests in test_asyncio_import_order.py that start the profiler after the loop was created or started now pass, so their xfail markers are removed.
Write the span each asyncio task runs to the stack profiler's task keys: from the activation listener, from a creation hook on loop.create_task (BaseEventLoop and uvloop), and from the first step of eager tasks. A weakref erases a task's key when the task dies. Per-task attribution in the sampler stays off.
Turn on per-task attribution for asyncio tasks where the profiler installs its task key writers. A sample of an asyncio task now carries the span of that task's own key, or no span, instead of the span that any task on the thread activated last. Remove the strict xfails that #21236 added to the asyncio endpoint label tests. Add end-to-end tests that decode profiles for inherited, eager, finished, OpenTelemetry, uvloop and asyncio.Runner cases. The concurrent-task tests check that every sample of each task carries that task's span or no span, and they fail with per-task attribution off. Some checks only count a task's own samples. Echion, the native stack walker, can render one task's frames under another task in two cases that predate this change: a sample that overlaps the moment a task starts or stops waiting, and uvloop set up through uvloop.install() or a policy before Python 3.11, where it does not find the loop boundary.
Each greenlet that the stack profiler tracks now gets its own span link key, and greenlet samples use only that key, never the span of their thread. - The activation listener writes the current greenlet's key, keyed by gevent.thread.get_ident(greenlet), which is the id the sampler reads. It is the same stack.link call that writes the thread and asyncio task keys, so a greenlet that runs an asyncio loop gets the span of the task that activates it. - _natively_tracked records the greenlets that stack.track_greenlet accepted. Only these get keys. A weak reference untracks a greenlet when it is collected, and untracking always clears its key. - The greenlet tracer seeds a greenlet once per profiler lifecycle with the span it inherited in its own Context. This labels greenlets that ran before profiling started, that were suspended across a stop and a start, and, in a fork child, the suspended greenlets of the forking thread. - Spawning a greenlet erases any key left at its address. - The gevent support turns the Greenlet attribution switch on once it tracks greenlets. Unpatching gevent turns it off first.
asyncio.to_thread and anyio.to_thread.run_sync run a function on a worker thread in a copy of the caller's Context. The worker inherits the caller's active span, but entering that copy activates no span, so the worker's thread key never got it. AnyIO worker samples had no span. asyncio.to_thread worker samples had none either, or, with the futures integration, a label that did not move to the parent when the span finished. - run_in_worker writes the inherited span to the worker's thread key before the function runs, and clears the key when it returns or raises. The function runs exactly once, and profiler errors never reach it. - install() adds import hooks that wrap asyncio.threads.to_thread and anyio.to_thread.run_sync. The collector calls it on start, before the keyed span links open, and a module whose hook failed is retried on the next start. - A new profile-anyio test suite covers AnyIO on the asyncio and trio backends.
0262d4a to
a5e73bb
Compare
…copied-context-workers # Conflicts: # ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt # ddtrace/profiling/collector/stack.py
Main removed opentracing from the default test dependencies, which changes every environment's lock hash. Regenerate the profile-anyio locks under their new hashes. Each lock differs from the old one only by the removed opentracing pin.
|
Closing in favor of smaller PRs, starting with #21653. The copied-Context worker change will come back as its own PR. |
Description
This draft carries a stack of commits, so CI runs on all of them together. Review it commit by commit. Each commit is one change and builds on the ones before it. The first three commits are #21297.
Supersedes #19736, #19420 and #19737.
Problem. The stack profiler labels each sample with a span: span id, local root span id and trace endpoint. Today the label comes from the thread: the span that was last activated on that thread. That is wrong for code where one thread runs many units of work, or where a thread runs on behalf of another one:
asyncio.to_threadoranyio.to_thread.run_syncrun in a copy of the caller'scontextvars.Context. Entering that copy activates no span, so their samples have no span, or one that never moves to the parent span when the span finishes.Approach. The native span link table is keyed by execution unit: a thread, an asyncio task or a greenlet. A unit's entry is its key. The tracer's activation listener and a few creation hooks write keys. The sampler labels a sample with the key of the unit it ran, instead of the thread's.
refactor(profiling): key native span links by execution unit(+2 follow-ups)feat(profiling): expose keyed span link bindingsfix(profiling): publish span links with revalidation and retarget on finishtrace.span_discard), keys that point at it move to its unfinished parent.feat(profiling): snapshot per-unit span attribution in the samplerfix(profiling): render tasks of asyncio loops started without set_event_loopasyncio.Runner(loop_factory=...)or a barerun_until_completenow render as tasks.feat(profiling): track asyncio task span linksfix(profiling): isolate asyncio task span attributionfix(profiling): isolate gevent greenlet span attributionfix(profiling): attribute copied-Context worker threadsasyncio.to_threadandanyio.to_thread.run_sync, so the worker's thread key gets the caller's span while the function runs.Testing
stack_test(C++ unit tests for the table, the sampler snapshot and the running-loop slots) passes from a fresh build.test_stack_asyncio_task_attribution.py,test_stack_asyncio_task_span_links.py,test_stack_asyncio_endpoint_labels.py(the strict xfails from test(profiling): add asyncio task span attribution tests #21236 are removed),test_asyncio_running_loop.pytest_stack_gevent_span_links.py, plus profiler cases intests/opentelemetry/test_context.pytest_stack_asyncio_to_thread_span_links.py, andtest_stack_anyio_to_thread_span_links.pyin a newprofile-anyiosuitetests/profilingsuite on Python 3.9, 3.12 and 3.14, the gevent venv (3.12) and both uvloop venvs (3.9, 3.13), plusprofile-anyioon 3.9 and 3.15. Python 3.10, 3.11 and 3.15 ran the changed test files only.Risks
asyncio.Task(...)directlyBaseEventLoopsubclasses nor uvloopactive()uvloop.install()or a policy on Python 3.9 or 3.10, beforeasyncio.run(). Both happen on main too. With this change, those frames carry the other task's span instead of the thread's.asyncio.to_threadandanyio.to_thread.run_syncgain arun_in_workerframe. Eager asyncio tasks gain a wrapper frame.Additional Notes
profile-anyiolock files were generated on an aarch64 host, not with the canonical command. Runscripts/test-requirements lock profile-anyioon an x86-64 host before this leaves draft.