Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

authlib.integrations.requests_client.OAuth2Session creates a reference cycle that requires a deep garbage collection cycle to cleanup #698

Open
patrys opened this issue Jan 24, 2025 · 0 comments
Assignees
Labels

Comments

@patrys
Copy link

patrys commented Jan 24, 2025

Describe the bug

authlib.integrations.requests_client.OAuth2Session holds a reference to itself (through self.session) and references each other with Oauth2Auth (through TokenAuth.client). Those two references prevent the unused session objects from being freed until the garbage collector runs a deep cleanup cycle (generation=2).

To Reproduce

  1. Disable garbage collection temporarily to make sure we are the ones who catch it
  2. Set garbage collector's debug level to DEBUG_LEAK
  3. Create and delete an OAuth2Session object
  4. Force a garbage collection run to confirm that the problem exists (the output will list all hard to free objects)
import gc

from authlib.integrations.requests_client import OAuth2Session

session = OAuth2Session()
gc.collect()  # make sure there is no lingering garbage
gc.disable()
gc.set_debug(gc.DEBUG_LEAK)
del session
gc.collect()
gc.set_debug(0)

Expected behavior

The memory should be freed as soon as the session becomes unused.

Environment:

  • OS: MacOS and Linux
  • Python Version: 3.12
  • Authlib Version: 1.4.0

Additional context

Adding the following finalizers to authlib breaks up the cycles and results in the garbage collector finding no garbage:

class OAuth2Session(OAuth2Client, Session):
    ...

    def __del__(self):
        del self.session
class TokenAuth:
    ...

    def __del__(self):
        del self.client
        del self.hooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants