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
64 changes: 43 additions & 21 deletions sentry_sdk/_lock_free_metrics_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ class _Window:
Only the thread with the given identifier should change its local state.
"""

__slots__ = ("start", "threads", "retire_claims", "number_kept")
__slots__ = ("limits", "start", "threads", "retire_claims", "number_kept")

def __init__(self) -> None:
def __init__(self, limits: "dict[str, int]") -> None:
self.limits = limits
self.start = time.monotonic()
self.threads: "defaultdict[int, _ThreadState]" = defaultdict(_ThreadState)
self.retire_claims: "list[object]" = []
Expand All @@ -57,6 +58,7 @@ def __init__(self) -> None:

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


class LockFreeMetricsBatcher(Batcher["Metric"]):
Expand All @@ -77,13 +79,18 @@ def __init__(
) -> None:
super().__init__(capture_func, record_lost_func)

self._limits = {
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._queue: "deque[Metric]" = deque()
self._window = _Window()
self._window = _Window(self._limits)
self._trace_connected_window = _Window(self._trace_connected_limits)
self._admitted = _Admitted()
self._retired: "deque[_Window]" = deque(maxlen=20)
# Holds the claim of the one thread that gets to start the flusher.
Expand All @@ -92,7 +99,8 @@ def __init__(
def _reset_thread_state(self) -> None:
super()._reset_thread_state()
self._queue = deque()
self._window = _Window()
self._window = _Window(self._limits)
self._trace_connected_window = _Window(self._trace_connected_limits)
self._admitted = _Admitted()
self._retired = deque(maxlen=20)
self._flusher_claim = {}
Expand Down Expand Up @@ -138,8 +146,7 @@ def add(self, item: "Metric") -> None:
if not self._ensure_thread():
return None

limit = self._limits.get(item["name"])
if limit is None:
if item["name"] not in self._limits:
if len(self._queue) >= self.MAX_UNSAMPLED_BEFORE_DROP:
self._record_lost(item)
return None
Expand All @@ -158,6 +165,7 @@ def add(self, item: "Metric") -> None:
if window is None:
return

limit = window.limits[item["name"]]
reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]]
if (
len(reservoir.kept) < limit
Expand All @@ -170,20 +178,21 @@ def add(self, item: "Metric") -> None:
reservoir.index = None

if time.monotonic() - window.start >= self.FLUSH_WAIT_TIME:
self._retire_window(window)
self._retire_window(window, self._admitted.with_sampled_span)
finally:
self._active.flag = False

def admit(self, name: str) -> bool:
def admit(self, name: str, with_sampled_span: bool = False) -> bool:
"""
Count a captured metric and decide whether window sampling keeps it.
"""
limit = self._limits.get(name)
if limit is None:
if name not in self._limits:
return True

window = self._window
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 (
Expand All @@ -199,20 +208,24 @@ def admit(self, name: str) -> bool:
reservoir.index = index
return True

def _retire_window(self, window: "_Window") -> None:
def _retire_window(self, window: "_Window", with_sampled_span: bool) -> None:
claim = object()
window.retire_claims.append(claim)
if window.retire_claims[0] is not claim:
return

self._window = _Window()
if with_sampled_span:
self._trace_connected_window = _Window(self._trace_connected_limits)
else:
self._window = _Window(self._limits)
self._retired.append(window)

def flush(self) -> None:
self._retire_window(self._window)
self._retire_window(self._window, with_sampled_span=False)
self._retire_window(self._trace_connected_window, with_sampled_span=True)
super().flush()

def _flush(self) -> "Optional[Envelope]":
def _flush(self) -> None:
queue = self._queue
items: "list[Metric]" = []
# Only take what's queued now. Producers can keep enqueuing (no locks).
Expand All @@ -222,12 +235,18 @@ def _flush(self) -> "Optional[Envelope]":
except IndexError:
break

self._send(items)

sampled_out = 0

now = time.monotonic()
window = self._window
if now - window.start >= self.FLUSH_WAIT_TIME:
self._retire_window(window)
self._retire_window(window, with_sampled_span=False)

window = self._trace_connected_window
if now - window.start >= self.FLUSH_WAIT_TIME:
self._retire_window(window, with_sampled_span=True)

for window in self._retired.copy():
if (
Expand All @@ -239,7 +258,10 @@ def _flush(self) -> "Optional[Envelope]":
window = self._retired.popleft()
except IndexError:
break
sampled_out += self._harvest(window, items)

window_items: "list[Metric]" = []
sampled_out += self._harvest(window, window_items)
self._send(window_items)

if sampled_out:
self._record_lost_func(
Expand All @@ -248,15 +270,15 @@ def _flush(self) -> "Optional[Envelope]":
quantity=sampled_out,
)

def _send(self, items: "list[Metric]") -> None:
if not items:
return None
return

envelope = Envelope(
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))}
)
envelope.add_item(self._to_envelope_item(items))
self._capture_func(envelope)
return envelope

def _harvest(self, window: "_Window", items: "list[Metric]") -> int:
by_name: "dict[str, list[_Reservoir]]" = {}
Expand All @@ -267,7 +289,7 @@ def _harvest(self, window: "_Window", items: "list[Metric]") -> int:

sampled_out = 0
for name, reservoirs in by_name.items():
limit = self._limits[name]
limit = window.limits[name]
bounds = list(
itertools.accumulate(reservoir.seen for reservoir in reservoirs)
)
Expand Down
4 changes: 2 additions & 2 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]":
)
continue

clamped = min(max(rate, 0.2), 1000)
clamped = min(max(rate, 0.4), 1000)
if clamped != rate:
logger.warning(
"[Metrics] metrics_target_per_second for %s must be between 0.2 and 1000. Got %s, using %s.",
"[Metrics] metrics_target_per_second for %s must be between 0.4 and 1000. Got %s, using %s.",
name,
rate,
clamped,
Expand Down
10 changes: 8 additions & 2 deletions sentry_sdk/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import sentry_sdk
from sentry_sdk._lock_free_metrics_batcher import LockFreeMetricsBatcher
from sentry_sdk.traces import NoOpSpan
from sentry_sdk.utils import format_attribute

if TYPE_CHECKING:
Expand All @@ -18,8 +19,13 @@ def _capture_metric(
) -> None:
scope = sentry_sdk.get_current_scope()
batcher = scope.get_client().metrics_batcher
if isinstance(batcher, LockFreeMetricsBatcher) and not batcher.admit(name):
return
if isinstance(batcher, LockFreeMetricsBatcher):
span = scope.span
if not batcher.admit(
name=name,
with_sampled_span=span is not None and not isinstance(span, NoOpSpan),
):
return

attrs: "Attributes" = {}

Expand Down
104 changes: 70 additions & 34 deletions tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,18 +287,23 @@ 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):
@pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0])
def test_metrics_before_send_unsupported_edit(
sentry_init, traces_sample_rate, capture_items
):
def _before_metric(record, hint):
record["name"] = "test.renamed"
return record

sentry_init(
traces_sample_rate=traces_sample_rate,
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)
with sentry_sdk.start_span(name="test-span"):
sentry_sdk.metrics.count("test.original", 1)

get_client().flush()

Expand Down Expand Up @@ -599,82 +604,113 @@ def before_send_metric(metric, _):
get_client().flush()


@pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0])
def test_metrics_window_sampling(
sentry_init, capture_items, capture_record_lost_event_calls
sentry_init, traces_sample_rate, capture_items, capture_record_lost_event_calls
):
sentry_init(
_experiments={"metrics_target_per_second": {"test.hot": 1.5, "test.cold": 2}}
traces_sample_rate=traces_sample_rate,
_experiments={"metrics_target_per_second": {"test.hot": 1.5, "test.cold": 2}},
)
items = capture_items("trace_metric")
record_lost_event_calls = capture_record_lost_event_calls()

for _ in range(200):
sentry_sdk.metrics.count(
"test.hot", 1, attributes={"sentry.client_sample_rate": 0.5}
)
for _ in range(3):
sentry_sdk.metrics.count("test.cold", 1)
with sentry_sdk.start_span(name="test-span"):
for _ in range(200):
sentry_sdk.metrics.count(
"test.hot", 1, attributes={"sentry.client_sample_rate": 0.5}
)
for _ in range(3):
sentry_sdk.metrics.count("test.cold", 1)

get_client().flush()

metrics = [item.payload for item in items]

hot = [metric for metric in metrics if metric["name"] == "test.hot"]
assert len(hot) == 7
kept = 4 if traces_sample_rate else 3
assert len(hot) == kept
for metric in hot:
assert metric["attributes"]["sentry.client_sample_rate"] == 7 / 200 * 0.5
assert metric["attributes"]["sentry.client_sample_rate"] == kept / 200 * 0.5

cold = [metric for metric in metrics if metric["name"] == "test.cold"]
assert len(cold) == 3

assert record_lost_event_calls == [
("sample_rate", "trace_metric", None, 193),
assert [call for call in record_lost_event_calls if call[1] == "trace_metric"] == [
("sample_rate", "trace_metric", None, 200 - kept),
]


def test_metrics_window_sampling_new_window(sentry_init, capture_items):
sentry_init(_experiments={"metrics_target_per_second": {"test.counter": 2}})
@pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0])
def test_metrics_window_sampling_new_window(
sentry_init, traces_sample_rate, capture_items
):
sentry_init(
traces_sample_rate=traces_sample_rate,
_experiments={"metrics_target_per_second": {"test.counter": 2}},
)
items = capture_items("trace_metric")

for count in (30, 50):
for _ in range(count):
sentry_sdk.metrics.count("test.counter", 1)
with sentry_sdk.start_span(name="test-span"):
for _ in range(count):
sentry_sdk.metrics.count("test.counter", 1)
get_client().flush()

metrics = [item.payload for item in items]
assert len(metrics) == 10
assert len(metrics) == 5
for metric in metrics:
assert metric["attributes"]["sentry.client_sample_rate"] == 10 / count
assert metric["attributes"]["sentry.client_sample_rate"] == 5 / count

items.clear()


@pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0])
def test_metrics_window_sampling_drops_after_max_reached(
sentry_init, capture_items, capture_record_lost_event_calls
sentry_init,
traces_sample_rate,
capture_items,
capture_record_lost_event_calls,
):
sentry_init(
traces_sample_rate=traces_sample_rate,
_experiments={
"metrics_target_per_second": {"test.sampled": 1000, "test.late": 2}
}
"metrics_target_per_second": {
"test.a": 1000,
"test.b": 1000,
"test.late": 2,
}
},
)
items = capture_items("trace_metric")
record_lost_event_calls = capture_record_lost_event_calls()

for _ in range(5_020):
sentry_sdk.metrics.count("test.sampled", 1)
for _ in range(5):
sentry_sdk.metrics.count("test.late", 1)
for name in ("test.a", "test.b"):
for _ in range(2_510):
sentry_sdk.metrics.count(name, 1)
with sentry_sdk.start_span(name="test-span"):
for _ in range(5):
sentry_sdk.metrics.count("test.late", 1)

get_client().flush()

metrics = [item.payload for item in items]
assert len(metrics) == 5_000
for metric in metrics:
assert metric["name"] == "test.sampled"
assert metric["attributes"]["sentry.client_sample_rate"] == 5_000 / 5_020

assert record_lost_event_calls == [
("sample_rate", "trace_metric", None, 25),
for name in ("test.a", "test.b"):
sampled = [metric for metric in metrics if metric["name"] == name]
assert len(sampled) == 2_500
for metric in sampled:
assert metric["attributes"]["sentry.client_sample_rate"] == 2_500 / 2_510

late = [metric for metric in metrics if metric["name"] == "test.late"]
if traces_sample_rate:
assert len(late) == 5
lost = 20
else:
assert not late
lost = 25

assert [call for call in record_lost_event_calls if call[1] == "trace_metric"] == [
("sample_rate", "trace_metric", None, lost),
]


Expand Down
Loading