Skip to content

Commit 3e46f97

Browse files
committed
ref: Store tracked spans on start not finish
This matches the JS implementation, and without it we cannot use the span recorder of a span to find its parent transaction.
1 parent cf582f6 commit 3e46f97

File tree

1 file changed

+16
-23
lines changed

1 file changed

+16
-23
lines changed

sentry_sdk/tracing.py

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -67,28 +67,21 @@ def __iter__(self):
6767

6868

6969
class _SpanRecorder(object):
70-
__slots__ = ("maxlen", "finished_spans", "open_span_count")
70+
"""Limits the number of spans recorded in a transaction."""
71+
72+
__slots__ = ("maxlen", "spans")
7173

7274
def __init__(self, maxlen):
7375
# type: (int) -> None
7476
self.maxlen = maxlen
75-
self.open_span_count = 0 # type: int
76-
self.finished_spans = [] # type: List[Span]
77+
self.spans = [] # type: List[Span]
7778

78-
def start_span(self, span):
79+
def add(self, span):
7980
# type: (Span) -> None
80-
81-
# This is just so that we don't run out of memory while recording a lot
82-
# of spans. At some point we just stop and flush out the start of the
83-
# trace tree (i.e. the first n spans with the smallest
84-
# start_timestamp).
85-
self.open_span_count += 1
86-
if self.open_span_count > self.maxlen:
81+
if len(self.spans) > self.maxlen:
8782
span._span_recorder = None
88-
89-
def finish_span(self, span):
90-
# type: (Span) -> None
91-
self.finished_spans.append(span)
83+
else:
84+
self.spans.append(span)
9285

9386

9487
class Span(object):
@@ -157,7 +150,7 @@ def init_finished_spans(self, maxlen):
157150
# type: (int) -> None
158151
if self._span_recorder is None:
159152
self._span_recorder = _SpanRecorder(maxlen)
160-
self._span_recorder.start_span(self)
153+
self._span_recorder.add(self)
161154

162155
def __repr__(self):
163156
# type: () -> str
@@ -330,8 +323,6 @@ def finish(self, hub=None):
330323
if self._span_recorder is None:
331324
return None
332325

333-
self._span_recorder.finish_span(self)
334-
335326
if self.transaction is None:
336327
# If this has no transaction set we assume there's a parent
337328
# transaction for this span that would be flushed out eventually.
@@ -354,6 +345,12 @@ def finish(self, hub=None):
354345

355346
return None
356347

348+
finished_spans = [
349+
span.to_json(client)
350+
for span in self._span_recorder.spans
351+
if span is not self and span.timestamp is not None
352+
]
353+
357354
return hub.capture_event(
358355
{
359356
"type": "transaction",
@@ -362,11 +359,7 @@ def finish(self, hub=None):
362359
"tags": self._tags,
363360
"timestamp": self.timestamp,
364361
"start_timestamp": self.start_timestamp,
365-
"spans": [
366-
s.to_json(client)
367-
for s in self._span_recorder.finished_spans
368-
if s is not self
369-
],
362+
"spans": finished_spans,
370363
}
371364
)
372365

0 commit comments

Comments
 (0)