diff --git a/sentry_sdk/_batcher.py b/sentry_sdk/_batcher.py index 266bae9171..9af8b06f1a 100644 --- a/sentry_sdk/_batcher.py +++ b/sentry_sdk/_batcher.py @@ -1,7 +1,5 @@ -import os import random import threading -import weakref from typing import TYPE_CHECKING, Generic, TypeVar from sentry_sdk.envelope import Envelope, Item, PayloadRef @@ -38,17 +36,6 @@ def __init__( 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) - - def _reset_in_child() -> None: - method = weak_reset() - if method is not None: - method() - - os.register_at_fork(after_in_child=_reset_in_child) - def _reset_thread_state(self) -> None: self._buffer = [] self._running = True diff --git a/sentry_sdk/_span_batcher.py b/sentry_sdk/_span_batcher.py index b67d84f6ca..413756f72f 100644 --- a/sentry_sdk/_span_batcher.py +++ b/sentry_sdk/_span_batcher.py @@ -2,7 +2,6 @@ import random import threading import time -import weakref from collections import defaultdict from datetime import datetime, timezone from typing import TYPE_CHECKING @@ -62,17 +61,6 @@ def __init__( 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) - - def _reset_in_child() -> None: - method = weak_reset() - if method is not None: - method() - - os.register_at_fork(after_in_child=_reset_in_child) - def _reset_thread_state(self) -> None: self._span_buffer = defaultdict(list) self._running_size = defaultdict(lambda: 0) diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 7f84cea140..bbffb80405 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -2,6 +2,7 @@ import random import socket import uuid +import weakref from collections.abc import Mapping from contextvars import ContextVar from datetime import datetime, timezone @@ -389,6 +390,17 @@ def _record_lost_event( record_lost_func=_record_lost_event, ) + # 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_components_after_fork) + + def _reset_in_child() -> None: + method = weak_reset() + if method is not None: + method() + + os.register_at_fork(after_in_child=_reset_in_child) + max_request_body_size = ("always", "never", "small", "medium") if self.options["max_request_body_size"] not in max_request_body_size: raise ValueError( @@ -943,6 +955,11 @@ def _close_components(self) -> None: if self.monitor: self.monitor.kill() + def _reset_components_after_fork(self) -> None: + """Reset the state of all batchers to prevent deadlocks and duplicate telemetry.""" + for b in self._batchers: + b._reset_thread_state() + def _flush_components(self) -> None: """Flush all client components.""" self.session_flusher.flush() diff --git a/tests/test_client.py b/tests/test_client.py index 897d42af11..3ca9be3430 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1626,3 +1626,87 @@ async def test_async_socks_proxy(testcase): ) await client.close_async() + + +@pytest.mark.skipif( + sys.platform == "win32" + or not hasattr(os, "fork") + or not hasattr(os, "register_at_fork"), + reason="requires POSIX fork and os.register_at_fork (Python 3.7+)", +) +def test_batchers_reset_in_child_after_fork(sentry_init): + """Regression test for the batcher fork-deadlock fix. + + If os.fork() runs while another thread holds a batcher's lock, the child + inherits the lock locked. The holding thread does not exist in the child, + so the lock can never be released and _ensure_thread deadlocks forever. + The client's after-fork hook must replace each batcher's lock with a fresh + one in the child and reset its buffers, _flusher / _flusher_pid, _active, + _flush_event and _running. + """ + sentry_init(traces_sample_rate=1.0) + client = sentry_sdk.get_client() + log_batcher = client.log_batcher + metrics_batcher = client.metrics_batcher + span_batcher = client.span_batcher + assert log_batcher is not None + assert metrics_batcher is not None + assert span_batcher is not None + batchers = (log_batcher, metrics_batcher, span_batcher) + + original_locks = [batcher._lock for batcher in batchers] + for lock in original_locks: + lock.acquire() + + log_batcher._buffer.append(object()) + metrics_batcher._buffer.append(object()) + span_batcher._span_buffer["test-trace-id"].append(object()) + span_batcher._running_size["test-trace-id"] = 42 + for batcher in batchers: + batcher._active.flag = True + batcher._flush_event.set() + batcher._running = False + + pid = os.fork() + if pid == 0: + locks_replaced = all( + batcher._lock is not original_lock + for batcher, original_lock in zip(batchers, original_locks) + ) + locks_unheld = all( + batcher._lock.acquire(blocking=False) for batcher in batchers + ) + + flushers_reset = all( + batcher._flusher is None and batcher._flusher_pid is None + for batcher in batchers + ) + buffers_reset = ( + len(log_batcher._buffer) == 0 + and len(metrics_batcher._buffer) == 0 + and len(span_batcher._span_buffer) == 0 + and len(span_batcher._running_size) == 0 + ) + + active_reset = all( + not getattr(batcher._active, "flag", False) for batcher in batchers + ) + events_reset = all(not batcher._flush_event.is_set() for batcher in batchers) + running_reset = all(batcher._running is True for batcher in batchers) + + os._exit( + 0 + if locks_replaced + and locks_unheld + and flushers_reset + and buffers_reset + and active_reset + and events_reset + and running_reset + else 1 + ) + + for lock in original_locks: + lock.release() + _, status = os.waitpid(pid, 0) + assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0 diff --git a/tests/test_logs.py b/tests/test_logs.py index f594ba21e6..7bd7f52b23 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -1,5 +1,3 @@ -import os -import sys import time from unittest import mock @@ -812,63 +810,6 @@ def add_to_envelope_with_reentrant_add(envelope): # eventually be timed out by pytest-timeout -@pytest.mark.skipif( - sys.platform == "win32" - or not hasattr(os, "fork") - or not hasattr(os, "register_at_fork"), - reason="requires POSIX fork and os.register_at_fork (Python 3.7+)", -) -def test_log_batcher_lock_reset_in_child_after_fork(sentry_init): - """Regression test for the LogBatcher fork-deadlock fix. - - If os.fork() runs while another thread holds LogBatcher._lock, the - child inherits the lock locked. The holding thread does not exist in - the child, so the lock can never be released and _ensure_thread - deadlocks forever. The after-fork hook must replace the lock with a - fresh one in the child and reset - _flusher / _flusher_pid / _buffer / _active / _flush_event. - """ - sentry_init() - batcher = sentry_sdk.get_client().log_batcher - assert batcher is not None - - original_lock = batcher._lock - original_lock.acquire() - - batcher._buffer.append(object()) - batcher._active.flag = True - batcher._flush_event.set() - batcher._running = False - - pid = os.fork() - if pid == 0: - replaced = batcher._lock is not original_lock - unheld = batcher._lock.acquire(blocking=False) - - flusher_reset = batcher._flusher is None and batcher._flusher_pid is None - buffer_reset = len(batcher._buffer) == 0 - active_reset = not getattr(batcher._active, "flag", False) - - event_reset = not batcher._flush_event.is_set() - running_reset = batcher._running is True - - os._exit( - 0 - if replaced - and unheld - and flusher_reset - and buffer_reset - and active_reset - and event_reset - and running_reset - else 1 - ) - - original_lock.release() - _, status = os.waitpid(pid, 0) - assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0 - - @pytest.mark.tests_internal_exceptions def test_flush_loop_swallows_flush_exception(): """The flush loop must not let one failed flush kill the flusher thread. diff --git a/tests/test_metrics.py b/tests/test_metrics.py index efc458c32a..0d6e634e44 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -1,5 +1,3 @@ -import os -import sys from unittest import mock import pytest @@ -518,59 +516,3 @@ def before_send_metric(metric, _): ) get_client().flush() - - -@pytest.mark.skipif( - sys.platform == "win32" - or not hasattr(os, "fork") - or not hasattr(os, "register_at_fork"), - reason="requires POSIX fork and os.register_at_fork (Python 3.7+)", -) -def test_metrics_batcher_lock_reset_in_child_after_fork(sentry_init): - """Regression test for the MetricsBatcher fork-deadlock fix. - - If os.fork() runs while another thread holds MetricsBatcher._lock, - the child inherits the lock locked. The holding thread does not - exist in the child, so the lock can never be released and - _ensure_thread deadlocks forever. The after-fork hook must replace - the lock with a fresh one in the child and reset - _flusher / _flusher_pid / _buffer / _active / _flush_event. - """ - sentry_init() - batcher = sentry_sdk.get_client().metrics_batcher - assert batcher is not None - - original_lock = batcher._lock - original_lock.acquire() - - batcher._buffer.append(object()) - batcher._active.flag = True - batcher._flush_event.set() - batcher._running = False - - pid = os.fork() - if pid == 0: - replaced = batcher._lock is not original_lock - unheld = batcher._lock.acquire(blocking=False) - - flusher_reset = batcher._flusher is None and batcher._flusher_pid is None - buffer_reset = len(batcher._buffer) == 0 - active_reset = not getattr(batcher._active, "flag", False) - event_reset = not batcher._flush_event.is_set() - running_reset = batcher._running is True - - os._exit( - 0 - if replaced - and unheld - and flusher_reset - and buffer_reset - and active_reset - and event_reset - and running_reset - else 1 - ) - - original_lock.release() - _, status = os.waitpid(pid, 0) - assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0 diff --git a/tests/tracing/test_span_batcher.py b/tests/tracing/test_span_batcher.py index 6fb8c18d11..03704660e3 100644 --- a/tests/tracing/test_span_batcher.py +++ b/tests/tracing/test_span_batcher.py @@ -1,5 +1,3 @@ -import os -import sys import time from unittest import mock @@ -462,69 +460,6 @@ def test_trace_bucket_flushes_when_segment_ends( assert items[1].payload["name"] == "segment span" -@pytest.mark.skipif( - sys.platform == "win32" - or not hasattr(os, "fork") - or not hasattr(os, "register_at_fork"), - reason="requires POSIX fork and os.register_at_fork (Python 3.7+)", -) -def test_span_batcher_lock_reset_in_child_after_fork(sentry_init): - """Regression test for the SpanBatcher fork-deadlock fix. - - If os.fork() runs while another thread holds SpanBatcher._lock, the - child inherits the lock locked. The holding thread does not exist in - the child, so the lock can never be released and _ensure_thread - deadlocks forever. The after-fork hook must replace the lock with a - fresh one in the child and reset - _flusher / _flusher_pid / _span_buffer / _running_size / _active / - _flush_event. - """ - sentry_init( - traces_sample_rate=1.0, - ) - batcher = sentry_sdk.get_client().span_batcher - assert batcher is not None - - original_lock = batcher._lock - original_lock.acquire() - - batcher._span_buffer["test-trace-id"].append(object()) - batcher._running_size["test-trace-id"] = 42 - batcher._active.flag = True - batcher._flush_event.set() - batcher._running = False - - pid = os.fork() - if pid == 0: - replaced = batcher._lock is not original_lock - unheld = batcher._lock.acquire(blocking=False) - - flusher_reset = batcher._flusher is None and batcher._flusher_pid is None - span_buffer_reset = len(batcher._span_buffer) == 0 - running_size_reset = len(batcher._running_size) == 0 - - active_reset = not getattr(batcher._active, "flag", False) - event_reset = not batcher._flush_event.is_set() - running_reset = batcher._running is True - - os._exit( - 0 - if replaced - and unheld - and flusher_reset - and span_buffer_reset - and running_size_reset - and active_reset - and event_reset - and running_reset - else 1 - ) - - original_lock.release() - _, status = os.waitpid(pid, 0) - assert os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0 - - @pytest.mark.tests_internal_exceptions def test_flush_loop_swallows_flush_exception(): """The flush loop must not let one failed flush kill the flusher thread.