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/_lock_free_metrics_batcher.py b/sentry_sdk/_lock_free_metrics_batcher.py index 070efb2725..b8c8e75a6c 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,22 +87,33 @@ 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) - 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(maxlen=20) # Holds the claim of the one thread that gets to start the flusher. @@ -99,8 +122,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(maxlen=20) self._flusher_claim = {} @@ -146,7 +171,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 @@ -165,7 +190,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 @@ -186,13 +214,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 ( @@ -215,9 +243,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: @@ -289,7 +319,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..02edb63126 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, ) @@ -2066,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", 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