Skip to content

typing.py: builtin LRU caches worsen leaks that exist in other code #98253

Closed

Description

@wjakob

Bug report

I would like to report a refleak issue involving typing.py. The issue is that it internally uses LRU caches to cache certain type-related lookups, and these caches are not cleaned up when the Python interpreter shuts down. This causes leaks that impede software development and debugging of refleaks in general.

This specific part of typing.py has already once been identified as a source of refleaks by @gvanrossum (context: https://bugs.python.org/issue28649).

The following provides a small reproducer via a trivial package (https://github.com/wjakob/typing_repro) that exposes a class named A using nanobind. Why nanobind? It is extremely paranoid about any leaks involving bound types, functions, and instances, and prints warning messages to tell the user about this after the interpreter has shut down (it performs checks following finalization using Py_AtExit()).

preparation:

$ pip install git+https://github.com/wjakob/typing_repro

Reproducer:

from typing_repro import A

import pandas
import typing

def test(t: typing.Optional[A] = None):
    print(t)

Running this yields

nanobind: leaked 1 types!                                                                                         
 - leaked type "A"                                                                                                
nanobind: leaked 2 functions!
 - leaked function "add"
 - leaked function "__init__"
nanobind: this is likely caused by a reference counting issue in the binding code.

Note the import of pandas, which serves the role of a bigger package that uses the typing module and thereby populates the LRU caches. torch (PyTorch) or tensorflow also cause the issue, as does markupsafe, others likely affected as well.

EDIT: The problem that is common to all of these packages is that they leak some of their own types. For example, by Py_INCREFing references to heap types within extension modules. Because these types use typing.py and thereby reference the LRU caches (which are never cleaned up), it causes a flurry of refleaks that cascade into other packages.

Removing the test() function or removing the type annotation fixes the issue. The problem is that declaration causes cache entries to be created that are never cleaned up, even when the interpreter finalizes.

There is another way to avoid the issue: at the bottom of the script, insert

for f in typing._cleanups:
    f()

which clears the LRU caches in typing.py. Poof, errors gone. This leads me to suggest the following simple fix, to be added at the end of typing.py:

def _cleanup_handler():
    for f in _cleanups:
        f()

import atexit as _atexit
_atexit.register(_cleanup_handler)

This will clear the caches and ensure that interpreter finalization can avoid those type annotation-related leaks.

Your environment

  • CPython versions tested on: 3.8.10 and 3.10.;7
  • Operating system and architecture: Linux and macOS

Activity

  1. wjakob commented on Oct 21, 2022

    @wjakob
    ContributorAuthor

    I suppose we could put in the cleanup you recommend, but wouldn't it be better to fix the third-party packages that have this bug?

    It would not fix the issue in general – as my tests above showed (try, e.g. replacing markupsafe by pandas, tensorflow, pytorch, etc.) this pattern of extension modules holding a reference to a type is very common. It's a benign kind of leak that does not bother anyone else.

    What the LRU cache does is to spread this benign leak into a web of leaks involving anything else that also uses typing. That, I think is the gist of the issue.

  2. wjakob commented on Oct 21, 2022

    @wjakob
    ContributorAuthor

    Here is a proposed change to typing.py that fixes this behavior, using yet another approach. The idea is to break the reference chain at the typing._UnionGenericAlias.__getitem__ -> lru_cache segment, by using the function as a key into a global dict storing all of the used LRU caches.

    --- typing.py   2022-10-21 08:36:47.000000000 +0200
    +++ typing.py   2022-10-21 08:36:54.000000000 +0200
    @@ -293,6 +293,7 @@
     
     
     _cleanups = []
    +_caches = { }
     
     
     def _tp_cache(func=None, /, *, typed=False):
    @@ -300,13 +301,15 @@
         original function for non-hashable arguments.
         """
         def decorator(func):
    -        cached = functools.lru_cache(typed=typed)(func)
    -        _cleanups.append(cached.cache_clear)
    +        cache = functools.lru_cache(typed=typed)(func)
    +        _caches[func] = cache 
    +        _cleanups.append(cache.cache_clear)
    +        del cache
     
             @functools.wraps(func)
             def inner(*args, **kwds):
                 try:
    -                return cached(*args, **kwds)
    +                return _caches[func](*args, **kwds)
                 except TypeError:
                     pass  # All real errors (not unhashable args) are raised below.
                 return func(*args, **kwds)

    I tested this change, and it fixes the refleak issue on my end.

  3. Fidget-Spinner commented on Oct 25, 2022

    @Fidget-Spinner
    Member

    Just to reiterate so that I don't get lost in the weeds here:

    1. typing.py's LRU cache itself doesn't leak references. It just holds onto other things which may leak references or is held by said other things.
    2. Those other leaky things may hold a circular reference to typing.py's LRU cache through indirect means that are naturally found in typing.py.
    3. So it's proposed to break the reference cycle on typing.py's end, instead of getting the leaky extension to do it.

    Is this correct?

  4. wjakob commented on Oct 25, 2022

    @wjakob
    ContributorAuthor

    Yes, that summarizes things well. I would add that typing is an elementary part of the Python ecosystem, which includes many compiled extension with individually benign type leaks that now cause issues through the interaction with typing. Expecting them to be fixed instead would seem to me like an impossible game of whack-a-mole.

  5. changed the title [-]typing.py: builtin LRU caches leak references[/-] [+]typing.py: builtin LRU caches worsen leaks that exist in other code[/+] on Oct 25, 2022
  6. added
    type-feature
    and removed
    type-bug
    on Oct 29, 2022
  7. JelleZijlstra commented on Nov 5, 2022

    @JelleZijlstra
    Member

    Note that the repro no longer works at the moment because nanobind 0.0.8 contains a workaround for this leak. I proposed wjakob/typing_repro#3 to "fix" it. In the meantime, to use the repro, first install nanobind 0.0.7 and the package's other build requirements, then install typing_repro as in the OP above but with --no-build-isolation.

  8. added a commit that references this issue on Nov 30, 2022
  9. AlexWaygood commented on Nov 30, 2022

    @AlexWaygood
    Member

    Thanks for the PR and for being patient, @wjakob

  10. added a commit that references this issue on Dec 1, 2022
  11. wjakob commented on Dec 2, 2022

    @wjakob
    ContributorAuthor

    Thanks for accepting my patch :-)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancetopic-typingtype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions