diff --git a/sentry_sdk/_batcher.py b/sentry_sdk/_batcher.py index 7fdc8ee895..a73b1ac7a4 100644 --- a/sentry_sdk/_batcher.py +++ b/sentry_sdk/_batcher.py @@ -1,6 +1,7 @@ import os import random import threading +import time import weakref from datetime import datetime, timezone from typing import TYPE_CHECKING, Generic, TypeVar @@ -31,14 +32,7 @@ def __init__( self._buffer: "list[T]" = [] 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() - - self._flusher: "Optional[threading.Thread]" = None - self._flusher_pid: "Optional[int]" = None + self._reset_sync_state() # See https://github.com/getsentry/sentry-python/blob/051cc01640a29bfd64b1f1e2e3414c02f027dd1b/sentry_sdk/monitor.py#L41-L50 if hasattr(os, "register_at_fork"): @@ -51,14 +45,19 @@ def _reset_in_child() -> None: os.register_at_fork(after_in_child=_reset_in_child) - def _reset_thread_state(self) -> None: - self._buffer = [] + def _reset_sync_state(self) -> None: self._running = True self._lock = threading.Lock() - self._active = threading.local() - self._flush_event = threading.Event() - self._flusher = None - self._flusher_pid = None + self._active: "threading.local" = threading.local() + self._flush_event: "threading.Event" = threading.Event() + self._flush_cond: "threading.Condition" = threading.Condition(self._lock) + self._in_flight_flushes = 0 + self._flusher: "Optional[threading.Thread]" = None + self._flusher_pid: "Optional[int]" = None + + def _reset_thread_state(self) -> None: + self._buffer = [] + self._reset_sync_state() def _ensure_thread(self) -> bool: """For forking processes we might need to restart this thread. @@ -145,11 +144,26 @@ def kill(self) -> None: self._flush_event.set() self._flusher = None - def flush(self) -> None: + def _wait_for_in_flight_flushes(self, timeout: "Optional[float]" = None) -> None: + deadline = None if timeout is None else time.monotonic() + timeout + with self._flush_cond: + while self._in_flight_flushes > 0: + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + self._flush_cond.wait(timeout=remaining) + else: + self._flush_cond.wait() + + def flush(self, timeout: "Optional[float]" = None) -> None: was_active = getattr(self._active, "flag", False) self._active.flag = True try: self._flush() + # Avoid deadlocking if flush() is invoked re-entrantly from _capture_func. + if not was_active: + self._wait_for_in_flight_flushes(timeout=timeout) finally: self._active.flag = was_active @@ -182,8 +196,15 @@ def _flush(self) -> "Optional[Envelope]": self._add_to_envelope(envelope) self._buffer.clear() + self._in_flight_flushes += 1 - self._capture_func(envelope) + try: + self._capture_func(envelope) + finally: + with self._flush_cond: + self._in_flight_flushes -= 1 + if self._in_flight_flushes == 0: + self._flush_cond.notify_all() return envelope def _record_lost(self, item: "T") -> None: diff --git a/sentry_sdk/_span_batcher.py b/sentry_sdk/_span_batcher.py index 5e529ccc6e..9052ecf69f 100644 --- a/sentry_sdk/_span_batcher.py +++ b/sentry_sdk/_span_batcher.py @@ -1,6 +1,5 @@ import os import random -import threading import time import weakref from collections import defaultdict @@ -16,7 +15,7 @@ ) if TYPE_CHECKING: - from typing import Any, Callable, Optional + from typing import Any, Callable from sentry_sdk._types import SpanJSON @@ -51,17 +50,11 @@ def __init__( self._running_size: dict[str, int] = defaultdict(lambda: 0) 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._reset_sync_state() self._last_full_flush: float = time.monotonic() # drives time-based flushes - self._flush_event = threading.Event() self._pending_flush: set[str] = set() # buckets to be flushed - self._flusher: "Optional[threading.Thread]" = None - self._flusher_pid: "Optional[int]" = None - # See https://github.com/getsentry/sentry-python/blob/051cc01640a29bfd64b1f1e2e3414c02f027dd1b/sentry_sdk/monitor.py#L41-L50 if hasattr(os, "register_at_fork"): weak_reset = weakref.WeakMethod(self._reset_thread_state) @@ -76,18 +69,11 @@ def _reset_in_child() -> None: def _reset_thread_state(self) -> None: self._span_buffer = defaultdict(list) self._running_size = defaultdict(lambda: 0) - self._running = True - - self._lock = threading.Lock() - self._active = threading.local() + self._reset_sync_state() self._last_full_flush = time.monotonic() - self._flush_event = threading.Event() self._pending_flush = set() - self._flusher = None - self._flusher_pid = None - def _flush_loop(self) -> None: self._active.flag = True while self._running: @@ -261,5 +247,15 @@ def _flush(self, only_pending: bool = False) -> None: del self._span_buffer[bucket_id] del self._running_size[bucket_id] - for envelope in envelopes: - self._capture_func(envelope) + if not envelopes: + return + self._in_flight_flushes += 1 + + try: + for envelope in envelopes: + self._capture_func(envelope) + finally: + with self._flush_cond: + self._in_flight_flushes -= 1 + if self._in_flight_flushes == 0: + self._flush_cond.notify_all() diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 7f84cea140..42f82fd08f 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -1,6 +1,7 @@ import os import random import socket +import time import uuid from collections.abc import Mapping from contextvars import ContextVar @@ -943,11 +944,18 @@ def _close_components(self) -> None: if self.monitor: self.monitor.kill() - def _flush_components(self) -> None: - """Flush all client components.""" + def _flush_components(self, timeout: "Optional[float]" = None) -> "Optional[float]": + """Flush all client components and return remaining timeout budget.""" self.session_flusher.flush() + if timeout is None: + for b in self._batchers: + b.flush() + return None + + deadline = time.monotonic() + timeout for b in self._batchers: - b.flush() + b.flush(timeout=max(0.0, deadline - time.monotonic())) + return max(0.0, deadline - time.monotonic()) def close( self, @@ -963,7 +971,11 @@ def close( logger.warning( "close() used with AsyncHttpTransport. Use close_async() instead.", ) - self._flush_components() + self._flush_components( + timeout=( + self.options["shutdown_timeout"] if timeout is None else timeout + ) + ) else: self.flush(timeout=timeout, callback=callback) self._close_components() @@ -1012,9 +1024,12 @@ def flush( return if timeout is None: timeout = self.options["shutdown_timeout"] - self._flush_components() + remaining_timeout = self._flush_components(timeout=timeout) - self.transport.flush(timeout=timeout, callback=callback) + self.transport.flush( + timeout=timeout if remaining_timeout is None else remaining_timeout, + callback=callback, + ) async def flush_async( self, @@ -1036,8 +1051,11 @@ async def flush_async( return if timeout is None: timeout = self.options["shutdown_timeout"] - self._flush_components() - flush_task = self.transport.flush(timeout=timeout, callback=callback) # type: ignore + remaining_timeout = self._flush_components(timeout=timeout) + flush_task = self.transport.flush( # type: ignore + timeout=timeout if remaining_timeout is None else remaining_timeout, + callback=callback, + ) if flush_task is not None: await flush_task diff --git a/tests/conftest.py b/tests/conftest.py index 063a17c9c2..812389c46d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -304,20 +304,20 @@ def _flush(*args: "Any", **kwargs: "Any") -> "Any": drained_count += 1 wake.set() - def flush() -> None: + def flush(*args: "Any", **kwargs: "Any") -> None: nonlocal drained_count # Re-entrancy guard: if `flush()` is invoked from within a drain (e.g. a # custom transport), waiting on the flusher thread would deadlock, because # the flusher is blocked inside our own handler. if getattr(getattr(batcher, "_active", None), "flag", False): - orig_flush() + orig_flush(*args, **kwargs) return # If the background flusher thread was never started (no spans have # been added), there is no thread to drain and the counter will never # advance. Fall back to the original synchronous flush. if batcher._flusher is None or not batcher._flusher.is_alive(): - orig_flush() + orig_flush(*args, **kwargs) return with lock: @@ -330,7 +330,7 @@ def flush() -> None: break wake.wait() wake.clear() - orig_flush() + orig_flush(*args, **kwargs) object.__setattr__(batcher, "_flush", _flush) object.__setattr__(batcher, "flush", flush) diff --git a/tests/test_logs.py b/tests/test_logs.py index f594ba21e6..ffcfbc66e0 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -900,3 +900,98 @@ def _flush(self): batcher._flush_loop() assert calls == [1] + + +def test_batcher_flush_waits_for_in_flight_flusher_batch(): + import threading + + from sentry_sdk._batcher import Batcher + + class FakeBatcher(Batcher): + MAX_BEFORE_FLUSH = 1 + TYPE = "log" + CLIENT_REPORT_TYPE = "log_item" + CONTENT_TYPE = "application/vnd.sentry.items.log+json" + + @staticmethod + def _to_transport_format(item): + return item + + received = [] + taken = threading.Event() + release = threading.Event() + + def capture_func(envelope): + if threading.current_thread() is not threading.main_thread(): + taken.set() + release.wait(timeout=5) + received.append(envelope) + + batcher = FakeBatcher( + capture_func=capture_func, + record_lost_func=lambda *a, **k: None, + ) + + try: + batcher.add({"body": "hello"}) + assert taken.wait(timeout=5) + + def release_soon(): + time.sleep(0.1) + release.set() + + releaser = threading.Thread(target=release_soon) + releaser.start() + try: + batcher.flush() + assert len(received) == 1 + finally: + releaser.join(timeout=5) + finally: + release.set() + batcher.kill() + + +def test_client_flush_and_close_wait_for_in_flight_span_batch(): + import threading + + from sentry_sdk.transport import Transport + + received = [] + taken = threading.Event() + release = threading.Event() + + class SlowTransport(Transport): + def capture_envelope(self, envelope): + if threading.current_thread() is not threading.main_thread(): + taken.set() + release.wait(timeout=5) + received.extend(item.type for item in envelope.items) + + client = sentry_sdk.Client( + dsn="https://public@example.invalid/1", + transport=SlowTransport({"dsn": "https://public@example.invalid/1"}), + trace_lifecycle="stream", + traces_sample_rate=1.0, + ) + + with sentry_sdk.new_scope() as scope: + scope.set_client(client) + with sentry_sdk.traces.start_span(name="segment"): + pass + + assert taken.wait(timeout=5) + + def release_soon(): + time.sleep(0.1) + release.set() + + releaser = threading.Thread(target=release_soon) + releaser.start() + try: + client.flush(timeout=5.0) + assert received == ["span"] + finally: + releaser.join(timeout=5) + release.set() + client.close() diff --git a/tests/tracing/test_span_batcher.py b/tests/tracing/test_span_batcher.py index 6fb8c18d11..6fd138c21f 100644 --- a/tests/tracing/test_span_batcher.py +++ b/tests/tracing/test_span_batcher.py @@ -554,3 +554,144 @@ def _flush(self, only_pending=False): batcher._flush_loop() assert calls == [1] + + +def test_flush_waits_for_in_flight_flusher_batch(): + import threading + + received = [] + taken = threading.Event() + release = threading.Event() + + def capture_func(envelope): + if threading.current_thread() is not threading.main_thread(): + taken.set() + release.wait(timeout=5) + received.append(envelope) + + batcher = SpanBatcher( + capture_func=capture_func, + record_lost_func=lambda *a, **k: None, + ) + + class DummySegment: + def _dynamic_sampling_context(self): + return {"trace_id": "a" * 32} + + def _make_span(): + return { + "trace_id": "a" * 32, + "span_id": "b" * 16, + "name": "segment", + "is_segment": True, + "start_timestamp": 0.0, + "end_timestamp": 1.0, + "attributes": {}, + "_segment_span": DummySegment(), + } + + try: + batcher.add(_make_span()) + assert taken.wait(timeout=5) + + def release_soon(): + time.sleep(0.1) + release.set() + + releaser = threading.Thread(target=release_soon) + releaser.start() + try: + batcher.flush() + assert len(received) == 1 + finally: + releaser.join(timeout=5) + finally: + release.set() + batcher.kill() + + +def test_span_batcher_reentrant_flush_does_not_deadlock(): + import threading + + received = [] + batcher_ref = [] + done = threading.Event() + + def capture_func(envelope): + if len(received) == 0: + received.append(envelope) + batcher_ref[0].flush() + done.set() + + batcher = SpanBatcher( + capture_func=capture_func, + record_lost_func=lambda *a, **k: None, + ) + batcher_ref.append(batcher) + + class DummySegment: + def _dynamic_sampling_context(self): + return {"trace_id": "a" * 32} + + try: + batcher.add( + { + "trace_id": "a" * 32, + "span_id": "b" * 16, + "name": "segment", + "is_segment": True, + "start_timestamp": 0.0, + "end_timestamp": 1.0, + "attributes": {}, + "_segment_span": DummySegment(), + } + ) + assert done.wait(timeout=5) + batcher.flush() + assert len(received) == 1 + finally: + batcher.kill() + + +def test_span_batcher_flush_respects_timeout(): + import threading + + taken = threading.Event() + release = threading.Event() + + def capture_func(envelope): + if threading.current_thread() is not threading.main_thread(): + taken.set() + release.wait(timeout=5) + + batcher = SpanBatcher( + capture_func=capture_func, + record_lost_func=lambda *a, **k: None, + ) + + class DummySegment: + def _dynamic_sampling_context(self): + return {"trace_id": "a" * 32} + + try: + batcher.add( + { + "trace_id": "a" * 32, + "span_id": "b" * 16, + "name": "segment", + "is_segment": True, + "start_timestamp": 0.0, + "end_timestamp": 1.0, + "attributes": {}, + "_segment_span": DummySegment(), + } + ) + assert taken.wait(timeout=5) + + start = time.monotonic() + batcher.flush(timeout=0.05) + elapsed = time.monotonic() - start + assert elapsed < 1.0 + finally: + release.set() + batcher.kill()