Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 15 additions & 15 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 🐛
Expand All @@ -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 ✨
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.


Expand Down
61 changes: 44 additions & 17 deletions sentry_sdk/_lock_free_metrics_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Check warning on line 31 in sentry_sdk/_lock_free_metrics_batcher.py

View check run for this annotation

@sentry/warden / warden: code-review

[ZQF-R42] Reentrant metric capture bypasses reservoir replacement after admission (additional location)

If `before_send_metric` emits the same sampled metric, an under-capacity outer admission reserves no slot; the nested capture can fill it, after which the outer `add()` drops the outer metric without a reservoir draw. At a one-item limit this always keeps the nested metric from the pair, biasing the configured random sample.


class _ThreadState:
Expand All @@ -53,6 +55,10 @@
self.number_kept = 0


class _Admitted(threading.local):
window: "Optional[_Window]" = None

Check warning on line 59 in sentry_sdk/_lock_free_metrics_batcher.py

View check run for this annotation

@sentry/warden / warden: code-review

Sampled metrics dropped by before_send are counted twice in client reports

With window sampling enabled for a metric, a `before_send_metric` drop is reported as `before_send` or `callback_error`, then counted again as `sample_rate` during harvest. Client reports therefore overstate the number of lost metrics and misattribute some losses.


class LockFreeMetricsBatcher(Batcher["Metric"]):
MAX_UNSAMPLED_BEFORE_FLUSH = 1000
MAX_UNSAMPLED_BEFORE_DROP = 5_000
Expand All @@ -78,15 +84,17 @@

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]" = {}

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:
Expand Down Expand Up @@ -130,11 +138,6 @@
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:
Expand All @@ -151,27 +154,50 @@
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

Check warning on line 170 in sentry_sdk/_lock_free_metrics_batcher.py

View check run for this annotation

@sentry/warden / warden: code-review

Reentrant metric capture bypasses reservoir replacement after admission

If `before_send_metric` emits the same sampled metric, an under-capacity outer admission reserves no slot; the nested capture can fill it, after which the outer `add()` drops the outer metric without a reservoir draw. At a one-item limit this always keeps the nested metric from the pair, biasing the configured random sample.

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()
Expand Down Expand Up @@ -237,6 +263,7 @@
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():
Expand Down
9 changes: 9 additions & 0 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion sentry_sdk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2066,4 +2066,4 @@ def _get_default_options() -> "dict[str, Any]":
del _get_default_options


VERSION = "3.0.1b2"
VERSION = "3.1.0b1"
8 changes: 7 additions & 1 deletion sentry_sdk/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -15,6 +16,11 @@
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

Check warning on line 22 in sentry_sdk/metrics.py

View check run for this annotation

@sentry/warden / warden: code-review

[LGS-ZUM] Sampled metrics dropped by before_send are counted twice in client reports (additional location)

With window sampling enabled for a metric, a `before_send_metric` drop is reported as `before_send` or `callback_error`, then counted again as `sample_rate` during harvest. Client reports therefore overstate the number of lost metrics and misattribute some losses.

attrs: "Attributes" = {}

if attributes:
Expand All @@ -32,7 +38,7 @@
"attributes": attrs,
}

sentry_sdk.get_current_scope()._capture_metric(metric)
scope._capture_metric(metric)


def count(
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
23 changes: 23 additions & 0 deletions tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading