From 50ced6edf84c97078851b35fceb000a13d9c1fe1 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Tue, 1 Dec 2026 10:07:10 +0100 Subject: [PATCH 1/3] feat: Window sample all metrics with metrics_target_per_second=True --- sentry_sdk/_lock_free_metrics_batcher.py | 73 +++++++++++++++++------- sentry_sdk/client.py | 4 +- sentry_sdk/consts.py | 4 +- tests/test_metrics.py | 31 ++++++++++ 4 files changed, 89 insertions(+), 23 deletions(-) diff --git a/sentry_sdk/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index bc61cd4d26..066703d3f8 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -16,10 +16,12 @@ ) if TYPE_CHECKING: - from typing import Any, Callable, Optional + from typing import Any, Callable, Optional, Union from sentry_sdk._types import Metric +DEFAULT_TARGET_PER_SECOND = 0.4 + class _Reservoir: __slots__ = ("kept", "seen", "index") @@ -46,10 +48,20 @@ class _Window: Only the thread with the given identifier should change its local state. """ - __slots__ = ("limits", "start", "threads", "retire_claims", "number_kept") + __slots__ = ( + "limits", + "default_limit", + "start", + "threads", + "retire_claims", + "number_kept", + ) - def __init__(self, limits: "dict[str, int]") -> None: + def __init__( + self, limits: "dict[str, int]", default_limit: "Optional[int]" + ) -> None: self.limits = limits + self.default_limit = default_limit self.start = time.monotonic() self.threads: "defaultdict[int, _ThreadState]" = defaultdict(_ThreadState) self.retire_claims: "list[object]" = [] @@ -75,25 +87,36 @@ def __init__( self, capture_func: "Callable[[Envelope], None]", record_lost_func: "Callable[..., None]", - window_sampling: "dict[str, float]", + window_sampling: "Union[bool, dict[str, float]]", ) -> None: super().__init__(capture_func, record_lost_func) # The limit is split between the two windows, so that a name never goes # over it in total. Metrics in sampled spans get the extra slot of an odd # limit. - limits = { - name: int(rate * self.FLUSH_WAIT_TIME) - for name, rate in window_sampling.items() - } + limits = {} + default_limit = None + if window_sampling is True: + default_limit = int(DEFAULT_TARGET_PER_SECOND * self.FLUSH_WAIT_TIME) + elif isinstance(window_sampling, dict): + limits = { + name: int(rate * self.FLUSH_WAIT_TIME) + for name, rate in window_sampling.items() + } self._limits = {name: limit // 2 for name, limit in limits.items()} self._trace_connected_limits = { name: (limit + 1) // 2 for name, limit in limits.items() } + self._default_limit = None if default_limit is None else default_limit // 2 + self._trace_connected_default_limit = ( + None if default_limit is None else (default_limit + 1) // 2 + ) self._queue: "deque[Metric]" = deque() - self._window = _Window(self._limits) - self._trace_connected_window = _Window(self._trace_connected_limits) + self._window = _Window(self._limits, self._default_limit) + self._trace_connected_window = _Window( + self._trace_connected_limits, self._trace_connected_default_limit + ) self._admitted = _Admitted() self._retired: "deque[_Window]" = deque() # Holds the claim of the one thread that gets to start the flusher. @@ -102,8 +125,10 @@ def __init__( def _reset_thread_state(self) -> None: super()._reset_thread_state() self._queue = deque() - self._window = _Window(self._limits) - self._trace_connected_window = _Window(self._trace_connected_limits) + self._window = _Window(self._limits, self._default_limit) + self._trace_connected_window = _Window( + self._trace_connected_limits, self._trace_connected_default_limit + ) self._admitted = _Admitted() self._retired = deque() self._flusher_claim = {} @@ -149,7 +174,7 @@ def add(self, item: "Metric") -> None: if not self._ensure_thread(): return None - if item["name"] not in self._limits: + if self._limits.get(item["name"], self._default_limit) is None: if len(self._queue) >= self.MAX_UNSAMPLED_BEFORE_DROP: self._record_lost(item) return None @@ -168,7 +193,10 @@ def add(self, item: "Metric") -> None: if window is None: return - limit = window.limits[item["name"]] + limit = window.limits.get(item["name"], window.default_limit) + if limit is None: + return + reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]] if ( len(reservoir.kept) < limit @@ -189,13 +217,13 @@ def admit(self, name: str, with_sampled_span: bool = False) -> bool: """ Count a captured metric and decide whether window sampling keeps it. """ - if name not in self._limits: + window = self._trace_connected_window if with_sampled_span else self._window + limit = window.limits.get(name, window.default_limit) + if limit is None: return True - window = self._trace_connected_window if with_sampled_span else self._window self._admitted.window = window self._admitted.with_sampled_span = with_sampled_span - limit = window.limits[name] reservoir = window.threads[threading.get_ident()].reservoirs[name] reservoir.seen += 1 if ( @@ -218,9 +246,11 @@ def _retire_window(self, window: "_Window", with_sampled_span: bool) -> None: return if with_sampled_span: - self._trace_connected_window = _Window(self._trace_connected_limits) + self._trace_connected_window = _Window( + self._trace_connected_limits, self._trace_connected_default_limit + ) else: - self._window = _Window(self._limits) + self._window = _Window(self._limits, self._default_limit) self._retired.append(window) def flush(self) -> None: @@ -292,7 +322,10 @@ def _harvest(self, window: "_Window", items: "list[Metric]") -> int: sampled_out = 0 for name, reservoirs in by_name.items(): - limit = window.limits[name] + limit = window.limits.get(name, window.default_limit) + if limit is None: + continue + bounds = list( itertools.accumulate(reservoir.seen for reservoir in reservoirs) ) diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 535fb64747..1196bce4b7 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -131,7 +131,7 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]": rv["data_collection"] = _resolve_data_collection(rv) window_sampling = rv["_experiments"].get("metrics_target_per_second") - if window_sampling is not None: + if window_sampling is not None and window_sampling is not True: valid_rates = {} if isinstance(window_sampling, dict): for name, rate in window_sampling.items(): @@ -159,7 +159,7 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]": valid_rates[name] = clamped else: logger.warning( - "[Metrics] metrics_target_per_second must map metric names to metrics per second. Got %s, not sampling.", + "[Metrics] metrics_target_per_second must be True or map metric names to metrics per second. Got %s, not sampling.", window_sampling, ) rv["_experiments"] = { diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 9722fba427..567773734d 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -74,7 +74,9 @@ class CompressionAlgo(Enum): "transport_num_pools": Optional[int], "transport_http2": Optional[bool], "transport_async": Optional[bool], - "metrics_target_per_second": Optional[Dict[str, float]], + "metrics_target_per_second": Optional[ + Union[Literal[True], Dict[str, float]] + ], }, total=False, ) diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 8e5d2b0fc6..2d18938181 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -641,6 +641,37 @@ def test_metrics_window_sampling( ] +@pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0]) +def test_metrics_window_sampling_all_names( + sentry_init, traces_sample_rate, capture_items +): + sentry_init( + traces_sample_rate=traces_sample_rate, + _experiments={"metrics_target_per_second": True}, + ) + items = capture_items("trace_metric") + + for name in ("test.a", "test.b"): + for _ in range(50): + sentry_sdk.metrics.count(name, 1) + with sentry_sdk.start_span(name="test-span"): + for _ in range(50): + sentry_sdk.metrics.count(name, 1) + + get_client().flush() + + for name in ("test.a", "test.b"): + metrics = [item.payload for item in items if item.payload["name"] == name] + if traces_sample_rate: + assert sorted("span_id" in metric for metric in metrics) == [False, True] + rate = 1 / 50 + else: + assert len(metrics) == 1 + rate = 1 / 100 + for metric in metrics: + assert metric["attributes"]["sentry.client_sample_rate"] == rate + + @pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0]) def test_metrics_window_sampling_new_window( sentry_init, traces_sample_rate, capture_items From 667ca25b2784acaed46add02652027a1fe6910a8 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Tue, 1 Dec 2026 11:58:38 +0100 Subject: [PATCH 2/3] revert re-entrancy fix --- sentry_sdk/_lock_free_metrics_batcher.py | 51 +++++++++++------------- sentry_sdk/client.py | 25 ++---------- sentry_sdk/metrics.py | 8 ++-- sentry_sdk/scope.py | 7 +--- 4 files changed, 32 insertions(+), 59 deletions(-) diff --git a/sentry_sdk/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index f63f951d63..b8c8e75a6c 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -24,11 +24,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: @@ -66,17 +68,9 @@ def __init__( self.number_kept = 0 -class _Admission: - """Where admit decided to keep a metric, for add to put it there.""" - - __slots__ = ("window", "with_sampled_span", "index") - - def __init__( - self, window: "_Window", with_sampled_span: bool, index: "Optional[int]" - ) -> None: - self.window = window - self.with_sampled_span = with_sampled_span - self.index = index +class _Admitted(threading.local): + window: "Optional[_Window]" = None + with_sampled_span = False class LockFreeMetricsBatcher(Batcher["Metric"]): @@ -120,6 +114,7 @@ def __init__( self._trace_connected_window = _Window( self._trace_connected_limits, self._trace_connected_default_limit ) + 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]" = {} @@ -131,6 +126,7 @@ def _reset_thread_state(self) -> None: self._trace_connected_window = _Window( self._trace_connected_limits, self._trace_connected_default_limit ) + self._admitted = _Admitted() self._retired = deque(maxlen=20) self._flusher_claim = {} @@ -165,7 +161,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 @@ -190,10 +186,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 limit = window.limits.get(item["name"], window.default_limit) if limit is None: return @@ -205,41 +201,40 @@ 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, admission.with_sampled_span) + self._retire_window(window, self._admitted.with_sampled_span) finally: self._active.flag = False - def admit( - self, name: str, with_sampled_span: bool = False - ) -> "tuple[bool, Optional[_Admission]]": + def admit(self, name: str, with_sampled_span: bool = False) -> 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. """ window = self._trace_connected_window if with_sampled_span else self._window limit = window.limits.get(name, window.default_limit) if limit is None: - return True, None + return True + self._admitted.window = window + self._admitted.with_sampled_span = with_sampled_span 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, with_sampled_span, None) + return True index = random.randrange(reservoir.seen) if index >= len(reservoir.kept): - return False, None + return False - return True, _Admission(window, with_sampled_span, index) + reservoir.index = index + return True def _retire_window(self, window: "_Window", with_sampled_span: bool) -> None: claim = object() diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index eb95b3f1d0..1196bce4b7 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 5d4bdbfaa6..2802ac1d4c 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -19,14 +19,12 @@ def _capture_metric( ) -> None: scope = sentry_sdk.get_current_scope() batcher = scope.get_client().metrics_batcher - admission = None if isinstance(batcher, LockFreeMetricsBatcher): span = scope.span - keep, admission = batcher.admit( + if not batcher.admit( name=name, with_sampled_span=span is not None and not isinstance(span, NoOpSpan), - ) - if not keep: + ): return attrs: "Attributes" = {} @@ -46,7 +44,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: From 4d462c33ca72d0ea860f104e3e2b0d93abc00f5f Mon Sep 17 00:00:00 2001 From: alexander-alderman-webb <224035503+alexander-alderman-webb@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:13:44 +0000 Subject: [PATCH 3/3] release: 3.1.0b2 --- CHANGELOG.md | 11 +++++++++++ docs/conf.py | 2 +- sentry_sdk/consts.py | 2 +- setup.py | 2 +- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a348ad25f..aa5c25db37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 3.1.0b2 + +### New Features ✨ + +- Window sample all metrics with `metrics_target_per_second=True` by @alexander-alderman-webb in [#8428](https://github.com/getsentry/sentry-python/pull/8428) +- Dual window for metrics with sampled spans by @alexander-alderman-webb in [#8427](https://github.com/getsentry/sentry-python/pull/8427) + +### Internal Changes 🔧 + +- (metrics) Drop negatively sampled metrics immediately by @alexander-alderman-webb with @sentry-release-bot in [#8425](https://github.com/getsentry/sentry-python/pull/8425) + ## 3.1.0b1 ### New Features ✨ diff --git a/docs/conf.py b/docs/conf.py index 3ebef6f09e..8571e41b1f 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.1.0b1" +release = "3.1.0b2" version = ".".join(release.split(".")[:2]) # The short X.Y version. diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 567773734d..02edb63126 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -2068,4 +2068,4 @@ def _get_default_options() -> "dict[str, Any]": del _get_default_options -VERSION = "3.1.0b1" +VERSION = "3.1.0b2" diff --git a/setup.py b/setup.py index 8000f1aefb..2c99b336fb 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ def get_file_text(file_name): setup( name="sentry-sdk", - version="3.1.0b1", + version="3.1.0b2", author="Sentry Team and Contributors", author_email="hello@sentry.io", url="https://github.com/getsentry/sentry-python",