Skip to content

Commit 299947d

Browse files
BYKclaude
andcommitted
fix: Handle CancelledError in AsyncWorker._target
When kill() cancels the _target task while it's waiting on queue.get(), the CancelledError propagates through the coroutine. Without catching it, the coroutine gets garbage collected with an unhandled exception, causing pytest's PytestUnraisableExceptionWarning. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent d19271e commit 299947d

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

sentry_sdk/worker.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -298,20 +298,23 @@ def submit(self, callback: "Callable[[], Any]") -> bool:
298298
async def _target(self) -> None:
299299
if self._queue is None:
300300
return
301-
while True:
302-
callback = await self._queue.get()
303-
if callback is _TERMINATOR:
304-
self._queue.task_done()
305-
break
306-
# Firing tasks instead of awaiting them allows for concurrent requests
307-
with mark_sentry_task_internal():
308-
task = asyncio.create_task(self._process_callback(callback))
309-
# Create a strong reference to the task so it can be cancelled on kill
310-
# and does not get garbage collected while running
311-
self._active_tasks.add(task)
312-
task.add_done_callback(self._on_task_complete)
313-
# Yield to let the event loop run other tasks
314-
await asyncio.sleep(0)
301+
try:
302+
while True:
303+
callback = await self._queue.get()
304+
if callback is _TERMINATOR:
305+
self._queue.task_done()
306+
break
307+
# Firing tasks instead of awaiting them allows for concurrent requests
308+
with mark_sentry_task_internal():
309+
task = asyncio.create_task(self._process_callback(callback))
310+
# Create a strong reference to the task so it can be cancelled on kill
311+
# and does not get garbage collected while running
312+
self._active_tasks.add(task)
313+
task.add_done_callback(self._on_task_complete)
314+
# Yield to let the event loop run other tasks
315+
await asyncio.sleep(0)
316+
except asyncio.CancelledError:
317+
pass # Expected during kill()
315318

316319
async def _process_callback(self, callback: "Callable[[], Any]") -> None:
317320
# Callback is an async coroutine, need to await it

0 commit comments

Comments
 (0)