From 1566a93d9f3f727169105b723bd80091cebb4279 Mon Sep 17 00:00:00 2001 From: Daniel Szoke Date: Mon, 7 Jul 2025 17:39:24 +0200 Subject: [PATCH] fix(profiling): Fix race condition while processing profiles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If multiple threads happen to be processing profiles, we could encounter a race condition, that would lead to more profiles being processed than are available in the `new_profiles` deque. To avoid this, we can break upon encountering an `IndexError`. This line appears to be the most likely cause of #4542 – in any case, handling an `IndexError` is not harmful Fixes #4542 --- sentry_sdk/profiler/continuous_profiler.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/sentry_sdk/profiler/continuous_profiler.py b/sentry_sdk/profiler/continuous_profiler.py index 00dd29e36c..77ddf188f6 100644 --- a/sentry_sdk/profiler/continuous_profiler.py +++ b/sentry_sdk/profiler/continuous_profiler.py @@ -370,7 +370,13 @@ def _sample_stack(*args, **kwargs): # that are starting profiles are not blocked until it # can acquire the lock. for _ in range(new_profiles): - self.active_profiles.add(self.new_profiles.popleft()) + try: + profile = self.new_profiles.popleft() + except IndexError: + # If another thread is concurrently popping profiles, we could + # end up with an empty deque here. + break + self.active_profiles.add(profile) inactive_profiles = [] for profile in self.active_profiles: