Skip to content

SentryAsgiMiddleware keeps its application alive until cyclic garbage collection #8351

Open

Description

@jjsaunier

How do you use Sentry?

Reproduced locally without a Sentry backend. The effect occurs in the SDK process.

Version

Sentry Python SDK 2.74.0 and current master at 8842a6e05b01604108d1ea05aa9ab7580464e572. Reproduced on CPython 3.14.

Steps to reproduce

Run this with the SDK installed.

import gc
import weakref

from sentry_sdk.integrations.asgi import SentryAsgiMiddleware


class App:
    async def __call__(self, scope, receive, send):
        pass


was_enabled = gc.isenabled()
gc.disable()
try:
    app = App()
    app_ref = weakref.ref(app)
    middleware = SentryAsgiMiddleware(app)
    del middleware, app
    print("Retained before collection:", app_ref() is not None)
    gc.collect()
    print("Retained after collection:", app_ref() is not None)
finally:
    if was_enabled:
        gc.enable()

Expected result

The application reference is released as soon as the last reference to the wrapper is dropped.

Actual result

On CPython the first print is True and the second is False. The wrapper stores a bound method in its __call__ slot, and that method references the wrapper. The Starlette integration constructs a wrapper on each ASGI invocation, so the wrapper and its application closure accumulate until cyclic garbage collection.

Would you be open to binding the ASGI2 or ASGI3 method when __call__ is accessed? That would keep the original synchronous and asynchronous callable behavior, including the coroutine inspection used for ASGI version detection. I can include a regression test that completes a request in both modes and checks that the wrapper releases the application before collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions