diff --git a/CHANGELOG.md b/CHANGELOG.md index 9abdd479f4..4a348ad25f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 3.1.0b1 + +### New Features ✨ + +- Add per-metric windows to lock free metrics batcher by @alexander-alderman-webb with @sentry-release-bot in [#8327](https://github.com/getsentry/sentry-python/pull/8327) +- Add basic lock-free metrics batcher by @alexander-alderman-webb and @claude in [#8326](https://github.com/getsentry/sentry-python/pull/8326) + +### Internal Changes 🔧 + +- (deps) Lock file maintenance by @renovate in [#8421](https://github.com/getsentry/sentry-python/pull/8421) +- (mcp) Remove unused \_extract_tool_result_content helper by @sentry-junior in [#8422](https://github.com/getsentry/sentry-python/pull/8422) +- (metrics) Drop negatively sampled metrics immediately by @alexander-alderman-webb in [#8425](https://github.com/getsentry/sentry-python/pull/8425) +- Update contributing guidelines by @sentrivana in [#8424](https://github.com/getsentry/sentry-python/pull/8424) +- Move locks into batcher subclasses by @alexander-alderman-webb in [#8325](https://github.com/getsentry/sentry-python/pull/8325) + ## 3.0.2 ### Bug Fixes 🐛 @@ -15,21 +30,6 @@ - (deps) Update getsentry/craft action to v3.14.1 by @renovate in [#8398](https://github.com/getsentry/sentry-python/pull/8398) - (dev) Replace pre-commit with prek by @joshuarli in [#8354](https://github.com/getsentry/sentry-python/pull/8354) -## 3.0.1b2 - -### New Features ✨ - -- Add per-metric windows to lock free metrics batcher by @alexander-alderman-webb with @sentry-release-bot in [#8327](https://github.com/getsentry/sentry-python/pull/8327) -- Add basic lock-free metrics batcher by @alexander-alderman-webb and @claude in [#8326](https://github.com/getsentry/sentry-python/pull/8326) - -### Internal Changes 🔧 - -- Move locks into batcher subclasses by @alexander-alderman-webb in [#8325](https://github.com/getsentry/sentry-python/pull/8325) - -## 3.0.1b1 - -- No documented changes. - ## 3.0.1 ### New Features ✨ diff --git a/docs/conf.py b/docs/conf.py index fbaf1f7982..3ebef6f09e 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.0.1b2" +release = "3.1.0b1" 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 67bca818fd..46f9ab1cfd 100644 --- a/sentry_sdk/_lock_free_metrics_batcher.py +++ b/sentry_sdk/_lock_free_metrics_batcher.py @@ -22,11 +22,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: @@ -53,6 +55,10 @@ def __init__(self) -> None: self.number_kept = 0 +class _Admitted(threading.local): + window: "Optional[_Window]" = None + + class LockFreeMetricsBatcher(Batcher["Metric"]): MAX_UNSAMPLED_BEFORE_FLUSH = 1000 MAX_UNSAMPLED_BEFORE_DROP = 5_000 @@ -78,7 +84,8 @@ def __init__( self._queue: "deque[Metric]" = deque() self._window = _Window() - self._retired: "deque[_Window]" = deque() + 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]" = {} @@ -86,7 +93,8 @@ def _reset_thread_state(self) -> None: super()._reset_thread_state() self._queue = deque() self._window = _Window() - self._retired = deque() + self._admitted = _Admitted() + self._retired = deque(maxlen=20) self._flusher_claim = {} def _ensure_thread(self) -> bool: @@ -130,11 +138,6 @@ def add(self, item: "Metric") -> None: if not self._ensure_thread(): return None - window = self._window - if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME: - self._retire_window(window) - window = self._window - limit = self._limits.get(item["name"]) if limit is None: if len(self._queue) >= self.MAX_UNSAMPLED_BEFORE_DROP: @@ -151,27 +154,50 @@ def add(self, item: "Metric") -> None: self._flush_event.set() return - self._add_to_window(item, window, limit) + window = self._admitted.window + if window is None: + return + + reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]] + if ( + len(reservoir.kept) < limit + and window.number_kept < self.MAX_KEPT_PER_WINDOW + ): + window.number_kept += 1 + reservoir.kept.append(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) finally: self._active.flag = False - def _add_to_window(self, item: "Metric", window: "_Window", limit: int) -> None: - state = window.threads[threading.get_ident()] - reservoir = state.reservoirs[item["name"]] + def admit(self, name: str) -> bool: + """ + Count a captured metric and decide whether window sampling keeps it. + """ + limit = self._limits.get(name) + if limit is None: + return True + + window = self._window + self._admitted.window = window + 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 ): - window.number_kept += 1 - reservoir.kept.append(item) - return + return True index = random.randrange(reservoir.seen) if index >= len(reservoir.kept): - return + return False - reservoir.kept[index] = item + reservoir.index = index + return True def _retire_window(self, window: "_Window") -> None: claim = object() @@ -237,6 +263,7 @@ def _harvest(self, window: "_Window", items: "list[Metric]") -> int: for state in window.threads.copy().values(): for name, reservoir in state.reservoirs.copy().items(): by_name.setdefault(name, []).append(reservoir) + window.threads.clear() sampled_out = 0 for name, reservoirs in by_name.items(): diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 24b3a2986e..a98f4b74d8 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -862,6 +862,7 @@ def _capture_telemetry( scope.apply_to_telemetry(telemetry) before_send = None + metric_name = None if ty == "log": before_send = get_before_send_log(self.options) @@ -870,6 +871,8 @@ def _capture_telemetry( elif ty == "metric": before_send = get_before_send_metric(self.options) serialized = telemetry + if self.options["_experiments"].get("metrics_target_per_second"): + metric_name = telemetry["name"] # type: ignore[index, typeddict-item] elif ty == "span": before_send = get_before_send_span(self.options) @@ -891,6 +894,12 @@ def _capture_telemetry( if serialized is None: self._record_lost_telemetry("before_send", ty, telemetry) # type: ignore[arg-type] return + if metric_name is not None and serialized.get("name") != metric_name: + logger.debug( + "[Metrics] Changing the metric name in before_send_metric is not supported when metrics_target_per_second is set. Keeping the original name %s.", + metric_name, + ) + serialized["name"] = metric_name # type: ignore[typeddict-unknown-key] elif ty == "span" and isinstance(telemetry, Span): # Reset the span to its original value before we attempted diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 1006c44777..9722fba427 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -2066,4 +2066,4 @@ def _get_default_options() -> "dict[str, Any]": del _get_default_options -VERSION = "3.0.1b2" +VERSION = "3.1.0b1" diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index 27b7468c0d..9c1b530e15 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._lock_free_metrics_batcher import LockFreeMetricsBatcher from sentry_sdk.utils import format_attribute if TYPE_CHECKING: @@ -15,6 +16,11 @@ def _capture_metric( unit: "Optional[str]" = None, attributes: "Optional[Attributes]" = None, ) -> None: + scope = sentry_sdk.get_current_scope() + batcher = scope.get_client().metrics_batcher + if isinstance(batcher, LockFreeMetricsBatcher) and not batcher.admit(name): + return + attrs: "Attributes" = {} if attributes: @@ -32,7 +38,7 @@ def _capture_metric( "attributes": attrs, } - sentry_sdk.get_current_scope()._capture_metric(metric) + scope._capture_metric(metric) def count( diff --git a/setup.py b/setup.py index 18ee209715..8000f1aefb 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ def get_file_text(file_name): setup( name="sentry-sdk", - version="3.0.1b2", + version="3.1.0b1", 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 0777845d9e..70a29fe732 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -287,6 +287,29 @@ def _before_metric(record, hint): assert item.payload.json["items"][0]["name"] == "test.drop" +def test_metrics_before_send_unsupported_edit(sentry_init, capture_items): + def _before_metric(record, hint): + record["name"] = "test.renamed" + return record + + sentry_init( + before_send_metric=_before_metric, + _experiments={"metrics_target_per_second": {"test.original": 2}}, + ) + items = capture_items("trace_metric") + + sentry_sdk.metrics.count("test.original", 1) + + get_client().flush() + + metrics = [item.payload for item in items] + + assert len(metrics) == 1 + (metric,) = metrics + + assert metric["name"] == "test.original" + + @pytest.mark.parametrize("window_sampling", [None, {"test.sampled": 2}]) def test_transport_format(sentry_init, window_sampling, capture_envelopes): sentry_init(