Skip to content

fix(tracing): Serialize spans outside the SpanBatcher lock (#8023) - #8170

Closed
ansh-rohilla wants to merge 1 commit into
getsentry:masterfrom
ansh-rohilla:fix/span-batcher-lock-outside-serialization-8023
Closed

ansh-rohilla wants to merge 1 commit into
getsentry:masterfrom
ansh-rohilla:fix/span-batcher-lock-outside-serialization-8023

Conversation

@ansh-rohilla

Copy link
Copy Markdown

Problem

In SpanBatcher._flush(), self._lock was held while calling _dynamic_sampling_context() and serializing spans via _to_transport_format(). This blocked concurrent additions to the buffer for the entire duration of serialization and posed potential lock-order inversion hazards with GC finalizers (similar to what was addressed in #7776 for Batcher).

Additionally, in SpanBatcher.add(), _record_lost_func was invoked while holding self._lock.

Solution

  1. In SpanBatcher._flush():
    • Detach the trace buckets under self._lock via self._span_buffer.pop(bucket_id, None) and self._running_size.pop(bucket_id, None).
    • Release self._lock before constructing envelopes and serializing spans with _to_transport_format().
  2. In SpanBatcher.add():
    • Move the _record_lost_func call outside self._lock when dropping spans due to queue overflow.
  3. In tests/tracing/test_span_batcher.py:
    • Add regression tests verifying:
      • _to_transport_format() executes without holding _lock.
      • Concurrent additions are not blocked while spans are serialized.
      • _record_lost_func is invoked outside _lock on queue overflow.

Fixes #8023

…#8023)

SpanBatcher._flush() previously held _lock while computing
_dynamic_sampling_context() and serializing spans via
_to_transport_format(). This blocked concurrent additions to the buffer
and posed lock-order inversion hazards during serialization or GC
finalizers, similar to what was resolved in getsentry#7776 for Batcher.

- Detach pending trace buckets under _lock and serialize / construct
  envelopes outside the lock in SpanBatcher._flush().
- Move _record_lost_func call outside _lock in SpanBatcher.add().
- Add regression tests verifying the lock is not held during
  serialization, concurrent additions are unblocked, and dropped spans
  record losses outside the lock.

Fixes getsentry#8023
@ansh-rohilla
ansh-rohilla requested a review from a team as a code owner October 30, 2026 11:43
@ansh-rohilla
ansh-rohilla deleted the fix/span-batcher-lock-outside-serialization-8023 branch October 30, 2026 11:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SpanBatcher serializes spans while holding its buffer lock

1 participant