-
Notifications
You must be signed in to change notification settings - Fork 514
feat(profiling): add GC observability collector #18566
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
vlad-scherbich
wants to merge
8
commits into
main
Choose a base branch
from
vlad/profiling-gc-collector
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
895e9e6
feat(profiling): add GC observability collector
vlad-scherbich b7a169b
fix(profiling/tests): fix GC test flakiness from collector module rei…
vlad-scherbich 3b62367
Guard _explicit_count with a lock for thread safety
vlad-scherbich 3d9ccc2
Use line=0 for pseudo-frames in push_frame calls
vlad-scherbich c76f61b
Guard debug-only GC introspection behind LOG level check
vlad-scherbich 843e2ba
Fix GC config help text to match actual exported data
vlad-scherbich fbbc19f
Patch ddup in unit tests that start GCCollector
vlad-scherbich dd1b04a
Add GC collector test coverage for alloc, snapshot, generation names,…
vlad-scherbich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import gc | ||
| import logging | ||
| import threading | ||
| import time | ||
| from typing import Callable | ||
|
|
||
| from ddtrace.internal.datadog.profiling import ddup | ||
| from ddtrace.profiling import collector | ||
|
|
||
|
|
||
| LOG = logging.getLogger(__name__) | ||
|
|
||
| _GEN_NAMES: tuple[str, ...] = ( | ||
| "gc.collect[gen=0]", | ||
| "gc.collect[gen=1]", | ||
| "gc.collect[gen=2]", | ||
| ) | ||
|
|
||
|
|
||
| class GCCollector(collector.Collector): | ||
| """Collect GC pause durations, collection counts, and configuration state. | ||
|
|
||
| Hooks gc.callbacks for per-collection events and emits a snapshot sample | ||
| once per profile flush interval with cumulative counts and config state. | ||
|
|
||
| Data emitted: | ||
| - Wall time samples (push_walltime) attributed to synthetic gc.collect[gen=N] | ||
| frames — appear in the Wall Time profile view. | ||
| - Alloc samples (push_alloc) with collected-object count — appear in the | ||
| Alloc profile view under the same frames. | ||
| - A gc.config snapshot sample per flush carrying explicit gc.collect() call | ||
| count in the sample count field. | ||
| """ | ||
|
|
||
| def _start_service(self) -> None: | ||
| self._start_ns: dict[int, int] = {} | ||
| self._explicit_count: int = 0 | ||
| self._count_lock = threading.Lock() | ||
| self._orig_collect: Callable[..., int] = gc.collect | ||
| gc.collect = self._patched_collect | ||
| gc.callbacks.append(self._on_gc) | ||
| LOG.debug("GCCollector started") | ||
|
|
||
| def _stop_service(self) -> None: | ||
| try: | ||
| gc.callbacks.remove(self._on_gc) | ||
| except ValueError: | ||
| pass | ||
| gc.collect = self._orig_collect | ||
| LOG.debug("GCCollector stopped") | ||
|
|
||
| def _patched_collect(self, generation: int = 2) -> int: | ||
| with self._count_lock: | ||
| self._explicit_count += 1 | ||
| return self._orig_collect(generation) | ||
|
Comment on lines
+54
to
+57
|
||
|
|
||
|
Comment on lines
+54
to
+58
|
||
| def _on_gc(self, phase: str, info: dict[str, int]) -> None: | ||
| gen = info.get("generation", 0) | ||
| if phase == "start": | ||
| self._start_ns[gen] = time.monotonic_ns() | ||
| elif phase == "stop": | ||
| start = self._start_ns.pop(gen, None) | ||
| if start is None: | ||
| return | ||
| pause_ns = time.monotonic_ns() - start | ||
| frame_name = _GEN_NAMES[gen] if gen < len(_GEN_NAMES) else "gc.collect" | ||
|
|
||
| handle = ddup.SampleHandle() | ||
| handle.push_walltime(pause_ns, 1) | ||
| handle.push_frame(frame_name, "gc", 0, 0) | ||
| handle.push_monotonic_ns(time.monotonic_ns()) | ||
|
Copilot marked this conversation as resolved.
|
||
| handle.flush_sample() | ||
|
|
||
| collected = info.get("collected", 0) | ||
| if collected > 0: | ||
| handle2 = ddup.SampleHandle() | ||
| handle2.push_alloc(collected, 1) | ||
| handle2.push_frame(frame_name, "gc", 0, 0) | ||
| handle2.push_monotonic_ns(time.monotonic_ns()) | ||
| handle2.flush_sample() | ||
|
|
||
| def snapshot(self) -> None: # type: ignore[override] | ||
| with self._count_lock: | ||
| explicit = self._explicit_count | ||
| self._explicit_count = 0 | ||
|
|
||
| handle = ddup.SampleHandle() | ||
| # Use count field to carry explicit gc.collect() tally for this interval. | ||
| # A zero walltime with count > 0 is the established pattern for pure-count | ||
| # samples (same as lock release-time samples with zero duration). | ||
| handle.push_walltime(0, explicit) | ||
| handle.push_frame("gc.config", "gc", 0, 0) | ||
| handle.push_monotonic_ns(time.monotonic_ns()) | ||
| handle.flush_sample() | ||
|
|
||
| if LOG.isEnabledFor(logging.DEBUG): | ||
| thresholds = gc.get_threshold() | ||
| enabled = gc.isenabled() | ||
| freeze_count = gc.get_freeze_count() if hasattr(gc, "get_freeze_count") else 0 | ||
| stats = gc.get_stats() | ||
| total_collections = sum(s.get("collections", 0) for s in stats) | ||
| LOG.debug( | ||
| "GCCollector snapshot: enabled=%s thresholds=%s freeze=%d total_collections=%d explicit_collect=%d", | ||
| enabled, | ||
| thresholds, | ||
| freeze_count, | ||
| total_collections, | ||
| explicit, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When another library or test replaces
gc.collectwhile the profiler is running, stopping this collector unconditionally restores the function captured at profiler startup and silently discards that later patch. Because this collector is enabled by default and mutates a process-wide stdlib function, this can break code that wrapsgc.collectafter profiling starts; only restore whengc.collectis still this collector's wrapper, or otherwise chain/coordinate the wrapper safely.Useful? React with 👍 / 👎.