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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# Changelog

## 3.1.0b2

### New Features ✨

- Window sample all metrics with `metrics_target_per_second=True` by @alexander-alderman-webb in [#8428](https://github.com/getsentry/sentry-python/pull/8428)
- Dual window for metrics with sampled spans by @alexander-alderman-webb in [#8427](https://github.com/getsentry/sentry-python/pull/8427)

### Internal Changes 🔧

- (metrics) Drop negatively sampled metrics immediately by @alexander-alderman-webb with @sentry-release-bot in [#8425](https://github.com/getsentry/sentry-python/pull/8425)

## 3.1.0b1

### 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.1.0b1"
release = "3.1.0b2"
version = ".".join(release.split(".")[:2]) # The short X.Y version.


Expand Down
73 changes: 53 additions & 20 deletions sentry_sdk/_lock_free_metrics_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@
)

if TYPE_CHECKING:
from typing import Any, Callable, Optional
from typing import Any, Callable, Optional, Union

from sentry_sdk._types import Metric

DEFAULT_TARGET_PER_SECOND = 0.4


class _Reservoir:
__slots__ = ("kept", "seen", "index")
Expand All @@ -46,10 +48,20 @@ class _Window:
Only the thread with the given identifier should change its local state.
"""

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

def __init__(self, limits: "dict[str, int]") -> None:
def __init__(
self, limits: "dict[str, int]", default_limit: "Optional[int]"
) -> None:
self.limits = limits
self.default_limit = default_limit
self.start = time.monotonic()
self.threads: "defaultdict[int, _ThreadState]" = defaultdict(_ThreadState)
self.retire_claims: "list[object]" = []
Expand All @@ -75,22 +87,33 @@ def __init__(
self,
capture_func: "Callable[[Envelope], None]",
record_lost_func: "Callable[..., None]",
window_sampling: "dict[str, float]",
window_sampling: "Union[bool, dict[str, float]]",
) -> None:
super().__init__(capture_func, record_lost_func)

limits = {
name: int(rate * self.FLUSH_WAIT_TIME)
for name, rate in window_sampling.items()
}
limits = {}
default_limit = None
if window_sampling is True:
default_limit = int(DEFAULT_TARGET_PER_SECOND * self.FLUSH_WAIT_TIME)
elif isinstance(window_sampling, dict):
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._default_limit = None if default_limit is None else default_limit // 2
self._trace_connected_default_limit = (
None if default_limit is None else (default_limit + 1) // 2
)

self._queue: "deque[Metric]" = deque()
self._window = _Window(self._limits)
self._trace_connected_window = _Window(self._trace_connected_limits)
self._window = _Window(self._limits, self._default_limit)
self._trace_connected_window = _Window(
self._trace_connected_limits, self._trace_connected_default_limit
)
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 @@ -99,8 +122,10 @@ def __init__(
def _reset_thread_state(self) -> None:
super()._reset_thread_state()
self._queue = deque()
self._window = _Window(self._limits)
self._trace_connected_window = _Window(self._trace_connected_limits)
self._window = _Window(self._limits, self._default_limit)
self._trace_connected_window = _Window(
self._trace_connected_limits, self._trace_connected_default_limit
)
self._admitted = _Admitted()
self._retired = deque(maxlen=20)
self._flusher_claim = {}
Expand Down Expand Up @@ -146,7 +171,7 @@ def add(self, item: "Metric") -> None:
if not self._ensure_thread():
return None

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

limit = window.limits[item["name"]]
limit = window.limits.get(item["name"], window.default_limit)
if limit is None:
return

reservoir = window.threads[threading.get_ident()].reservoirs[item["name"]]
if (
len(reservoir.kept) < limit
Expand All @@ -186,13 +214,13 @@ def admit(self, name: str, with_sampled_span: bool = False) -> bool:
"""
Count a captured metric and decide whether window sampling keeps it.
"""
if name not in self._limits:
window = self._trace_connected_window if with_sampled_span else self._window
limit = window.limits.get(name, window.default_limit)
if limit is None:
return True

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 @@ -215,9 +243,11 @@ def _retire_window(self, window: "_Window", with_sampled_span: bool) -> None:
return

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

def flush(self) -> None:
Expand Down Expand Up @@ -289,7 +319,10 @@ def _harvest(self, window: "_Window", items: "list[Metric]") -> int:

sampled_out = 0
for name, reservoirs in by_name.items():
limit = window.limits[name]
limit = window.limits.get(name, window.default_limit)
if limit is None:
continue

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 @@ -131,7 +131,7 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]":
rv["data_collection"] = _resolve_data_collection(rv)

window_sampling = rv["_experiments"].get("metrics_target_per_second")
if window_sampling is not None:
if window_sampling is not None and window_sampling is not True:
valid_rates = {}
if isinstance(window_sampling, dict):
for name, rate in window_sampling.items():
Expand Down Expand Up @@ -159,7 +159,7 @@ def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]":
valid_rates[name] = clamped
else:
logger.warning(
"[Metrics] metrics_target_per_second must map metric names to metrics per second. Got %s, not sampling.",
"[Metrics] metrics_target_per_second must be True or map metric names to metrics per second. Got %s, not sampling.",
window_sampling,
)
rv["_experiments"] = {
Expand Down
6 changes: 4 additions & 2 deletions sentry_sdk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ class CompressionAlgo(Enum):
"transport_num_pools": Optional[int],
"transport_http2": Optional[bool],
"transport_async": Optional[bool],
"metrics_target_per_second": Optional[Dict[str, float]],
"metrics_target_per_second": Optional[
Union[Literal[True], Dict[str, float]]
],
},
total=False,
)
Expand Down Expand Up @@ -2066,4 +2068,4 @@ def _get_default_options() -> "dict[str, Any]":
del _get_default_options


VERSION = "3.1.0b1"
VERSION = "3.1.0b2"
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.1.0b1",
version="3.1.0b2",
author="Sentry Team and Contributors",
author_email="hello@sentry.io",
url="https://github.com/getsentry/sentry-python",
Expand Down
31 changes: 31 additions & 0 deletions tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,37 @@ def test_metrics_window_sampling(
]


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

for name in ("test.a", "test.b"):
for _ in range(50):
sentry_sdk.metrics.count(name, 1)
with sentry_sdk.start_span(name="test-span"):
for _ in range(50):
sentry_sdk.metrics.count(name, 1)

get_client().flush()

for name in ("test.a", "test.b"):
metrics = [item.payload for item in items if item.payload["name"] == name]
if traces_sample_rate:
assert sorted("span_id" in metric for metric in metrics) == [False, True]
rate = 1 / 50
else:
assert len(metrics) == 1
rate = 1 / 100
for metric in metrics:
assert metric["attributes"]["sentry.client_sample_rate"] == rate


@pytest.mark.parametrize("traces_sample_rate", [0.0, 1.0])
def test_metrics_window_sampling_new_window(
sentry_init, traces_sample_rate, capture_items
Expand Down
Loading