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..b7fdeb2dc6 100644 --- a/sentry_sdk/_metrics_batcher.py +++ b/sentry_sdk/_metrics_batcher.py @@ -1,15 +1,90 @@ +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, Hashable, 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" +# 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", "stratify_by", "seen", "kept", "strata") + + 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 + self.kept = 0 + # Without `stratify_by` there is a single stratum. + self.strata: "Dict[Hashable, _Stratum]" = {} 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. + + 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. + 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 +93,164 @@ 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)), + tuple(item.get(STRATIFY_BY_KEY) or ()), # type: ignore[arg-type] + ) + + 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 + 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: + # 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 + + 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(): + if window.seen <= window.kept: + continue + + 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[sample.indices[0]], + window.seen - wanted, + wanted - window.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 +273,20 @@ 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 + + +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/_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..2505936ae6 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -1,7 +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, STRATIFY_BY_KEY from sentry_sdk.utils import format_attribute if TYPE_CHECKING: @@ -14,6 +15,8 @@ def _capture_metric( value: float, unit: "Optional[str]" = None, attributes: "Optional[Attributes]" = None, + sample_per_second: "Optional[float]" = None, + stratify_by: "Optional[Sequence[str]]" = None, ) -> None: attrs: "Attributes" = {} @@ -32,6 +35,13 @@ 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] + 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) @@ -40,8 +50,12 @@ def count( value: float, 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) + _capture_metric( + name, "counter", value, unit, attributes, sample_per_second, stratify_by + ) def gauge( @@ -49,8 +63,12 @@ def gauge( value: float, 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) + _capture_metric( + name, "gauge", value, unit, attributes, sample_per_second, stratify_by + ) def distribution( @@ -58,5 +76,9 @@ def distribution( value: float, 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) + _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 933d878fec..9306ceecf2 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -663,3 +663,183 @@ 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 + + +@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)]