Skip to content

Commit cf8a3ed

Browse files
committed
fix(sessions): clean up threading on kill+flush
This follows the precedent set in transport.flush, and helps me with my project to assert thread hygeine in sentry test suite (related: DI-1008), but also makes the system much more deterministic for everyone. This will cause shutdown to be quite slow until #4561 goes in. So I'd reject this if you reject that.
1 parent a7b2d67 commit cf8a3ed

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

sentry_sdk/sessions.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,9 @@ def __init__(
166166

167167
def flush(self):
168168
# type: (...) -> None
169-
pending_sessions = self.pending_sessions
170-
self.pending_sessions = []
169+
with self._thread_lock:
170+
pending_sessions = self.pending_sessions
171+
self.pending_sessions = []
171172

172173
with self._aggregate_lock:
173174
pending_aggregates = self.pending_aggregates
@@ -191,6 +192,26 @@ def flush(self):
191192
if len(envelope.items) > 0:
192193
self.capture_func(envelope)
193194

195+
# hygiene: deterministically clean up any stopping thread
196+
if not self._thread_stopping():
197+
return
198+
with self._thread_lock:
199+
if not self._thread_stopping():
200+
return
201+
if self._thread: # typing
202+
self._thread.join()
203+
self._thread = None
204+
self._thread_for_pid = None
205+
206+
def _thread_stopping(self):
207+
# type: (...) -> bool
208+
return (
209+
not self._running
210+
and self._thread is not None
211+
# we are the parent thread:
212+
and self._thread_for_pid == os.getpid()
213+
)
214+
194215
def _ensure_running(self):
195216
# type: (...) -> None
196217
"""

0 commit comments

Comments
 (0)