From 5d8a85952930bc0ac968ff8aa878d30fbace9606 Mon Sep 17 00:00:00 2001 From: Fabian Schindler Date: Tue, 24 Feb 2026 15:22:17 +0100 Subject: [PATCH] fix(asyncio): treat `asyncio.Task`s as trace continuation and new transactions --- sentry_sdk/integrations/asyncio.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/sentry_sdk/integrations/asyncio.py b/sentry_sdk/integrations/asyncio.py index b7aa0a7202..91dc4b5d5b 100644 --- a/sentry_sdk/integrations/asyncio.py +++ b/sentry_sdk/integrations/asyncio.py @@ -57,6 +57,12 @@ def _sentry_task_factory( coro: "Coroutine[Any, Any, Any]", **kwargs: "Any", ) -> "asyncio.Future[Any]": + # we get the current span here, as later it may already be closed + in_span = sentry_sdk.get_current_span() is not None + headers = dict( + sentry_sdk.get_current_scope().iter_trace_propagation_headers() + ) + @_wrap_coroutine(coro) async def _task_with_sentry_span_creation() -> "Any": result = None @@ -66,16 +72,16 @@ async def _task_with_sentry_span_creation() -> "Any": ) task_spans = integration.task_spans if integration else False + if task_spans and in_span: + transaction = sentry_sdk.continue_trace( + headers, op="task", name="downstream" + ) + ctx = sentry_sdk.start_transaction(transaction) + else: + ctx = nullcontext() + with sentry_sdk.isolation_scope(): - with ( - sentry_sdk.start_span( - op=OP.FUNCTION, - name=get_name(coro), - origin=AsyncioIntegration.origin, - ) - if task_spans - else nullcontext() - ): + with ctx: try: result = await coro except StopAsyncIteration as e: