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
15 changes: 10 additions & 5 deletions sentry_sdk/_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -137,6 +133,15 @@ def add(self, item: "T") -> None:
finally:
self._active.flag = False

def _add_locked(self, item: "T") -> bool:
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
Expand Down
159 changes: 156 additions & 3 deletions sentry_sdk/_metrics_batcher.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import math
import random
import time
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, logger, 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 Metric, MetricWindowSamplingOptions
from sentry_sdk.envelope import Envelope

DEFAULT_SAMPLE_PER_SECOND = 2
# Matches FLUSH_WAIT_TIME, so each window goes out in one flush
WINDOW_SECONDS = 5.0


class MetricsBatcher(Batcher["Metric"]):
Expand All @@ -18,6 +26,151 @@ 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._default_limit: "Optional[int]" = None
self._name_limits: "Dict[str, int]" = {}
if window_sampling:
options = window_sampling if isinstance(window_sampling, dict) else {}
per_name = options.get("per_name")
if isinstance(per_name, dict):
self._name_limits = {
name: self._parse_limit(rate) for name, rate in per_name.items()
}
if "sample_per_second" in options or not self._name_limits:
self._default_limit = self._parse_limit(
options.get("sample_per_second", DEFAULT_SAMPLE_PER_SECOND)
)
self._sampling = bool(self._name_limits) or self._default_limit is not None

self._reset_sampling_state()
super().__init__(capture_func, record_lost_func)

def _reset_thread_state(self) -> None:
super()._reset_thread_state()
self._reset_sampling_state()

def _reset_sampling_state(self) -> None:
self._window_start = time.monotonic()
self._reservoirs: "Dict[str, List[Metric]]" = {}
self._seen: "Dict[str, int]" = {}
# Reservoirs count against MAX_BEFORE_DROP together with the buffer, so
# memory stays bounded no matter how many names there are
self._held = 0
self._sampled_out: "List[Tuple[Metric, int]]" = []

def _parse_limit(self, value: float) -> int:
try:
rate = float(value)
except (TypeError, ValueError):
rate = math.nan

if not (math.isfinite(rate) and rate > 0):
logger.warning(
"[Metrics] Given window sampling rate is invalid. It must be a positive number. Got %r, using %s instead.",
value,
DEFAULT_SAMPLE_PER_SECOND,
)
rate = DEFAULT_SAMPLE_PER_SECOND

# Never go below 1, so we always keep at least one metric per name to
# extrapolate from
return min(max(1, int(rate * WINDOW_SECONDS)), self.MAX_BEFORE_DROP)

def _add_locked(self, item: "Metric") -> bool:
if not self._sampling:
return super()._add_locked(item)

name = item["name"]
limit = self._name_limits.get(name, self._default_limit)
if limit is None:
if len(self._buffer) + self._held >= self.MAX_BEFORE_DROP:
return False
return super()._add_locked(item)

if time.monotonic() - self._window_start >= WINDOW_SECONDS:
self._close_window()

reservoir = self._reservoirs.setdefault(name, [])
seen = self._seen.get(name, 0) + 1
if len(reservoir) < limit:
# Replacing a slot in a full reservoir doesn't need more memory, only
# a new slot does
if len(self._buffer) + self._held >= self.MAX_BEFORE_DROP:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Window close drops incoming metrics

Medium Severity

Closing a full window copies every reserved metric into _buffer up to MAX_BEFORE_DROP, then the same add still capacity-checks that buffer. The metric that closed the window, and any that arrive before the flusher drains, are discarded as queue_overflow even though that capacity is about to be freed. MAX_BEFORE_FLUSH is meant to leave headroom for this gap, but a window close can fill the buffer to the hard cap in one shot and wipe that headroom out.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c27cfa5. Configure here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty reservoirs bypass memory bound

Medium Severity

A new metric name is inserted into _reservoirs before the MAX_BEFORE_DROP check. When that check fails, the empty list stays in the map and _held never counts it, so unique names arriving while at capacity can grow _reservoirs without bound until the window closes. That breaks the claim that metric memory stays bounded by MAX_BEFORE_DROP.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c27cfa5. Configure here.

reservoir.append(item)
self._held += 1
else:
index = random.randrange(seen)
if index < limit:
reservoir[index] = item
self._seen[name] = seen
return True

def _close_window(self) -> None:
for name, kept in self._reservoirs.items():
seen = self._seen.get(name, 0)
if kept and seen > len(kept):
rate = len(kept) / seen
for item in kept:
attributes = item["attributes"]
client_rate = attributes.get("sentry.client_sample_rate")
if isinstance(client_rate, (int, float)) and 0 < client_rate <= 1:
attributes["sentry.client_sample_rate"] = rate * client_rate

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs a conventions update, sentry.client_sample_rate is defined at the sample rate for a span.

else:
attributes["sentry.client_sample_rate"] = rate
self._sampled_out.append((kept[0], seen - len(kept)))
self._buffer.extend(kept)

self._reservoirs = {}
self._seen = {}
self._held = 0
self._window_start = time.monotonic()
if len(self._buffer) >= self.MAX_BEFORE_FLUSH:
self._flush_event.set()

def flush(self) -> None:
if self._sampling:
with self._lock:
self._close_window()
super().flush()

def _flush(self) -> "Optional[Envelope]":
if not self._sampling:
return super()._flush()

with self._lock:
# Early flushes leave the window open, so a name can't go over its
# rate
if time.monotonic() - self._window_start >= WINDOW_SECONDS:
self._close_window()
sampled_out, self._sampled_out = self._sampled_out, []

envelope = super()._flush()

# Record outside of the lock, since this serializes a metric and every
# add() would wait on it
for item, count in sampled_out:
self._record_lost_func(
reason="sample_rate",
data_category=self.CLIENT_REPORT_TYPE,
quantity=count,
)
# Serializing every sampled out metric would cost as much as we saved
# by sampling, so we estimate from one
with capture_internal_exceptions():
self._record_lost_func(
reason="sample_rate",
data_category="trace_metric_byte",
quantity=count * len(self._to_envelope_item([item]).get_bytes()),
)

return envelope

@staticmethod
def _to_transport_format(item: "Metric") -> "Any":
res = {
Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,12 @@ class DataCollection(TypedDict):
},
)

MetricWindowSamplingOptions = TypedDict(
"MetricWindowSamplingOptions",
{"sample_per_second": float, "per_name": Dict[str, float]},
total=False,
)

SpanJSON = TypedDict(
"SpanJSON",
{
Expand Down
3 changes: 3 additions & 0 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,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 = SpanBatcher(
Expand Down
4 changes: 4 additions & 0 deletions sentry_sdk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class CompressionAlgo(Enum):
IgnoreSpansConfig,
Log,
Metric,
MetricWindowSamplingOptions,
SpanJSON,
TracesSampler,
)
Expand All @@ -73,6 +74,9 @@ class CompressionAlgo(Enum):
"transport_num_pools": Optional[int],
"transport_http2": Optional[bool],
"transport_async": Optional[bool],
"metrics_window_sampling": Optional[
Union[bool, MetricWindowSamplingOptions]
],
},
total=False,
)
Expand Down
Loading
Loading