From c27cfa560a412606141397ddc2851a529e77e16a Mon Sep 17 00:00:00 2001 From: Kev Date: Tue, 17 Nov 2026 20:13:11 -0500 Subject: [PATCH] feat(metrics): Add experimental window sampling for trace metrics Behind an _experimental flag, we will add window sampling to allow for better handling of high volume metric event data. --- sentry_sdk/_batcher.py | 15 ++- sentry_sdk/_metrics_batcher.py | 159 +++++++++++++++++++++- sentry_sdk/_types.py | 6 + sentry_sdk/client.py | 3 + sentry_sdk/consts.py | 4 + tests/test_metrics.py | 233 +++++++++++++++++++++++++++++++++ 6 files changed, 412 insertions(+), 8 deletions(-) diff --git a/sentry_sdk/_batcher.py b/sentry_sdk/_batcher.py index 7fdc8ee895..6b64a31828 100644 --- a/sentry_sdk/_batcher.py +++ b/sentry_sdk/_batcher.py @@ -124,11 +124,7 @@ def add(self, item: "T") -> None: return None with self._lock: - dropped = len(self._buffer) >= self.MAX_BEFORE_DROP - if not dropped: - self._buffer.append(item) - if len(self._buffer) >= self.MAX_BEFORE_FLUSH: - self._flush_event.set() + dropped = not self._add_locked(item) # Record the loss outside of the lock, since this might involve # serializing the item to report lost bytes @@ -137,6 +133,15 @@ def add(self, item: "T") -> None: finally: self._active.flag = False + def _add_locked(self, item: "T") -> bool: + if len(self._buffer) >= self.MAX_BEFORE_DROP: + return False + + self._buffer.append(item) + if len(self._buffer) >= self.MAX_BEFORE_FLUSH: + self._flush_event.set() + return True + def kill(self) -> None: if self._flusher is None: return diff --git a/sentry_sdk/_metrics_batcher.py b/sentry_sdk/_metrics_batcher.py index 706e5ca653..59edb5dd62 100644 --- a/sentry_sdk/_metrics_batcher.py +++ b/sentry_sdk/_metrics_batcher.py @@ -1,12 +1,20 @@ +import math +import random +import time from typing import TYPE_CHECKING from sentry_sdk._batcher import Batcher -from sentry_sdk.utils import serialize_attribute +from sentry_sdk.utils import capture_internal_exceptions, logger, serialize_attribute if TYPE_CHECKING: - from typing import Any + from typing import Any, Callable, Dict, List, Optional, Tuple, Union - from sentry_sdk._types import Metric + from sentry_sdk._types import Metric, MetricWindowSamplingOptions + from sentry_sdk.envelope import Envelope + +DEFAULT_SAMPLE_PER_SECOND = 2 +# Matches FLUSH_WAIT_TIME, so each window goes out in one flush +WINDOW_SECONDS = 5.0 class MetricsBatcher(Batcher["Metric"]): @@ -18,6 +26,151 @@ class MetricsBatcher(Batcher["Metric"]): CLIENT_REPORT_TYPE = "trace_metric" CONTENT_TYPE = "application/vnd.sentry.items.trace-metric+json" + def __init__( + self, + capture_func: "Callable[[Envelope], None]", + record_lost_func: "Callable[..., None]", + window_sampling: "Union[bool, MetricWindowSamplingOptions, None]" = None, + ) -> None: + self._default_limit: "Optional[int]" = None + self._name_limits: "Dict[str, int]" = {} + if window_sampling: + options = window_sampling if isinstance(window_sampling, dict) else {} + per_name = options.get("per_name") + if isinstance(per_name, dict): + self._name_limits = { + name: self._parse_limit(rate) for name, rate in per_name.items() + } + if "sample_per_second" in options or not self._name_limits: + self._default_limit = self._parse_limit( + options.get("sample_per_second", DEFAULT_SAMPLE_PER_SECOND) + ) + self._sampling = bool(self._name_limits) or self._default_limit is not None + + self._reset_sampling_state() + super().__init__(capture_func, record_lost_func) + + def _reset_thread_state(self) -> None: + super()._reset_thread_state() + self._reset_sampling_state() + + def _reset_sampling_state(self) -> None: + self._window_start = time.monotonic() + self._reservoirs: "Dict[str, List[Metric]]" = {} + self._seen: "Dict[str, int]" = {} + # Reservoirs count against MAX_BEFORE_DROP together with the buffer, so + # memory stays bounded no matter how many names there are + self._held = 0 + self._sampled_out: "List[Tuple[Metric, int]]" = [] + + def _parse_limit(self, value: float) -> int: + try: + rate = float(value) + except (TypeError, ValueError): + rate = math.nan + + if not (math.isfinite(rate) and rate > 0): + logger.warning( + "[Metrics] Given window sampling rate is invalid. It must be a positive number. Got %r, using %s instead.", + value, + DEFAULT_SAMPLE_PER_SECOND, + ) + rate = DEFAULT_SAMPLE_PER_SECOND + + # Never go below 1, so we always keep at least one metric per name to + # extrapolate from + return min(max(1, int(rate * WINDOW_SECONDS)), self.MAX_BEFORE_DROP) + + def _add_locked(self, item: "Metric") -> bool: + if not self._sampling: + return super()._add_locked(item) + + name = item["name"] + limit = self._name_limits.get(name, self._default_limit) + if limit is None: + if len(self._buffer) + self._held >= self.MAX_BEFORE_DROP: + return False + return super()._add_locked(item) + + if time.monotonic() - self._window_start >= WINDOW_SECONDS: + self._close_window() + + reservoir = self._reservoirs.setdefault(name, []) + seen = self._seen.get(name, 0) + 1 + if len(reservoir) < limit: + # Replacing a slot in a full reservoir doesn't need more memory, only + # a new slot does + if len(self._buffer) + self._held >= self.MAX_BEFORE_DROP: + return False + reservoir.append(item) + self._held += 1 + else: + index = random.randrange(seen) + if index < limit: + reservoir[index] = item + self._seen[name] = seen + return True + + def _close_window(self) -> None: + for name, kept in self._reservoirs.items(): + seen = self._seen.get(name, 0) + if kept and seen > len(kept): + rate = len(kept) / seen + for item in kept: + attributes = item["attributes"] + client_rate = attributes.get("sentry.client_sample_rate") + if isinstance(client_rate, (int, float)) and 0 < client_rate <= 1: + attributes["sentry.client_sample_rate"] = rate * client_rate + else: + attributes["sentry.client_sample_rate"] = rate + self._sampled_out.append((kept[0], seen - len(kept))) + self._buffer.extend(kept) + + self._reservoirs = {} + self._seen = {} + self._held = 0 + self._window_start = time.monotonic() + if len(self._buffer) >= self.MAX_BEFORE_FLUSH: + self._flush_event.set() + + def flush(self) -> None: + if self._sampling: + with self._lock: + self._close_window() + super().flush() + + def _flush(self) -> "Optional[Envelope]": + if not self._sampling: + return super()._flush() + + with self._lock: + # Early flushes leave the window open, so a name can't go over its + # rate + if time.monotonic() - self._window_start >= WINDOW_SECONDS: + self._close_window() + sampled_out, self._sampled_out = self._sampled_out, [] + + envelope = super()._flush() + + # Record outside of the lock, since this serializes a metric and every + # add() would wait on it + for item, count in sampled_out: + self._record_lost_func( + reason="sample_rate", + data_category=self.CLIENT_REPORT_TYPE, + quantity=count, + ) + # Serializing every sampled out metric would cost as much as we saved + # by sampling, so we estimate from one + with capture_internal_exceptions(): + self._record_lost_func( + reason="sample_rate", + data_category="trace_metric_byte", + quantity=count * len(self._to_envelope_item([item]).get_bytes()), + ) + + return envelope + @staticmethod def _to_transport_format(item: "Metric") -> "Any": res = { diff --git a/sentry_sdk/_types.py b/sentry_sdk/_types.py index 40efa2d228..d77bee2b24 100644 --- a/sentry_sdk/_types.py +++ b/sentry_sdk/_types.py @@ -359,6 +359,12 @@ class DataCollection(TypedDict): }, ) + MetricWindowSamplingOptions = TypedDict( + "MetricWindowSamplingOptions", + {"sample_per_second": float, "per_name": Dict[str, float]}, + total=False, + ) + SpanJSON = TypedDict( "SpanJSON", { diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 7f84cea140..0daa3ec17e 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -382,6 +382,9 @@ def _record_lost_event( self.metrics_batcher = MetricsBatcher( capture_func=_capture_envelope, record_lost_func=_record_lost_event, + window_sampling=self.options["_experiments"].get( + "metrics_window_sampling" + ), ) self.span_batcher = SpanBatcher( diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 953b693744..83ff4d161d 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -54,6 +54,7 @@ class CompressionAlgo(Enum): IgnoreSpansConfig, Log, Metric, + MetricWindowSamplingOptions, SpanJSON, TracesSampler, ) @@ -73,6 +74,9 @@ class CompressionAlgo(Enum): "transport_num_pools": Optional[int], "transport_http2": Optional[bool], "transport_async": Optional[bool], + "metrics_window_sampling": Optional[ + Union[bool, MetricWindowSamplingOptions] + ], }, total=False, ) diff --git a/tests/test_metrics.py b/tests/test_metrics.py index efc458c32a..374d2c3f00 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -1,11 +1,13 @@ import os import sys +import time from unittest import mock import pytest import sentry_sdk from sentry_sdk import get_client +from sentry_sdk._metrics_batcher import MetricsBatcher from sentry_sdk.consts import SPANDATA, VERSION @@ -574,3 +576,234 @@ def test_metrics_batcher_lock_reset_in_child_after_fork(sentry_init): original_lock.release() _, status = os.waitpid(pid, 0) assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0 + + +def test_metrics_not_sampled_by_default(sentry_init, capture_items): + sentry_init() + items = capture_items("trace_metric") + + for _ in range(100): + sentry_sdk.metrics.count("test.counter", 1) + + get_client().flush() + + metrics = [item.payload for item in items] + assert len(metrics) == 100 + + for metric in metrics: + assert "sentry.client_sample_rate" not in metric["attributes"] + + +def test_metrics_window_sampling_basics( + sentry_init, capture_items, capture_record_lost_event_calls +): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + record_lost_event_calls = capture_record_lost_event_calls() + + for _ in range(200): + sentry_sdk.metrics.count("test.hot", 1) + for _ in range(3): + sentry_sdk.metrics.count("test.cold", 1) + + get_client().flush() + + metrics = [item.payload for item in items] + assert len(metrics) == 13 + + hot = [metric for metric in metrics if metric["name"] == "test.hot"] + assert len(hot) == 10 + for metric in hot: + assert metric["attributes"]["sentry.client_sample_rate"] == 0.05 + + cold = [metric for metric in metrics if metric["name"] == "test.cold"] + assert len(cold) == 3 + for metric in cold: + assert "sentry.client_sample_rate" not in metric["attributes"] + + assert record_lost_event_calls == [ + ("sample_rate", "trace_metric", None, 190), + ("sample_rate", "trace_metric_byte", None, mock.ANY), + ] + + +@pytest.mark.parametrize( + "sample_per_second,expected_count", + [ + (4, 20), + (0.2, 1), + (0.05, 1), + (float("inf"), 10), + (float("nan"), 10), + (0, 10), + (-1, 10), + ("fast", 10), + ], +) +def test_metrics_window_sampling_sample_per_second( + sentry_init, capture_items, sample_per_second, expected_count +): + sentry_init( + _experiments={ + "metrics_window_sampling": {"sample_per_second": sample_per_second} + } + ) + items = capture_items("trace_metric") + + for _ in range(200): + sentry_sdk.metrics.count("test.counter", 1) + + get_client().flush() + + assert len(items) == expected_count + + +def test_metrics_window_sampling_per_name(sentry_init, capture_items): + sentry_init( + _experiments={"metrics_window_sampling": {"per_name": {"test.hot": 0.2}}} + ) + items = capture_items("trace_metric") + + for _ in range(200): + sentry_sdk.metrics.count("test.hot", 1) + sentry_sdk.metrics.count("test.other", 1) + + get_client().flush() + + metrics = [item.payload for item in items] + assert len(metrics) == 201 + + (hot,) = [metric for metric in metrics if metric["name"] == "test.hot"] + assert hot["attributes"]["sentry.client_sample_rate"] == 1 / 200 + + other = [metric for metric in metrics if metric["name"] == "test.other"] + for metric in other: + assert "sentry.client_sample_rate" not in metric["attributes"] + + +@pytest.mark.parametrize( + "client_sample_rate,expected_sample_rate", + [ + (0.5, 0.05), + (5, 0.1), + (0, 0.1), + (-1, 0.1), + (float("nan"), 0.1), + ("0.5", 0.1), + ], +) +def test_metrics_window_sampling_multiplies_client_sample_rate( + sentry_init, capture_items, client_sample_rate, expected_sample_rate +): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + + for _ in range(100): + sentry_sdk.metrics.count( + "test.counter", + 1, + attributes={"sentry.client_sample_rate": client_sample_rate}, + ) + + get_client().flush() + + metrics = [item.payload for item in items] + assert len(metrics) == 10 + + for metric in metrics: + assert metric["attributes"]["sentry.client_sample_rate"] == expected_sample_rate + + +def test_metrics_window_sampling_new_window(sentry_init, capture_items, monkeypatch): + # Shorten the window so that the test doesn't have to wait 5 seconds for it + # to close + monkeypatch.setattr(sentry_sdk._metrics_batcher, "WINDOW_SECONDS", 1.0) + + sentry_init(_experiments={"metrics_window_sampling": {"sample_per_second": 10}}) + items = capture_items("trace_metric") + + for _ in range(30): + sentry_sdk.metrics.count("test.counter", 1) + time.sleep(1.1) + for _ in range(30): + sentry_sdk.metrics.count("test.counter", 1) + + get_client().flush() + + metrics = [item.payload for item in items] + assert len(metrics) == 20 + + for metric in metrics: + assert metric["attributes"]["sentry.client_sample_rate"] == 1 / 3 + + +def test_metrics_window_sampling_does_not_cap_names(sentry_init, capture_items): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + + for i in range(600): + sentry_sdk.metrics.count(f"test.counter{i}", 1) + sentry_sdk.metrics.count(f"test.counter{i}", 1) + + get_client().flush() + + assert len(items) == 1200 + + +def test_metrics_window_sampling_drops_after_max_reached( + sentry_init, capture_items, capture_record_lost_event_calls, monkeypatch +): + monkeypatch.setattr(MetricsBatcher, "MAX_BEFORE_DROP", 25) + + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + record_lost_event_calls = capture_record_lost_event_calls() + + for name in ("test.a", "test.b", "test.c"): + for _ in range(10): + sentry_sdk.metrics.count(name, 1) + + get_client().flush() + + metrics = [item.payload for item in items] + assert len(metrics) == 25 + + # No name went over its limit, so nothing was sampled and the only loss is + # the overflow + for metric in metrics: + assert "sentry.client_sample_rate" not in metric["attributes"] + + assert len(record_lost_event_calls) == 5 + for lost_event_call in record_lost_event_calls: + reason, data_category, item, quantity = lost_event_call + + assert reason == "queue_overflow" + assert data_category == "trace_metric" + assert quantity == 1 + assert item.payload.json["items"][0]["name"] == "test.c" + + +def test_metrics_window_sampling_after_before_send_metric(sentry_init, capture_items): + before_send_metric_calls = 0 + + def _before_metric(record, hint): + nonlocal before_send_metric_calls + before_send_metric_calls += 1 + return record + + sentry_init( + before_send_metric=_before_metric, + _experiments={"metrics_window_sampling": True}, + ) + items = capture_items("trace_metric") + + for _ in range(200): + sentry_sdk.metrics.count("test.counter", 1) + + get_client().flush() + + # Sampling happens after before_send_metric, so it still sees every metric + assert before_send_metric_calls == 200 + + metrics = [item.payload for item in items] + assert len(metrics) == 10