SDK not instrumenting Asyncio calls when sentry_sdk.init
called at app lifecycle's beginning, outside an async
function
#2328
Labels
Better async support
Integration: Asyncio
Triaged
Has been looked at recently during old issue triage
How do you use Sentry?
Sentry Saas (sentry.io)
Version
1.30.0
Steps to Reproduce
To observe the issue, we can run the following code snippet:
Expected Result
We would expect the SDK to record spans for all async calls. In particular, calls to the function
fib
should appear as spans in the performance transaction, so that we observe the following when viewing the performance transaction in Sentry:Actual Result
However, if we actually run the above code snippet and then view the generated performance transaction in Sentry, we will observe that the
fib
spans are missing! Instead, our transaction looks like the following:The missing spans indicate that the SDK is not instrumenting async task calls as we would expect it to.
Workaround
For now, we can work around this bug by initializing the SDK within our first
async
function call, like so:If we run the workaround code, we observe the expected result. However, we should fix the bug so that we also observe the expected result when we initialize the SDK outside an async function call.
Possible fix
The issue appears to arise from within the
patch_asyncio
function, which is defined insentry_sdk/integrations/asyncio.py
, specifically by the line which obtains the loop like so:asyncio.get_running_loop
can only be called from within a coroutine or callback. When we initialize the SDK outside an async function, we violate this precondition and aRuntimeError
is raised. The SDK handles this error, but the error prevents the SDK from auto-instrumenting calls to async functions.Replacing the
asyncio.get_running_loop()
call with a call toasyncio.get_event_loop()
would likely fix this bug, but we need to ensure thatget_event_loop
does not cause any unintended side effects before implementing this change.Alternatively, this issue could likely be resolved by instrumenting asyncio through the use of a custom event loop policy which instruments the SDK when a new event loop is created in addition to instrumenting the current event loop. This solution may be preferable since it would likely also resolve #2333.
The text was updated successfully, but these errors were encountered: