Skip to content
Closed
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
13 changes: 0 additions & 13 deletions sentry_sdk/_batcher.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 0 additions & 12 deletions sentry_sdk/_span_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 17 additions & 0 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand Down
84 changes: 84 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
59 changes: 0 additions & 59 deletions tests/test_logs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os
import sys
import time
from unittest import mock

Expand Down Expand Up @@ -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.
Expand Down
58 changes: 0 additions & 58 deletions tests/test_metrics.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os
import sys
from unittest import mock

import pytest
Expand Down Expand Up @@ -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
65 changes: 0 additions & 65 deletions tests/tracing/test_span_batcher.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os
import sys
import time
from unittest import mock

Expand Down Expand Up @@ -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.
Expand Down
Loading