From 589a778439a39d16a5ccdfce0489e69a7f025a44 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:48:37 +0000 Subject: [PATCH 1/2] feat(metrics): Add experimental window sampling for trace metrics Behind _experiments={"metrics_window_sampling": True | {"sample_per_second": N}}. The existing ~5s flush window is the sampling window. Each metric name keeps at most sample_per_second * FLUSH_WAIT_TIME metrics per window (50 at the default 10/s), picked by reservoir sampling directly in the regular buffer (append, or replace in place). Override per call with sample_per_second=. At flush, kept metrics get sentry.client_sample_rate = kept/seen, multiplied into any rate the caller set, so counts extrapolate. Back pressure: when the buffer reaches MAX_BEFORE_FLUSH and flushes early, every name's allowance is halved for the next window; each window that flushes on the timer doubles it back, up to the requested rate. Client reports reuse existing reasons: sample_rate for drops at the requested rate, backpressure for the extra drops from a lowered allowance. Byte outcomes are estimated from one serialized metric per name. Batcher gets a behavior-preserving _add_locked hook; per-name state is cleared with the buffer on every flush and after fork. Co-Authored-By: Kevan Fisher --- sentry_sdk/_batcher.py | 17 ++- sentry_sdk/_metrics_batcher.py | 185 ++++++++++++++++++++++++++++++++- sentry_sdk/_types.py | 11 ++ sentry_sdk/client.py | 3 + sentry_sdk/consts.py | 4 + sentry_sdk/metrics.py | 15 ++- tests/test_metrics.py | 107 +++++++++++++++++++ 7 files changed, 331 insertions(+), 11 deletions(-) diff --git a/sentry_sdk/_batcher.py b/sentry_sdk/_batcher.py index 7fdc8ee895..a343265608 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,17 @@ def add(self, item: "T") -> None: finally: self._active.flag = False + def _add_locked(self, item: "T") -> bool: + """Append an item to the buffer. Called with the lock held. Returns + False if the buffer is full and the item was dropped.""" + 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..0ddbdaf90c 100644 --- a/sentry_sdk/_metrics_batcher.py +++ b/sentry_sdk/_metrics_batcher.py @@ -1,15 +1,61 @@ +import random 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, 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 Attributes, Metric, MetricWindowSamplingOptions + from sentry_sdk.envelope import Envelope + +# Experimental window sampling, see `MetricsBatcher`. +DEFAULT_SAMPLE_PER_SECOND = 10 +# Lowest factor that back pressure can scale every allowance down to. +MIN_PRESSURE = 0.01 + +# Private key set by `sentry_sdk.metrics` when the caller passes +# `sample_per_second`. It is never serialized (see `_to_transport_format`). +SAMPLE_PER_SECOND_KEY = "_sample_per_second" +CLIENT_SAMPLE_RATE_ATTRIBUTE = "sentry.client_sample_rate" + + +class _NameWindow: + """Per metric name state for the current flush window.""" + + __slots__ = ("base_allowance", "allowance", "seen", "indices") + + def __init__(self, base_allowance: int, allowance: int) -> None: + # What this name asked for: `sample_per_second * FLUSH_WAIT_TIME`. + self.base_allowance = base_allowance + # What it gets this window, after back pressure. + self.allowance = allowance + self.seen = 0 + # Positions of this name's metrics in the shared buffer. + self.indices: "List[int]" = [] class MetricsBatcher(Batcher["Metric"]): + """ + With the experimental `metrics_window_sampling` option, the flush window + (`FLUSH_WAIT_TIME`, ~5s) is also the sampling window. Each metric name + keeps at most `sample_per_second * FLUSH_WAIT_TIME` metrics (50 at the + default 10/s) in the regular buffer per window, picked by reservoir + sampling, so every metric seen in the window has the same chance to be + kept. At flush, kept metrics get `sentry.client_sample_rate = kept / seen` + (multiplied into any rate the caller set) so counts extrapolate. + + Back pressure: when the buffer reaches `MAX_BEFORE_FLUSH` and flushes + early, every name's allowance is halved for the next window. Each window + that flushes on the timer doubles it back, up to what was asked for. + Metrics dropped because of a lowered allowance are reported as + `backpressure`, the rest as `sample_rate`. + + The buffer itself is unchanged: metrics are appended or replaced in place, + and the per-name state is cleared with the buffer on every flush. + """ + MAX_BEFORE_FLUSH = 1000 MAX_BEFORE_DROP = 10_000 FLUSH_WAIT_TIME = 5.0 @@ -18,6 +64,132 @@ 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._sample_per_second: "Optional[float]" = None + if window_sampling: + options = {} if window_sampling is True else window_sampling + self._sample_per_second = options.get( + "sample_per_second", DEFAULT_SAMPLE_PER_SECOND + ) + + self._reset_window_state() + super().__init__(capture_func, record_lost_func) + + def _reset_thread_state(self) -> None: + super()._reset_thread_state() + self._reset_window_state() + + def _reset_window_state(self) -> None: + self._windows: "Dict[str, _NameWindow]" = {} + self._pressure = 1.0 + self._hit_flush_cap = False + # (sample item, sample_rate drops, backpressure drops) per name, + # recorded after the flush releases the lock. + self._pending_lost: "List[Tuple[Metric, int, int]]" = [] + + def _add_locked(self, item: "Metric") -> bool: + if self._sample_per_second is None: + return super()._add_locked(item) + + name = item["name"] + window = self._windows.get(name) + if window is None: + per_second = self._sample_per_second + try: + per_second = float(item.get(SAMPLE_PER_SECOND_KEY, per_second)) # type: ignore[arg-type] + except (TypeError, ValueError): + pass + base_allowance = max(1, int(per_second * self.FLUSH_WAIT_TIME)) + window = _NameWindow( + base_allowance, max(1, int(base_allowance * self._pressure)) + ) + + if len(window.indices) < window.allowance: + if not super()._add_locked(item): + return False + window.indices.append(len(self._buffer) - 1) + self._windows[name] = window + if len(self._buffer) >= self.MAX_BEFORE_FLUSH: + self._hit_flush_cap = True + else: + # Algorithm R: replace a kept metric in place, so every metric + # seen in the window has the same allowance / seen chance. + j = random.randrange(window.seen + 1) + if j < window.allowance: + self._buffer[window.indices[j]] = item + + window.seen += 1 + return True + + def _add_to_envelope(self, envelope: "Envelope") -> None: + # Called by `_flush` with the lock held, right before the buffer is + # cleared. + if self._sample_per_second is not None: + self._close_window() + super()._add_to_envelope(envelope) + + def _close_window(self) -> None: + for window in self._windows.values(): + kept = len(window.indices) + if window.seen <= kept: + continue + + rate = kept / window.seen + for index in window.indices: + attributes = self._buffer[index]["attributes"] + attributes[CLIENT_SAMPLE_RATE_ATTRIBUTE] = rate * _existing_rate( + attributes + ) + + wanted = min(window.seen, window.base_allowance) + self._pending_lost.append( + (self._buffer[window.indices[0]], window.seen - wanted, wanted - kept) + ) + + if self._hit_flush_cap: + self._pressure = max(self._pressure / 2, MIN_PRESSURE) + else: + self._pressure = min(self._pressure * 2, 1.0) + + self._hit_flush_cap = False + self._windows = {} + + def _flush(self) -> "Optional[Envelope]": + envelope = super()._flush() + + with self._lock: + pending, self._pending_lost = self._pending_lost, [] + + for item, sampled, pressured in pending: + # One serialized metric is the byte estimate for every dropped + # metric of that name. + size = 0 + with capture_internal_exceptions(): + size = len(self._to_envelope_item([item]).get_bytes()) + + for reason, count in ( + ("sample_rate", sampled), + ("backpressure", pressured), + ): + if count <= 0: + continue + self._record_lost_func( + reason=reason, data_category=self.CLIENT_REPORT_TYPE, quantity=count + ) + if size: + self._record_lost_func( + reason=reason, + data_category="trace_metric_byte", + quantity=count * size, + ) + + return envelope + @staticmethod def _to_transport_format(item: "Metric") -> "Any": res = { @@ -40,3 +212,10 @@ def _to_transport_format(item: "Metric") -> "Any": res["unit"] = item["unit"] return res + + +def _existing_rate(attributes: "Attributes") -> float: + try: + return float(attributes.get(CLIENT_SAMPLE_RATE_ATTRIBUTE, 1.0)) # type: ignore[arg-type] + except (TypeError, ValueError): + return 1.0 diff --git a/sentry_sdk/_types.py b/sentry_sdk/_types.py index 202282908d..f46305afce 100644 --- a/sentry_sdk/_types.py +++ b/sentry_sdk/_types.py @@ -373,6 +373,17 @@ class DataCollection(TypedDict): MetricProcessor = Callable[[Metric, Hint], Optional[Metric]] + MetricWindowSamplingOptions = TypedDict( + "MetricWindowSamplingOptions", + { + # Max metrics kept per metric name per second, per process, + # applied per flush window. Overridable per call with + # `sample_per_second=`. + "sample_per_second": float, + }, + total=False, + ) + SpanJSON = TypedDict( "SpanJSON", { diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index eec943176c..0c8d3650b6 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -691,6 +691,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 = None diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 3d89c260f3..9355f7897b 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -55,6 +55,7 @@ class CompressionAlgo(Enum): IgnoreSpansConfig, Log, Metric, + MetricWindowSamplingOptions, ProfilerMode, SpanJSON, TracesSampler, @@ -84,6 +85,9 @@ class CompressionAlgo(Enum): "before_send_log": Optional[Callable[[Log, Hint], Optional[Log]]], "enable_metrics": Optional[bool], "before_send_metric": Optional[Callable[[Metric, Hint], Optional[Metric]]], + "metrics_window_sampling": Optional[ + Union[bool, MetricWindowSamplingOptions] + ], "trace_lifecycle": Optional[Literal["static", "stream"]], "ignore_spans": Optional[IgnoreSpansConfig], "before_send_span": Optional[ diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index 27b7468c0d..da7fcfadc9 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._metrics_batcher import SAMPLE_PER_SECOND_KEY from sentry_sdk.utils import format_attribute if TYPE_CHECKING: @@ -14,6 +15,7 @@ def _capture_metric( value: float, unit: "Optional[str]" = None, attributes: "Optional[Attributes]" = None, + sample_per_second: "Optional[float]" = None, ) -> None: attrs: "Attributes" = {} @@ -32,6 +34,10 @@ def _capture_metric( "attributes": attrs, } + if sample_per_second is not None: + # Only used by the experimental `metrics_window_sampling` option. + metric[SAMPLE_PER_SECOND_KEY] = sample_per_second # type: ignore[literal-required] + sentry_sdk.get_current_scope()._capture_metric(metric) @@ -40,8 +46,9 @@ def count( value: float, unit: "Optional[str]" = None, attributes: "Optional[dict[str, Any]]" = None, + sample_per_second: "Optional[float]" = None, ) -> None: - _capture_metric(name, "counter", value, unit, attributes) + _capture_metric(name, "counter", value, unit, attributes, sample_per_second) def gauge( @@ -49,8 +56,9 @@ def gauge( value: float, unit: "Optional[str]" = None, attributes: "Optional[dict[str, Any]]" = None, + sample_per_second: "Optional[float]" = None, ) -> None: - _capture_metric(name, "gauge", value, unit, attributes) + _capture_metric(name, "gauge", value, unit, attributes, sample_per_second) def distribution( @@ -58,5 +66,6 @@ def distribution( value: float, unit: "Optional[str]" = None, attributes: "Optional[dict[str, Any]]" = None, + sample_per_second: "Optional[float]" = None, ) -> None: - _capture_metric(name, "distribution", value, unit, attributes) + _capture_metric(name, "distribution", value, unit, attributes, sample_per_second) diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 933d878fec..bba7c97859 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -663,3 +663,110 @@ 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 _lost(calls, reason, data_category="trace_metric"): + return sum(q for (r, c, _, q) in calls if r == reason and c == data_category) + + +def test_metrics_window_sampling_off_by_default(sentry_init, capture_items): + sentry_init() + items = capture_items("trace_metric") + + for _ in range(100): + sentry_sdk.metrics.count("test.counter", 1, sample_per_second=1) + + get_client().flush() + metrics = [item.payload for item in items] + + assert len(metrics) == 100 + assert all("sentry.client_sample_rate" not in m["attributes"] for m in metrics) + + +def test_metrics_window_sampling( + sentry_init, capture_items, capture_record_lost_event_calls +): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + lost = capture_record_lost_event_calls() + + # 10/s over the 5s flush window keeps 50 per name. + for _ in range(200): + sentry_sdk.metrics.count("test.hot", 2) + for _ in range(3): + sentry_sdk.metrics.count("test.cold", 1) + for _ in range(200): + sentry_sdk.metrics.count("test.override", 1, sample_per_second=20) + for _ in range(100): + sentry_sdk.metrics.count( + "test.presampled", 1, attributes={"sentry.client_sample_rate": 0.5} + ) + + get_client().flush() + metrics = [item.payload for item in items] + + def by_name(name): + return [m for m in metrics if m["name"] == name] + + hot = by_name("test.hot") + assert len(hot) == 50 + assert all(m["attributes"]["sentry.client_sample_rate"] == 0.25 for m in hot) + # Counts still extrapolate to the real total + assert sum( + m["value"] / m["attributes"]["sentry.client_sample_rate"] for m in hot + ) == pytest.approx(400) + + cold = by_name("test.cold") + assert len(cold) == 3 + assert all("sentry.client_sample_rate" not in m["attributes"] for m in cold) + + override = by_name("test.override") + assert len(override) == 100 + assert all(m["attributes"]["sentry.client_sample_rate"] == 0.5 for m in override) + assert all("_sample_per_second" not in m for m in override) + + presampled = by_name("test.presampled") + assert len(presampled) == 50 + assert all(m["attributes"]["sentry.client_sample_rate"] == 0.25 for m in presampled) + + assert _lost(lost, "sample_rate") == 150 + 100 + 50 + assert _lost(lost, "sample_rate", "trace_metric_byte") > 0 + assert _lost(lost, "backpressure") == 0 + + +def test_metrics_window_sampling_back_pressure( + sentry_init, capture_items, capture_record_lost_event_calls, monkeypatch +): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + lost = capture_record_lost_event_calls() + + batcher = get_client().metrics_batcher + monkeypatch.setattr(batcher, "MAX_BEFORE_FLUSH", 100) + # Flush only when the test says so, to keep windows deterministic. + monkeypatch.setattr(batcher._flush_event, "set", lambda: None) + + def emit(names): + del items[:] + del lost[:] + for name in range(names): + for _ in range(100): + sentry_sdk.metrics.count(f"test.{name}", 1) + get_client().flush() + return [item.payload for item in items] + + # 10 names * 50 hits the flush cap of 100: nothing is pushed down yet. + assert len(emit(10)) == 500 + assert _lost(lost, "backpressure") == 0 + + # Next window every name is halved to 25. + metrics = emit(10) + assert len(metrics) == 250 + assert all(m["attributes"]["sentry.client_sample_rate"] == 0.25 for m in metrics) + assert _lost(lost, "sample_rate") == 500 + assert _lost(lost, "backpressure") == 250 + + # Halved again to 12, which stays under the cap, so the window after + # recovers to 25. + assert len(emit(1)) == 12 + assert len(emit(1)) == 25 From b0fc05efd0f1dc23554b6fa74a12d3ced4af911a Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:41:08 +0000 Subject: [PATCH 2/2] feat(metrics): Add stratify_by to experimental window sampling `stratify_by=[attribute keys]` on count/gauge/distribution splits a metric name's window allowance between strata (distinct values of those attributes) by water-filling: small strata keep every metric and the rest of the allowance goes to the big ones. Each stratum gets its own `sentry.client_sample_rate = kept / seen`, so a rare value is not sampled away by a hot one and counts still extrapolate. A new metric in a stratum that has kept everything so far takes a random slot from the biggest stratum; otherwise it goes through Algorithm R within its stratum. Slots are still replaced in place, so a name never holds more than its allowance in the buffer. Strata are capped at allowance - 1 per name, past that values share an "other" stratum, so every stratum keeps at least one metric. Back pressure, flush, client reports, and fork reset are unchanged. Co-Authored-By: Kevan Fisher --- sentry_sdk/_metrics_batcher.py | 117 ++++++++++++++++++++++++++------- sentry_sdk/metrics.py | 23 +++++-- tests/test_metrics.py | 73 ++++++++++++++++++++ 3 files changed, 185 insertions(+), 28 deletions(-) diff --git a/sentry_sdk/_metrics_batcher.py b/sentry_sdk/_metrics_batcher.py index 0ddbdaf90c..b7fdeb2dc6 100644 --- a/sentry_sdk/_metrics_batcher.py +++ b/sentry_sdk/_metrics_batcher.py @@ -5,7 +5,7 @@ from sentry_sdk.utils import capture_internal_exceptions, serialize_attribute if TYPE_CHECKING: - from typing import Any, Callable, Dict, List, Optional, Tuple, Union + from typing import Any, Callable, Dict, Hashable, List, Optional, Tuple, Union from sentry_sdk._types import Attributes, Metric, MetricWindowSamplingOptions from sentry_sdk.envelope import Envelope @@ -18,22 +18,42 @@ # Private key set by `sentry_sdk.metrics` when the caller passes # `sample_per_second`. It is never serialized (see `_to_transport_format`). SAMPLE_PER_SECOND_KEY = "_sample_per_second" +# Same, for `stratify_by`. +STRATIFY_BY_KEY = "_stratify_by" CLIENT_SAMPLE_RATE_ATTRIBUTE = "sentry.client_sample_rate" +# Stratum for attribute values past a name's stratum cap. +_OTHER_STRATUM = object() + + +class _Stratum: + """One group of a metric name's window, e.g. one `job_type` value.""" + + __slots__ = ("seen", "indices") + + def __init__(self) -> None: + self.seen = 0 + # Positions of this stratum's metrics in the shared buffer. + self.indices: "List[int]" = [] + class _NameWindow: """Per metric name state for the current flush window.""" - __slots__ = ("base_allowance", "allowance", "seen", "indices") + __slots__ = ("base_allowance", "allowance", "stratify_by", "seen", "kept", "strata") - def __init__(self, base_allowance: int, allowance: int) -> None: + def __init__( + self, base_allowance: int, allowance: int, stratify_by: "Tuple[str, ...]" + ) -> None: # What this name asked for: `sample_per_second * FLUSH_WAIT_TIME`. self.base_allowance = base_allowance # What it gets this window, after back pressure. self.allowance = allowance + self.stratify_by = stratify_by self.seen = 0 - # Positions of this name's metrics in the shared buffer. - self.indices: "List[int]" = [] + self.kept = 0 + # Without `stratify_by` there is a single stratum. + self.strata: "Dict[Hashable, _Stratum]" = {} class MetricsBatcher(Batcher["Metric"]): @@ -46,6 +66,15 @@ class MetricsBatcher(Batcher["Metric"]): kept. At flush, kept metrics get `sentry.client_sample_rate = kept / seen` (multiplied into any rate the caller set) so counts extrapolate. + With `stratify_by=[attribute keys]`, the name's allowance is split between + the strata (distinct values of those attributes) by water-filling: small + strata keep every metric, the rest of the allowance goes to the big ones, + and each stratum gets its own `kept / seen` rate. A new metric in a stratum + that has kept everything so far takes a random slot from the biggest + stratum, otherwise it goes through reservoir sampling within its stratum. + Strata are capped at `allowance - 1` per name, past that values share an + "other" stratum, so every stratum keeps at least one metric. + Back pressure: when the buffer reaches `MAX_BEFORE_FLUSH` and flushes early, every name's allowance is halved for the next window. Each window that flushes on the timer doubles it back, up to what was asked for. @@ -106,23 +135,47 @@ def _add_locked(self, item: "Metric") -> bool: pass base_allowance = max(1, int(per_second * self.FLUSH_WAIT_TIME)) window = _NameWindow( - base_allowance, max(1, int(base_allowance * self._pressure)) + base_allowance, + max(1, int(base_allowance * self._pressure)), + tuple(item.get(STRATIFY_BY_KEY) or ()), # type: ignore[arg-type] ) - if len(window.indices) < window.allowance: + key = _stratum_key(item["attributes"], window.stratify_by) + if key not in window.strata and len(window.strata) >= window.allowance - 1: + key = _OTHER_STRATUM + stratum = window.strata.get(key) or _Stratum() + kept = len(stratum.indices) + + if window.kept < window.allowance: if not super()._add_locked(item): return False - window.indices.append(len(self._buffer) - 1) + stratum.indices.append(len(self._buffer) - 1) + window.kept += 1 self._windows[name] = window if len(self._buffer) >= self.MAX_BEFORE_FLUSH: self._hit_flush_cap = True else: - # Algorithm R: replace a kept metric in place, so every metric - # seen in the window has the same allowance / seen chance. - j = random.randrange(window.seen + 1) - if j < window.allowance: - self._buffer[window.indices[j]] = item - + # Only a stratum that has kept everything so far can be under its + # fair share. Once it drops a metric, its share only shrinks. + biggest = stratum + if kept == stratum.seen: + biggest = max(window.strata.values(), key=lambda s: len(s.indices)) + + if kept + 1 < len(biggest.indices): + # Take a random slot from the biggest stratum, which stays a + # uniform sample of its metrics. + slot = biggest.indices.pop(random.randrange(len(biggest.indices))) + self._buffer[slot] = item + stratum.indices.append(slot) + else: + # Algorithm R: replace a kept metric in place, so every metric + # seen in the stratum has the same kept / seen chance. + j = random.randrange(stratum.seen + 1) + if j < kept: + self._buffer[stratum.indices[j]] = item + + window.strata[key] = stratum + stratum.seen += 1 window.seen += 1 return True @@ -135,20 +188,28 @@ def _add_to_envelope(self, envelope: "Envelope") -> None: def _close_window(self) -> None: for window in self._windows.values(): - kept = len(window.indices) - if window.seen <= kept: + if window.seen <= window.kept: continue - rate = kept / window.seen - for index in window.indices: - attributes = self._buffer[index]["attributes"] - attributes[CLIENT_SAMPLE_RATE_ATTRIBUTE] = rate * _existing_rate( - attributes - ) + for stratum in window.strata.values(): + if stratum.seen <= len(stratum.indices): + continue + rate = len(stratum.indices) / stratum.seen + for index in stratum.indices: + attributes = self._buffer[index]["attributes"] + attributes[CLIENT_SAMPLE_RATE_ATTRIBUTE] = rate * _existing_rate( + attributes + ) + + sample = next(s for s in window.strata.values() if s.indices) wanted = min(window.seen, window.base_allowance) self._pending_lost.append( - (self._buffer[window.indices[0]], window.seen - wanted, wanted - kept) + ( + self._buffer[sample.indices[0]], + window.seen - wanted, + wanted - window.kept, + ) ) if self._hit_flush_cap: @@ -219,3 +280,13 @@ def _existing_rate(attributes: "Attributes") -> float: return float(attributes.get(CLIENT_SAMPLE_RATE_ATTRIBUTE, 1.0)) # type: ignore[arg-type] except (TypeError, ValueError): return 1.0 + + +def _stratum_key( + attributes: "Attributes", stratify_by: "Tuple[str, ...]" +) -> "Tuple[Hashable, ...]": + # List attribute values aren't hashable. + return tuple( + tuple(v) if isinstance(v, list) else v + for v in (attributes.get(k) for k in stratify_by) + ) diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index da7fcfadc9..2505936ae6 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -1,8 +1,8 @@ import time -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Optional, Sequence import sentry_sdk -from sentry_sdk._metrics_batcher import SAMPLE_PER_SECOND_KEY +from sentry_sdk._metrics_batcher import SAMPLE_PER_SECOND_KEY, STRATIFY_BY_KEY from sentry_sdk.utils import format_attribute if TYPE_CHECKING: @@ -16,6 +16,7 @@ def _capture_metric( unit: "Optional[str]" = None, attributes: "Optional[Attributes]" = None, sample_per_second: "Optional[float]" = None, + stratify_by: "Optional[Sequence[str]]" = None, ) -> None: attrs: "Attributes" = {} @@ -37,6 +38,9 @@ def _capture_metric( if sample_per_second is not None: # Only used by the experimental `metrics_window_sampling` option. metric[SAMPLE_PER_SECOND_KEY] = sample_per_second # type: ignore[literal-required] + if stratify_by: + # Same, a stratum per distinct value of these attribute keys. + metric[STRATIFY_BY_KEY] = tuple(stratify_by) # type: ignore[literal-required] sentry_sdk.get_current_scope()._capture_metric(metric) @@ -47,8 +51,11 @@ def count( unit: "Optional[str]" = None, attributes: "Optional[dict[str, Any]]" = None, sample_per_second: "Optional[float]" = None, + stratify_by: "Optional[Sequence[str]]" = None, ) -> None: - _capture_metric(name, "counter", value, unit, attributes, sample_per_second) + _capture_metric( + name, "counter", value, unit, attributes, sample_per_second, stratify_by + ) def gauge( @@ -57,8 +64,11 @@ def gauge( unit: "Optional[str]" = None, attributes: "Optional[dict[str, Any]]" = None, sample_per_second: "Optional[float]" = None, + stratify_by: "Optional[Sequence[str]]" = None, ) -> None: - _capture_metric(name, "gauge", value, unit, attributes, sample_per_second) + _capture_metric( + name, "gauge", value, unit, attributes, sample_per_second, stratify_by + ) def distribution( @@ -67,5 +77,8 @@ def distribution( unit: "Optional[str]" = None, attributes: "Optional[dict[str, Any]]" = None, sample_per_second: "Optional[float]" = None, + stratify_by: "Optional[Sequence[str]]" = None, ) -> None: - _capture_metric(name, "distribution", value, unit, attributes, sample_per_second) + _capture_metric( + name, "distribution", value, unit, attributes, sample_per_second, stratify_by + ) diff --git a/tests/test_metrics.py b/tests/test_metrics.py index bba7c97859..9306ceecf2 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -770,3 +770,76 @@ def emit(names): # recovers to 25. assert len(emit(1)) == 12 assert len(emit(1)) == 25 + + +@pytest.mark.parametrize("c_first", [True, False]) +def test_metrics_window_sampling_stratify_by(sentry_init, capture_items, c_first): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + + def emit(job_type, n): + for _ in range(n): + # 2/s over the 5s flush window keeps 10 for the name. + sentry_sdk.metrics.count( + "test.jobs", + 1, + attributes={"job_type": job_type}, + sample_per_second=2, + stratify_by=["job_type"], + ) + + order = [("c", 1000), ("a", 2), ("b", 2)] + for job_type, n in order if c_first else reversed(order): + emit(job_type, n) + + get_client().flush() + metrics = [item.payload for item in items] + assert all("_stratify_by" not in m for m in metrics) + + def by_job_type(job_type): + return [m for m in metrics if m["attributes"]["job_type"] == job_type] + + # Small strata keep everything, the rest of the allowance goes to "c". + for job_type in ("a", "b"): + kept = by_job_type(job_type) + assert len(kept) == 2 + assert all("sentry.client_sample_rate" not in m["attributes"] for m in kept) + + c = by_job_type("c") + assert len(c) == 6 + assert all( + m["attributes"]["sentry.client_sample_rate"] == pytest.approx(0.006) for m in c + ) + assert sum( + 1 / m["attributes"].get("sentry.client_sample_rate", 1) for m in metrics + ) == pytest.approx(1004) + + +def test_metrics_window_sampling_stratify_by_cap(sentry_init, capture_items): + sentry_init(_experiments={"metrics_window_sampling": True}) + items = capture_items("trace_metric") + + # 20 job types, but the name only keeps 10: 9 get their own stratum and + # the rest share one. + for i in range(20): + for _ in range(10): + sentry_sdk.metrics.count( + "test.jobs", + 1, + attributes={"job_type": str(i)}, + sample_per_second=2, + stratify_by=["job_type"], + ) + + get_client().flush() + metrics = [item.payload for item in items] + + rates = { + m["attributes"]["job_type"]: m["attributes"]["sentry.client_sample_rate"] + for m in metrics + } + assert len(metrics) == len(rates) == 10 + for i in range(9): + assert rates.pop(str(i)) == pytest.approx(1 / 10) + # One metric left for the 110 that share the "other" stratum. + assert list(rates.values()) == [pytest.approx(1 / 110)]