From e5e7b7d39a1b723a76c4aeba279e7e35f19ab5a3 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Wed, 18 Nov 2026 12:52:49 +0100 Subject: [PATCH] chore: Move locks into batcher subclasses --- sentry_sdk/_batcher.py | 78 +--------------------------- sentry_sdk/_log_batcher.py | 94 +++++++++++++++++++++++++++++++++- sentry_sdk/_metrics_batcher.py | 94 +++++++++++++++++++++++++++++++++- sentry_sdk/_span_batcher.py | 32 ++++++++++++ 4 files changed, 218 insertions(+), 80 deletions(-) diff --git a/sentry_sdk/_batcher.py b/sentry_sdk/_batcher.py index 7fdc8ee895..266bae9171 100644 --- a/sentry_sdk/_batcher.py +++ b/sentry_sdk/_batcher.py @@ -2,11 +2,10 @@ import random import threading import weakref -from datetime import datetime, timezone from typing import TYPE_CHECKING, Generic, TypeVar from sentry_sdk.envelope import Envelope, Item, PayloadRef -from sentry_sdk.utils import capture_internal_exceptions, format_timestamp +from sentry_sdk.utils import capture_internal_exceptions if TYPE_CHECKING: from typing import Any, Callable, Optional @@ -32,7 +31,6 @@ def __init__( self._capture_func = capture_func self._record_lost_func = record_lost_func self._running = True - self._lock = threading.Lock() self._active: "threading.local" = threading.local() self._flush_event: "threading.Event" = threading.Event() @@ -54,44 +52,11 @@ def _reset_in_child() -> None: def _reset_thread_state(self) -> None: self._buffer = [] self._running = True - self._lock = threading.Lock() self._active = threading.local() self._flush_event = threading.Event() self._flusher = None self._flusher_pid = None - 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 - - with self._lock: - # Recheck to make sure another thread didn't get here and start the - # the flusher in the meantime - if self._flusher_pid == pid: - return True - - self._flusher_pid = pid - - self._flusher = threading.Thread(target=self._flush_loop) - self._flusher.daemon = True - - try: - self._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 - - return True - def _flush_loop(self) -> None: # Mark the flush-loop thread as active for its entire lifetime so # that any re-entrant add() triggered by GC warnings during wait(), @@ -109,34 +74,6 @@ def _flush_loop(self) -> None: with capture_internal_exceptions(): self._flush() - def add(self, item: "T") -> None: - # Bail out if the current thread is already executing batcher code. - # This prevents deadlocks when code running inside the batcher (e.g. - # _add_to_envelope during flush, or _flush_event.wait/set) triggers - # a GC-emitted warning that routes back through the logging - # integration into add(). - if getattr(self._active, "flag", False): - return None - - self._active.flag = True - try: - if not self._ensure_thread() or self._flusher is 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() - - # Record the loss outside of the lock, since this might involve - # serializing the item to report lost bytes - if dropped: - self._record_lost(item) - finally: - self._active.flag = False - def kill(self) -> None: if self._flusher is None: return @@ -173,18 +110,7 @@ def _add_to_envelope(self, envelope: "Envelope") -> None: envelope.add_item(self._to_envelope_item(self._buffer)) def _flush(self) -> "Optional[Envelope]": - envelope = Envelope( - headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} - ) - with self._lock: - if len(self._buffer) == 0: - return None - - self._add_to_envelope(envelope) - self._buffer.clear() - - self._capture_func(envelope) - return envelope + raise NotImplementedError def _record_lost(self, item: "T") -> None: envelope_item = None diff --git a/sentry_sdk/_log_batcher.py b/sentry_sdk/_log_batcher.py index b139b56da2..155f3b1382 100644 --- a/sentry_sdk/_log_batcher.py +++ b/sentry_sdk/_log_batcher.py @@ -1,10 +1,14 @@ +import os +import threading +from datetime import datetime, timezone from typing import TYPE_CHECKING from sentry_sdk._batcher import Batcher -from sentry_sdk.utils import serialize_attribute +from sentry_sdk.envelope import Envelope +from sentry_sdk.utils import format_timestamp, serialize_attribute if TYPE_CHECKING: - from typing import Any + from typing import Any, Callable, Optional from sentry_sdk._types import Log @@ -18,6 +22,92 @@ class LogBatcher(Batcher["Log"]): CLIENT_REPORT_TYPE = "log_item" CONTENT_TYPE = "application/vnd.sentry.items.log+json" + def __init__( + self, + capture_func: "Callable[[Envelope], None]", + record_lost_func: "Callable[..., None]", + ) -> None: + super().__init__(capture_func, record_lost_func) + self._lock = threading.Lock() + + def _reset_thread_state(self) -> None: + super()._reset_thread_state() + self._lock = threading.Lock() + + 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 + + with self._lock: + # Recheck to make sure another thread didn't get here and start the + # the flusher in the meantime + if self._flusher_pid == pid: + return True + + self._flusher_pid = pid + + self._flusher = threading.Thread(target=self._flush_loop) + self._flusher.daemon = True + + try: + self._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 + + return True + + def add(self, item: "Log") -> None: + # Bail out if the current thread is already executing batcher code. + # This prevents deadlocks when code running inside the batcher (e.g. + # _add_to_envelope during flush, or _flush_event.wait/set) triggers + # a GC-emitted warning that routes back through the logging + # integration into add(). + if getattr(self._active, "flag", False): + return None + + self._active.flag = True + try: + if not self._ensure_thread() or self._flusher is 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() + + # Record the loss outside of the lock, since this might involve + # serializing the item to report lost bytes + if dropped: + self._record_lost(item) + finally: + self._active.flag = False + + def _flush(self) -> "Optional[Envelope]": + envelope = Envelope( + headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} + ) + with self._lock: + if len(self._buffer) == 0: + return None + + self._add_to_envelope(envelope) + self._buffer.clear() + + self._capture_func(envelope) + return envelope + @staticmethod def _to_transport_format(item: "Log") -> "Any": if "sentry.severity_number" not in item["attributes"]: diff --git a/sentry_sdk/_metrics_batcher.py b/sentry_sdk/_metrics_batcher.py index 706e5ca653..68f367d3bd 100644 --- a/sentry_sdk/_metrics_batcher.py +++ b/sentry_sdk/_metrics_batcher.py @@ -1,10 +1,14 @@ +import os +import threading +from datetime import datetime, timezone from typing import TYPE_CHECKING from sentry_sdk._batcher import Batcher -from sentry_sdk.utils import serialize_attribute +from sentry_sdk.envelope import Envelope +from sentry_sdk.utils import format_timestamp, serialize_attribute if TYPE_CHECKING: - from typing import Any + from typing import Any, Callable, Optional from sentry_sdk._types import Metric @@ -18,6 +22,92 @@ 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]", + ) -> None: + super().__init__(capture_func, record_lost_func) + self._lock = threading.Lock() + + def _reset_thread_state(self) -> None: + super()._reset_thread_state() + self._lock = threading.Lock() + + 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 + + with self._lock: + # Recheck to make sure another thread didn't get here and start the + # the flusher in the meantime + if self._flusher_pid == pid: + return True + + self._flusher_pid = pid + + self._flusher = threading.Thread(target=self._flush_loop) + self._flusher.daemon = True + + try: + self._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 + + return True + + def add(self, item: "Metric") -> None: + # Bail out if the current thread is already executing batcher code. + # This prevents deadlocks when code running inside the batcher (e.g. + # _add_to_envelope during flush, or _flush_event.wait/set) triggers + # a GC-emitted warning that routes back through the logging + # integration into add(). + if getattr(self._active, "flag", False): + return None + + self._active.flag = True + try: + if not self._ensure_thread() or self._flusher is 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() + + # Record the loss outside of the lock, since this might involve + # serializing the item to report lost bytes + if dropped: + self._record_lost(item) + finally: + self._active.flag = False + + def _flush(self) -> "Optional[Envelope]": + envelope = Envelope( + headers={"sent_at": format_timestamp(datetime.now(timezone.utc))} + ) + with self._lock: + if len(self._buffer) == 0: + return None + + self._add_to_envelope(envelope) + self._buffer.clear() + + self._capture_func(envelope) + return envelope + @staticmethod def _to_transport_format(item: "Metric") -> "Any": res = { diff --git a/sentry_sdk/_span_batcher.py b/sentry_sdk/_span_batcher.py index 5e529ccc6e..b67d84f6ca 100644 --- a/sentry_sdk/_span_batcher.py +++ b/sentry_sdk/_span_batcher.py @@ -88,6 +88,38 @@ def _reset_thread_state(self) -> None: self._flusher = None self._flusher_pid = None + 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 + + with self._lock: + # Recheck to make sure another thread didn't get here and start the + # the flusher in the meantime + if self._flusher_pid == pid: + return True + + self._flusher_pid = pid + + self._flusher = threading.Thread(target=self._flush_loop) + self._flusher.daemon = True + + try: + self._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 + + return True + def _flush_loop(self) -> None: self._active.flag = True while self._running: