Skip to content
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
36694ec
feat: Add basic lock-free metrics batcher
alexander-alderman-webb Nov 18, 2026
9434dbb
chore: Reset batchers at fork from client
alexander-alderman-webb Nov 18, 2026
e6fdd6c
merge
alexander-alderman-webb Nov 18, 2026
2f854bc
remove register_at_fork remnants
alexander-alderman-webb Nov 18, 2026
868f23f
use single consumer
alexander-alderman-webb Nov 18, 2026
bc3dd79
use sentinels
alexander-alderman-webb Nov 18, 2026
d8c36a2
simplify tests
alexander-alderman-webb Nov 18, 2026
cd895eb
Merge branch 'webb/deduplicate-register-at-fork' into webb/sliding-wi…
alexander-alderman-webb Nov 18, 2026
fb7b724
restore uv.lock
alexander-alderman-webb Nov 18, 2026
8d305c0
Merge branch 'webb/deduplicate-register-at-fork' into webb/sliding-wi…
alexander-alderman-webb Nov 18, 2026
d0f0830
simplify
alexander-alderman-webb Nov 18, 2026
551c0f0
remove active flag
alexander-alderman-webb Nov 18, 2026
66b78ac
simplify further
alexander-alderman-webb Nov 18, 2026
921e3e7
clean up types
alexander-alderman-webb Nov 18, 2026
35804f1
fix comments
alexander-alderman-webb Nov 18, 2026
b9ca918
remove comment
alexander-alderman-webb Nov 18, 2026
99b7be1
remove comments
alexander-alderman-webb Nov 18, 2026
c39a589
use superclass
alexander-alderman-webb Nov 19, 2026
41bf46c
drop client-owned register_at_fork changes
alexander-alderman-webb Nov 19, 2026
721094c
remove redundant capture_internal_exceptions()
alexander-alderman-webb Nov 20, 2026
c97978e
Merge branch 'webb/lock-free-base' into webb/sliding-window-metrics-b…
alexander-alderman-webb Nov 23, 2026
3fececf
Merge branch 'webb/lock-free-base' into webb/sliding-window-metrics-b…
alexander-alderman-webb Nov 23, 2026
d3a620e
check self._active flag
alexander-alderman-webb Nov 23, 2026
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
138 changes: 138 additions & 0 deletions sentry_sdk/_lock_free_metrics_batcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import os
import threading
from collections import deque
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from sentry_sdk._batcher import Batcher
from sentry_sdk.envelope import Envelope
from sentry_sdk.utils import (
format_timestamp,
serialize_attribute,
)

if TYPE_CHECKING:
from typing import Any, Callable, Optional

from sentry_sdk._types import Metric


class LockFreeMetricsBatcher(Batcher["Metric"]):
MAX_BEFORE_FLUSH = 1000
MAX_BEFORE_DROP = 10_000
FLUSH_WAIT_TIME = 5.0

TYPE = "trace_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]",
) -> None:
super().__init__(capture_func, record_lost_func)
self._queue: "deque[Metric]" = deque()
# 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._flusher_claim = {}

def _ensure_thread(self) -> bool:
"""For forking processes we might need to restart this thread.
This ensures that our process actually has that thread running.
"""
if not self._running:
return False

pid = os.getpid()
if self._flusher_pid == pid:
return True

# dict.setdefault is atomic, so exactly one thread gets to start the flusher.
claim = object()
if self._flusher_claim.setdefault("flusher", claim) is not claim:
Comment on lines +55 to +57

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.

TIL of this setdefault hack

return True
Comment thread
alexander-alderman-webb marked this conversation as resolved.
Resolved

flusher = threading.Thread(target=self._flush_loop)
flusher.daemon = True
try:
flusher.start()
except RuntimeError:
# Unfortunately at this point the interpreter is in a state that no
# longer allows us to spawn a thread and we have to bail.
self._running = False
return False

self._flusher = flusher
self._flusher_pid = pid
return True

def add(self, item: "Metric") -> None:
# Bail out if the current thread is already executing batcher code.
if getattr(self._active, "flag", False):
return None

self._active.flag = True
try:
if not self._ensure_thread():
return None

queue = self._queue
if len(queue) >= self.MAX_BEFORE_DROP:
self._record_lost(item)
return None

queue.append(item)
if len(queue) < self.MAX_BEFORE_FLUSH or self._flush_event.is_set():
return

self._flush_event.set()
finally:
self._active.flag = False

def _flush(self) -> "Optional[Envelope]":
queue = self._queue
items: "list[Metric]" = []
# Only take what's queued now. Producers can keep enqueuing (no locks).
for _ in range(len(queue)):
try:
items.append(queue.popleft())
except IndexError:
break

if not items:
return None

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

@staticmethod
def _to_transport_format(item: "Metric") -> "Any":
res = {
"timestamp": item["timestamp"],
"name": item["name"],
"type": item["type"],
"value": item["value"],
"attributes": {
k: serialize_attribute(v) for (k, v) in item["attributes"].items()
},
}

if item.get("trace_id") is not None:
res["trace_id"] = item["trace_id"]

if item.get("span_id") is not None:
res["span_id"] = item["span_id"]

if item.get("unit") is not None:
res["unit"] = item["unit"]

return res
Loading