Skip to content

Commit fae46f6

Browse files
authored
fix: Avoid crashes when scope or hub is racy (getsentry#517)
* fix: Avoid crashes when scope or hub is racy * fix: Fix None deref
1 parent 0fb630e commit fae46f6

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

sentry_sdk/hub.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -440,8 +440,9 @@ def start_span(
440440
kwargs.setdefault("hub", self)
441441

442442
if span is None:
443-
if scope.span is not None:
444-
span = scope.span.new_span(**kwargs)
443+
span = scope.span
444+
if span is not None:
445+
span = span.new_span(**kwargs)
445446
else:
446447
span = Span(**kwargs)
447448

@@ -570,17 +571,19 @@ def iter_trace_propagation_headers(self):
570571
# type: () -> Generator[Tuple[str, str], None, None]
571572
# TODO: Document
572573
client, scope = self._stack[-1]
573-
if scope._span is None:
574+
span = scope.span
575+
576+
if span is None:
574577
return
575578

576579
propagate_traces = client and client.options["propagate_traces"]
577580
if not propagate_traces:
578581
return
579582

580583
if client and client.options["traceparent_v2"]:
581-
traceparent = scope._span.to_traceparent()
584+
traceparent = span.to_traceparent()
582585
else:
583-
traceparent = scope._span.to_legacy_traceparent()
586+
traceparent = span.to_legacy_traceparent()
584587

585588
yield "sentry-trace", traceparent
586589

sentry_sdk/scope.py

+13-4
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ class Scope(object):
6666
events that belong to it.
6767
"""
6868

69+
# NOTE: Even though it should not happen, the scope needs to not crash when
70+
# accessed by multiple threads. It's fine if it's full of races, but those
71+
# races should never make the user application crash.
72+
#
73+
# The same needs to hold for any accesses of the scope the SDK makes.
74+
6975
__slots__ = (
7076
"_level",
7177
"_name",
@@ -124,8 +130,9 @@ def transaction(self, value):
124130
# type: (Optional[str]) -> None
125131
"""When set this forces a specific transaction name to be set."""
126132
self._transaction = value
127-
if self._span:
128-
self._span.transaction = value
133+
span = self._span
134+
if span:
135+
span.transaction = value
129136

130137
@_attr_setter
131138
def user(self, value):
@@ -143,8 +150,10 @@ def span(self):
143150
def span(self, span):
144151
# type: (Optional[Span]) -> None
145152
self._span = span
146-
if span is not None and span.transaction:
147-
self._transaction = span.transaction
153+
if span is not None:
154+
span_transaction = span.transaction
155+
if span_transaction:
156+
self._transaction = span_transaction
148157

149158
def set_tag(
150159
self,

0 commit comments

Comments
 (0)