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
53 changes: 37 additions & 16 deletions sentry_sdk/_batcher.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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"):
Expand All @@ -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.
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
34 changes: 15 additions & 19 deletions sentry_sdk/_span_batcher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
import random
import threading
import time
import weakref
from collections import defaultdict
Expand All @@ -16,7 +15,7 @@
)

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

from sentry_sdk._types import SpanJSON

Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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()
34 changes: 26 additions & 8 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import random
import socket
import time
import uuid
from collections.abc import Mapping
from contextvars import ContextVar
Expand Down Expand Up @@ -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,
Expand All @@ -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()
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand Down
8 changes: 4 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
95 changes: 95 additions & 0 deletions tests/test_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading
Loading