From dc72f2f8b0d4a4e31729e34c7295b5d5c47c78c6 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Mon, 30 Nov 2026 10:03:39 +0100 Subject: [PATCH 1/6] ref(metrics): Drop negatively sampled metrics immediately --- sentry_sdk/_lock_free_metrics_batcher.py | 57 +++++++++++++++++------- sentry_sdk/client.py | 9 ++++ sentry_sdk/metrics.py | 8 +++- tests/test_metrics.py | 23 ++++++++++ 4 files changed, 81 insertions(+), 16 deletions(-) diff --git a/sentry_sdk/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index 9287d72df7..ae37345ed3 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -22,11 +22,13 @@ class _Reservoir: - __slots__ = ("kept", "seen") + __slots__ = ("kept", "seen", "index") def __init__(self) -> None: self.kept: "list[Metric]" = [] self.seen = 0 + # The slot admit picked for the metric currently on its way to add. + self.index: "Optional[int]" = None class _ThreadState: @@ -53,6 +55,10 @@ def __init__(self) -> None: self.number_kept = 0 +class _Admitted(threading.local): + window: "Optional[_Window]" = None + + class LockFreeMetricsBatcher(Batcher["Metric"]): MAX_UNSAMPLED_BEFORE_FLUSH = 1000 MAX_UNSAMPLED_BEFORE_DROP = 10_000 @@ -78,6 +84,7 @@ def __init__( self._queue: "deque[Metric]" = deque() self._window = _Window() + self._admitted = _Admitted() self._retired: "deque[_Window]" = deque() # Holds the claim of the one thread that gets to start the flusher. self._flusher_claim: "dict[str, object]" = {} @@ -86,6 +93,7 @@ def _reset_thread_state(self) -> None: super()._reset_thread_state() self._queue = deque() self._window = _Window() + self._admitted = _Admitted() self._retired = deque() self._flusher_claim = {} @@ -129,11 +137,6 @@ def add(self, item: "Metric") -> None: if not self._ensure_thread(): return None - window = self._window - if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME: - self._retire_window(window) - window = self._window - limit = self._limits.get(item["name"]) if limit is None: if len(self._queue) >= self.MAX_UNSAMPLED_BEFORE_DROP: @@ -150,27 +153,50 @@ def add(self, item: "Metric") -> None: self._flush_event.set() return - self._add_to_window(item, window, limit) + window = self._admitted.window + if window is None: + return + + reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]] + if ( + len(reservoir.kept) < limit + and window.number_kept < self.MAX_KEPT_PER_WINDOW + ): + window.number_kept += 1 + reservoir.kept.append(item) + elif reservoir.index is not None: + reservoir.kept[reservoir.index] = item + reservoir.index = None + + if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME: + self._retire_window(window) finally: self._active.flag = False - def _add_to_window(self, item: "Metric", window: "_Window", limit: int) -> None: - state = window.threads[threading.get_ident()] - reservoir = state.reservoirs[item["name"]] + def admit(self, name: str) -> bool: + """ + Count a captured metric and decide whether window sampling keeps it. + """ + limit = self._limits.get(name) + if limit is None: + return True + + window = self._window + self._admitted.window = window + reservoir = window.threads[threading.get_ident()].reservoirs[name] reservoir.seen += 1 if ( len(reservoir.kept) < limit and window.number_kept < self.MAX_KEPT_PER_WINDOW ): - window.number_kept += 1 - reservoir.kept.append(item) - return + return True index = random.randrange(reservoir.seen) if index >= len(reservoir.kept): - return + return False - reservoir.kept[index] = item + reservoir.index = index + return True def _retire_window(self, window: "_Window") -> None: claim = object() @@ -236,6 +262,7 @@ def _harvest(self, window: "_Window", items: "list[Metric]") -> int: for state in window.threads.copy().values(): for name, reservoir in state.reservoirs.copy().items(): by_name.setdefault(name, []).append(reservoir) + window.threads.clear() sampled_out = 0 for name, reservoirs in by_name.items(): diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 3960ffc1e8..43bb865e82 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -862,6 +862,7 @@ def _capture_telemetry( scope.apply_to_telemetry(telemetry) before_send = None + metric_name = None if ty == "log": before_send = get_before_send_log(self.options) @@ -870,6 +871,8 @@ def _capture_telemetry( elif ty == "metric": before_send = get_before_send_metric(self.options) serialized = telemetry + if self.options["_experiments"].get("metrics_window_sampling"): + metric_name = telemetry["name"] # type: ignore[index, typeddict-item] elif ty == "span": before_send = get_before_send_span(self.options) @@ -891,6 +894,12 @@ def _capture_telemetry( if serialized is None: self._record_lost_telemetry("before_send", ty, telemetry) # type: ignore[arg-type] return + if metric_name is not None and serialized.get("name") != metric_name: + logger.debug( + "[Metrics] Changing the metric name in before_send_metric is not supported when metrics_window_sampling is enabled. Keeping the original name %s.", + metric_name, + ) + serialized["name"] = metric_name # type: ignore[typeddict-unknown-key] elif ty == "span" and isinstance(telemetry, Span): # Reset the span to its original value before we attempted diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index 27b7468c0d..9c1b530e15 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Any, Optional import sentry_sdk +from sentry_sdk._lock_free_metrics_batcher import LockFreeMetricsBatcher from sentry_sdk.utils import format_attribute if TYPE_CHECKING: @@ -15,6 +16,11 @@ def _capture_metric( unit: "Optional[str]" = None, attributes: "Optional[Attributes]" = None, ) -> None: + scope = sentry_sdk.get_current_scope() + batcher = scope.get_client().metrics_batcher + if isinstance(batcher, LockFreeMetricsBatcher) and not batcher.admit(name): + return + attrs: "Attributes" = {} if attributes: @@ -32,7 +38,7 @@ def _capture_metric( "attributes": attrs, } - sentry_sdk.get_current_scope()._capture_metric(metric) + scope._capture_metric(metric) def count( diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 865e40f572..c4236327f0 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -287,6 +287,29 @@ def _before_metric(record, hint): assert item.payload.json["items"][0]["name"] == "test.drop" +def test_metrics_before_send_unsupported_edit(sentry_init, capture_items): + def _before_metric(record, hint): + record["name"] = "test.renamed" + return record + + sentry_init( + before_send_metric=_before_metric, + _experiments={"metrics_window_sampling": {"test.original": 2}}, + ) + items = capture_items("trace_metric") + + sentry_sdk.metrics.count("test.original", 1) + + get_client().flush() + + metrics = [item.payload for item in items] + + assert len(metrics) == 1 + (metric,) = metrics + + assert metric["name"] == "test.original" + + @pytest.mark.parametrize("window_sampling", [None, {"test.sampled": 2}]) def test_transport_format(sentry_init, window_sampling, capture_envelopes): sentry_init( From 6601bf08ece5a95b487e13e68de94fb21a192ce3 Mon Sep 17 00:00:00 2001 From: alexander-alderman-webb <224035503+alexander-alderman-webb@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:20:38 +0000 Subject: [PATCH 2/6] release: 3.1.0b1 --- CHANGELOG.md | 15 +++++++++++++++ docs/conf.py | 2 +- sentry_sdk/consts.py | 2 +- setup.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9abdd479f4..296e8e7c35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 3.1.0b1 + +### New Features ✨ + +- Add per-metric windows to lock free metrics batcher by @alexander-alderman-webb with @sentry-release-bot in [#8327](https://github.com/getsentry/sentry-python/pull/8327) +- Add basic lock-free metrics batcher by @alexander-alderman-webb and @claude in [#8326](https://github.com/getsentry/sentry-python/pull/8326) + +### Internal Changes 🔧 + +- (deps) Lock file maintenance by @renovate in [#8421](https://github.com/getsentry/sentry-python/pull/8421) +- (mcp) Remove unused \_extract_tool_result_content helper by @sentry-junior in [#8422](https://github.com/getsentry/sentry-python/pull/8422) +- (metrics) Drop negatively sampled metrics immediately by @alexander-alderman-webb in [#8425](https://github.com/getsentry/sentry-python/pull/8425) +- Update contributing guidelines by @sentrivana in [#8424](https://github.com/getsentry/sentry-python/pull/8424) +- Move locks into batcher subclasses by @alexander-alderman-webb in [#8325](https://github.com/getsentry/sentry-python/pull/8325) + ## 3.0.2 ### Bug Fixes 🐛 diff --git a/docs/conf.py b/docs/conf.py index fbaf1f7982..3ebef6f09e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,7 +17,7 @@ copyright = "2019-{}, Sentry Team and Contributors".format(datetime.now().year) author = "Sentry Team and Contributors" -release = "3.0.1b2" +release = "3.1.0b1" version = ".".join(release.split(".")[:2]) # The short X.Y version. diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 1006c44777..9722fba427 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -2066,4 +2066,4 @@ def _get_default_options() -> "dict[str, Any]": del _get_default_options -VERSION = "3.0.1b2" +VERSION = "3.1.0b1" diff --git a/setup.py b/setup.py index 18ee209715..8000f1aefb 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ def get_file_text(file_name): setup( name="sentry-sdk", - version="3.0.1b2", + version="3.1.0b1", author="Sentry Team and Contributors", author_email="hello@sentry.io", url="https://github.com/getsentry/sentry-python", From dadaef76ade74ac3844d887ecb4fc46a8a3dc121 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Mon, 30 Nov 2026 14:23:11 +0100 Subject: [PATCH 3/6] Update CHANGELOG.md --- CHANGELOG.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 296e8e7c35..4a348ad25f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,21 +30,6 @@ - (deps) Update getsentry/craft action to v3.14.1 by @renovate in [#8398](https://github.com/getsentry/sentry-python/pull/8398) - (dev) Replace pre-commit with prek by @joshuarli in [#8354](https://github.com/getsentry/sentry-python/pull/8354) -## 3.0.1b2 - -### New Features ✨ - -- Add per-metric windows to lock free metrics batcher by @alexander-alderman-webb with @sentry-release-bot in [#8327](https://github.com/getsentry/sentry-python/pull/8327) -- Add basic lock-free metrics batcher by @alexander-alderman-webb and @claude in [#8326](https://github.com/getsentry/sentry-python/pull/8326) - -### Internal Changes 🔧 - -- Move locks into batcher subclasses by @alexander-alderman-webb in [#8325](https://github.com/getsentry/sentry-python/pull/8325) - -## 3.0.1b1 - -- No documented changes. - ## 3.0.1 ### New Features ✨ From 8661b78deca1784b4499b61a766fbe96c9488dda Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Tue, 1 Dec 2026 10:56:04 +0100 Subject: [PATCH 4/6] avoid re-entrancy problems --- sentry_sdk/_lock_free_metrics_batcher.py | 43 +++++++++++++----------- sentry_sdk/client.py | 25 +++++++++++--- sentry_sdk/metrics.py | 9 +++-- sentry_sdk/scope.py | 7 ++-- 4 files changed, 55 insertions(+), 29 deletions(-) diff --git a/sentry_sdk/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index ca2280b093..6850b108ce 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -22,13 +22,11 @@ class _Reservoir: - __slots__ = ("kept", "seen", "index") + __slots__ = ("kept", "seen") def __init__(self) -> None: self.kept: "list[Metric]" = [] self.seen = 0 - # The slot admit picked for the metric currently on its way to add. - self.index: "Optional[int]" = None class _ThreadState: @@ -55,8 +53,14 @@ def __init__(self) -> None: self.number_kept = 0 -class _Admitted(threading.local): - window: "Optional[_Window]" = None +class _Admission: + """Where admit decided to keep a metric, for add to put it there.""" + + __slots__ = ("window", "index") + + def __init__(self, window: "_Window", index: "Optional[int]") -> None: + self.window = window + self.index = index class LockFreeMetricsBatcher(Batcher["Metric"]): @@ -84,7 +88,6 @@ def __init__( self._queue: "deque[Metric]" = deque() self._window = _Window() - self._admitted = _Admitted() self._retired: "deque[_Window]" = deque() # Holds the claim of the one thread that gets to start the flusher. self._flusher_claim: "dict[str, object]" = {} @@ -93,7 +96,6 @@ def _reset_thread_state(self) -> None: super()._reset_thread_state() self._queue = deque() self._window = _Window() - self._admitted = _Admitted() self._retired = deque() self._flusher_claim = {} @@ -128,7 +130,7 @@ def _ensure_thread(self) -> bool: return True - def add(self, item: "Metric") -> None: + def add(self, item: "Metric", admission: "Optional[_Admission]" = None) -> None: # Bail out if the current thread is already executing batcher code. if getattr(self._active, "flag", False): return None @@ -154,10 +156,11 @@ def add(self, item: "Metric") -> None: self._flush_event.set() return - window = self._admitted.window - if window is None: + if admission is None: return + window = admission.window + reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]] if ( len(reservoir.kept) < limit @@ -165,39 +168,39 @@ def add(self, item: "Metric") -> None: ): window.number_kept += 1 reservoir.kept.append(item) - elif reservoir.index is not None: - reservoir.kept[reservoir.index] = item - reservoir.index = None + elif admission.index is not None: + reservoir.kept[admission.index] = item if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME: self._retire_window(window) finally: self._active.flag = False - def admit(self, name: str) -> bool: + def admit(self, name: str) -> "tuple[bool, Optional[_Admission]]": """ Count a captured metric and decide whether window sampling keeps it. + + Returns whether to keep the metric, and where to keep it if it's sampled. + The admission has to be passed to add with the metric. """ limit = self._limits.get(name) if limit is None: - return True + return True, None window = self._window - self._admitted.window = window reservoir = window.threads[threading.get_ident()].reservoirs[name] reservoir.seen += 1 if ( len(reservoir.kept) < limit and window.number_kept < self.MAX_KEPT_PER_WINDOW ): - return True + return True, _Admission(window, None) index = random.randrange(reservoir.seen) if index >= len(reservoir.kept): - return False + return False, None - reservoir.index = index - return True + return True, _Admission(window, index) def _retire_window(self, window: "_Window") -> None: claim = object() diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index a98f4b74d8..fea75df79f 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -54,6 +54,7 @@ if TYPE_CHECKING: from typing import Any, Callable, Optional, Sequence, Type, TypeVar, Union + from sentry_sdk._lock_free_metrics_batcher import _Admission from sentry_sdk._log_batcher import LogBatcher from sentry_sdk._metrics_batcher import MetricsBatcher from sentry_sdk._types import ( @@ -231,7 +232,12 @@ def capture_event(self, *args: "Any", **kwargs: "Any") -> "Optional[str]": def _capture_log(self, log: "Log", scope: "Scope") -> None: pass - def _capture_metric(self, metric: "Metric", scope: "Scope") -> None: + def _capture_metric( + self, + metric: "Metric", + scope: "Scope", + admission: "Optional[_Admission]" = None, + ) -> None: pass def _capture_span(self, span: "Span", scope: "Scope") -> None: @@ -849,6 +855,7 @@ def _capture_telemetry( telemetry: "Optional[Union[Log, Metric, Span]]", ty: str, scope: "Scope", + admission: "Optional[_Admission]" = None, ) -> None: """ Capture attributes-based telemetry (logs, metrics, streamed spans). @@ -936,14 +943,24 @@ def _capture_telemetry( serialized["_segment_span"] = telemetry._segment # type: ignore batcher = self.span_batcher - if batcher is not None: + if batcher is None: + return + + if admission is None: batcher.add(serialized) # type: ignore + else: + batcher.add(serialized, admission) # type: ignore def _capture_log(self, log: "Optional[Log]", scope: "Scope") -> None: self._capture_telemetry(log, "log", scope) - def _capture_metric(self, metric: "Optional[Metric]", scope: "Scope") -> None: - self._capture_telemetry(metric, "metric", scope) + def _capture_metric( + self, + metric: "Optional[Metric]", + scope: "Scope", + admission: "Optional[_Admission]" = None, + ) -> None: + self._capture_telemetry(metric, "metric", scope, admission) def _capture_span(self, span: "Optional[Span]", scope: "Scope") -> None: self._capture_telemetry(span, "span", scope) diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index 9c1b530e15..82f5a350cb 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -18,8 +18,11 @@ def _capture_metric( ) -> None: scope = sentry_sdk.get_current_scope() batcher = scope.get_client().metrics_batcher - if isinstance(batcher, LockFreeMetricsBatcher) and not batcher.admit(name): - return + admission = None + if isinstance(batcher, LockFreeMetricsBatcher): + keep, admission = batcher.admit(name) + if not keep: + return attrs: "Attributes" = {} @@ -38,7 +41,7 @@ def _capture_metric( "attributes": attrs, } - scope._capture_metric(metric) + scope._capture_metric(metric, admission) def count( diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index abeafdb22a..faf4b535db 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -63,6 +63,7 @@ ) import sentry_sdk + from sentry_sdk._lock_free_metrics_batcher import _Admission from sentry_sdk._types import ( Attributes, AttributeValue, @@ -1147,7 +1148,9 @@ def _capture_log(self, log: "Optional[Log]") -> None: client._capture_log(log, scope=merged_scope) - def _capture_metric(self, metric: "Optional[Metric]") -> None: + def _capture_metric( + self, metric: "Optional[Metric]", admission: "Optional[_Admission]" = None + ) -> None: if metric is None: return @@ -1161,7 +1164,7 @@ def _capture_metric(self, metric: "Optional[Metric]") -> None: f"[Sentry Metrics] [{metric.get('type')}] {metric.get('name')}: {metric.get('value')}" ) - client._capture_metric(metric, scope=merged_scope) + client._capture_metric(metric, scope=merged_scope, admission=admission) def _capture_span(self, span: "Optional[Span]") -> None: if span is None: From 647fb4caee2ccab89ebde2d70ff4b7db24d7ebf6 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Tue, 1 Dec 2026 11:42:10 +0100 Subject: [PATCH 5/6] add maxlen to retired deque --- sentry_sdk/_lock_free_metrics_batcher.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sentry_sdk/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index 6850b108ce..74f005f9b0 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -88,7 +88,7 @@ def __init__( self._queue: "deque[Metric]" = deque() self._window = _Window() - self._retired: "deque[_Window]" = deque() + self._retired: "deque[_Window]" = deque(maxlen=20) # Holds the claim of the one thread that gets to start the flusher. self._flusher_claim: "dict[str, object]" = {} @@ -96,7 +96,7 @@ def _reset_thread_state(self) -> None: super()._reset_thread_state() self._queue = deque() self._window = _Window() - self._retired = deque() + self._retired = deque(maxlen=20) self._flusher_claim = {} def _ensure_thread(self) -> bool: From dc232739537df801e14dde3db0a2132442db209f Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Tue, 1 Dec 2026 11:59:39 +0100 Subject: [PATCH 6/6] revert re-entrancy fix --- sentry_sdk/_lock_free_metrics_batcher.py | 43 +++++++++++------------- sentry_sdk/client.py | 25 +++----------- sentry_sdk/metrics.py | 9 ++--- sentry_sdk/scope.py | 7 ++-- 4 files changed, 29 insertions(+), 55 deletions(-) diff --git a/sentry_sdk/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index 74f005f9b0..46f9ab1cfd 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -22,11 +22,13 @@ class _Reservoir: - __slots__ = ("kept", "seen") + __slots__ = ("kept", "seen", "index") def __init__(self) -> None: self.kept: "list[Metric]" = [] self.seen = 0 + # The slot admit picked for the metric currently on its way to add. + self.index: "Optional[int]" = None class _ThreadState: @@ -53,14 +55,8 @@ def __init__(self) -> None: self.number_kept = 0 -class _Admission: - """Where admit decided to keep a metric, for add to put it there.""" - - __slots__ = ("window", "index") - - def __init__(self, window: "_Window", index: "Optional[int]") -> None: - self.window = window - self.index = index +class _Admitted(threading.local): + window: "Optional[_Window]" = None class LockFreeMetricsBatcher(Batcher["Metric"]): @@ -88,6 +84,7 @@ def __init__( self._queue: "deque[Metric]" = deque() self._window = _Window() + self._admitted = _Admitted() self._retired: "deque[_Window]" = deque(maxlen=20) # Holds the claim of the one thread that gets to start the flusher. self._flusher_claim: "dict[str, object]" = {} @@ -96,6 +93,7 @@ def _reset_thread_state(self) -> None: super()._reset_thread_state() self._queue = deque() self._window = _Window() + self._admitted = _Admitted() self._retired = deque(maxlen=20) self._flusher_claim = {} @@ -130,7 +128,7 @@ def _ensure_thread(self) -> bool: return True - def add(self, item: "Metric", admission: "Optional[_Admission]" = None) -> None: + def add(self, item: "Metric") -> None: # Bail out if the current thread is already executing batcher code. if getattr(self._active, "flag", False): return None @@ -156,11 +154,10 @@ def add(self, item: "Metric", admission: "Optional[_Admission]" = None) -> None: self._flush_event.set() return - if admission is None: + window = self._admitted.window + if window is None: return - window = admission.window - reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]] if ( len(reservoir.kept) < limit @@ -168,39 +165,39 @@ def add(self, item: "Metric", admission: "Optional[_Admission]" = None) -> None: ): window.number_kept += 1 reservoir.kept.append(item) - elif admission.index is not None: - reservoir.kept[admission.index] = item + elif reservoir.index is not None: + reservoir.kept[reservoir.index] = item + reservoir.index = None if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME: self._retire_window(window) finally: self._active.flag = False - def admit(self, name: str) -> "tuple[bool, Optional[_Admission]]": + def admit(self, name: str) -> bool: """ Count a captured metric and decide whether window sampling keeps it. - - Returns whether to keep the metric, and where to keep it if it's sampled. - The admission has to be passed to add with the metric. """ limit = self._limits.get(name) if limit is None: - return True, None + return True window = self._window + self._admitted.window = window reservoir = window.threads[threading.get_ident()].reservoirs[name] reservoir.seen += 1 if ( len(reservoir.kept) < limit and window.number_kept < self.MAX_KEPT_PER_WINDOW ): - return True, _Admission(window, None) + return True index = random.randrange(reservoir.seen) if index >= len(reservoir.kept): - return False, None + return False - return True, _Admission(window, index) + reservoir.index = index + return True def _retire_window(self, window: "_Window") -> None: claim = object() diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index fea75df79f..a98f4b74d8 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -54,7 +54,6 @@ if TYPE_CHECKING: from typing import Any, Callable, Optional, Sequence, Type, TypeVar, Union - from sentry_sdk._lock_free_metrics_batcher import _Admission from sentry_sdk._log_batcher import LogBatcher from sentry_sdk._metrics_batcher import MetricsBatcher from sentry_sdk._types import ( @@ -232,12 +231,7 @@ def capture_event(self, *args: "Any", **kwargs: "Any") -> "Optional[str]": def _capture_log(self, log: "Log", scope: "Scope") -> None: pass - def _capture_metric( - self, - metric: "Metric", - scope: "Scope", - admission: "Optional[_Admission]" = None, - ) -> None: + def _capture_metric(self, metric: "Metric", scope: "Scope") -> None: pass def _capture_span(self, span: "Span", scope: "Scope") -> None: @@ -855,7 +849,6 @@ def _capture_telemetry( telemetry: "Optional[Union[Log, Metric, Span]]", ty: str, scope: "Scope", - admission: "Optional[_Admission]" = None, ) -> None: """ Capture attributes-based telemetry (logs, metrics, streamed spans). @@ -943,24 +936,14 @@ def _capture_telemetry( serialized["_segment_span"] = telemetry._segment # type: ignore batcher = self.span_batcher - if batcher is None: - return - - if admission is None: + if batcher is not None: batcher.add(serialized) # type: ignore - else: - batcher.add(serialized, admission) # type: ignore def _capture_log(self, log: "Optional[Log]", scope: "Scope") -> None: self._capture_telemetry(log, "log", scope) - def _capture_metric( - self, - metric: "Optional[Metric]", - scope: "Scope", - admission: "Optional[_Admission]" = None, - ) -> None: - self._capture_telemetry(metric, "metric", scope, admission) + def _capture_metric(self, metric: "Optional[Metric]", scope: "Scope") -> None: + self._capture_telemetry(metric, "metric", scope) def _capture_span(self, span: "Optional[Span]", scope: "Scope") -> None: self._capture_telemetry(span, "span", scope) diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index 82f5a350cb..9c1b530e15 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -18,11 +18,8 @@ def _capture_metric( ) -> None: scope = sentry_sdk.get_current_scope() batcher = scope.get_client().metrics_batcher - admission = None - if isinstance(batcher, LockFreeMetricsBatcher): - keep, admission = batcher.admit(name) - if not keep: - return + if isinstance(batcher, LockFreeMetricsBatcher) and not batcher.admit(name): + return attrs: "Attributes" = {} @@ -41,7 +38,7 @@ def _capture_metric( "attributes": attrs, } - scope._capture_metric(metric, admission) + scope._capture_metric(metric) def count( diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index faf4b535db..abeafdb22a 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -63,7 +63,6 @@ ) import sentry_sdk - from sentry_sdk._lock_free_metrics_batcher import _Admission from sentry_sdk._types import ( Attributes, AttributeValue, @@ -1148,9 +1147,7 @@ def _capture_log(self, log: "Optional[Log]") -> None: client._capture_log(log, scope=merged_scope) - def _capture_metric( - self, metric: "Optional[Metric]", admission: "Optional[_Admission]" = None - ) -> None: + def _capture_metric(self, metric: "Optional[Metric]") -> None: if metric is None: return @@ -1164,7 +1161,7 @@ def _capture_metric( f"[Sentry Metrics] [{metric.get('type')}] {metric.get('name')}: {metric.get('value')}" ) - client._capture_metric(metric, scope=merged_scope, admission=admission) + client._capture_metric(metric, scope=merged_scope) def _capture_span(self, span: "Optional[Span]") -> None: if span is None: