Repository navigation
Open
Labels
extension-modulesC modules in the Modules dirperformancePerformance or resource usagetype-bugAn unexpected behavior, bug, or error
Description
Bug report
I'm been hunting a memory leak in pydantic and I keep seeing _abc_subclasscheck popping up in the memray flamegraph.
Locally I've seen memray report that _abc_subclasscheck is using 2.8GB of memory in some cases!
I can't get anything that bad in a minimal example, but I have the following:
from abc import ABCMeta
from datetime import datetime
class MyMetaclass(ABCMeta):
pass
class MyClass(metaclass=MyMetaclass):
pass
def main():
class Foobar(MyClass):
pass
assert issubclass(Foobar, MyClass)
assert not issubclass(int, MyClass)
assert not issubclass(str, MyClass)
assert not issubclass(datetime, MyClass)
t = type('A', (), {})
assert not issubclass(t, MyClass)
if __name__ == '__main__':
import os, psutil
process = psutil.Process(os.getpid())
mb = 1024 * 1024
last = 0
for i in range(5_000):
main()
# mem = process.memory_info().rss
# print(f'{i + 1:>4d} {mem / mb:8.2f}MB {(mem - last) / mb:+8.2f}MB | {"━" * int(mem / 8_000_000)}')
# last = memA few things to note:
- the commented out last few lines print current memory and change in memory over time
- I'm not sure exactly which
issubclasscalls are necessary, certainly I don't see a rise in memory with just the last one - some memory drops (presumably related to clearing the abc caches?) is happening, but overall memory is increasing
- The performance of
issubclasson an abc is very poor indeed - this script takes 14seconds, if i switchABCMetatotypeit takes 121ms!
Your environment
- Python 3.10.0 installed with venv
- Ubuntu 21.10
Linked PRs
- gh-92810: Reduce memory usage by ABCMeta.__subclasscheck__ #131914
- gh-92810: Reduce memory usage by ABCMeta.__subclasscheck__ (alternative) #141171
- gh-92810: Cover ABCMeta instancecheck/subclasscheck with more tests #144941
- gh-92810: Reduce memory usage by ABCMeta.__subclasscheck__ (alternative2) #150540
- gh-92810: Lock-free cache implementation for ABCMeta #162361
Reacted by Alexander Hirner, Maciej Olko, Adrian Garcia Badaracco, Wasi Master, Vinícius Gonçalves de Oliveira, Felipe S. S. Schneider, Maksym Goritskyi and Bastien Orivel
Metadata
Metadata
Assignees
Labels
extension-modulesC modules in the Modules dirperformancePerformance or resource usagetype-bugAn unexpected behavior, bug, or error
Activity
sweeneyde commentedon May 15, 2022
From what I can gather, there is no actual leak strictly speaking, but it seems like it might be a corner case where that garbage collector isn't running as often as it maybe should be for this scenario.
Doing something like below shows some strange artifacts where the "before collection" case has widely variable numbers of
weakref.weakrefobjects lingering around, and widely variable performance. However, callinggc.collect()consistently takes the number back down. Does manually addingcollect()calls fix your use-case?@pablogsal any ideas?
pablogsal commentedon May 15, 2022
I will investigate later but you can also try to adjust the gc threshold down to force collections more often and another thing is to set the GC flags to debug flags to gc.DEBUG_SAVEALL so the cycles are being saved so we can inspect what objects are responsible or the memory and why they are forming cycles.
samuelcolvin commentedon May 15, 2022
Rather than the GC, and since the problem seems to be more severe when the checks return false, I thought this might be
_abc_negative_cachegrowing indefinitely?pablogsal commentedon May 15, 2022
Is possible, but we need some analysis and unfortunately I am writing this from my phone while hiking so I cannot test until I am back at home 😅
I would be surprised if this is a GC problem to be honest because that would involve some circular references and unless I am missing something there should not be growing isolated cycles here.
pablogsal commentedon May 15, 2022
My educated guess is that is likely the combination of this:
cpython/Modules/_abc.c
Line 201 in 36d42e7
cpython/Modules/_abc.c
Line 195 in 36d42e7
cpython/Modules/_abc.c
Line 190 in 36d42e7
sweeneyde commentedon May 15, 2022
I notice that the pure-python version uses a
WeakSetwhere the c version uses a set of weakrefs.cpython/Lib/_py_abc.py
Line 50 in 953ab07
pablogsal commentedon May 15, 2022
I asked a colleague to run the
memrayflamegraphs with native introspection while I return home. It shows clearly that my guess was right and is the ABC cache the one that is responsible of this problem.Note: This uses the latest development branch of
memrayso you may see something slightly different.Leaks
This shows the memory that is there at the end of execution
)
Peak
This shows where the chunks of memory that form the heap when the memory is at its peak where allocated
Resident size over time
You can see in the last plot how the cache is periodically cleaned up (maybe because GC passes?), but there is something that survives.
zrothberg commentedon Jun 12, 2022
So I messed around with python version of this a bit. By just removing the negative cache from ABCMeta it become around 30x faster and no longer had a memory leak taking 2 second to do 10000 iterations. Even manually calling gc.collect seems to be unable to free up all the memory.
It grows from 11mb at startup to 68 MB on end.
I went further and swapped to a regular
set()this had a memory leak but it was actually about half the size of the original memory leak and only went up to 33mb.VERY VERY VERY strangely adding that to
__subclasscheck__right before setting the cache actually speeds up the program about 3 times.My best guess is the issue is just one of pure volume.
cpython/Lib/_py_abc.py
Lines 141 to 147 in 733e15f
Because you are recursively running instance check and recursively caching the values its just creating a ton of items in the WeakRefs. Bumping the original code up to two child classes from MyClass grinds to an absolute halt. The real issue is if there is ever a parent class that has many children (like every single item in pydantic) you are going to perform subclass checking on 100+ different child classes and are going to be caching values in all 100+ different child classes. Because gc isn't able to catch up during this Myclass ends up with a few thousand subclasses still attached to it each of which is recursively gone through. Manually calling gc cleared the weakreferences from the
__subclasses__method but the leaked memory does not recoverFurther it is actually bugged and doesn't work properly which is actually what is stopping this from melting down all the time. If a class was already called with
isinstancewhen its called a second time it will never run through all the subclasses as the cache will not break and it will be short circuited at the top. Frankly that bug probably prevented a lot of major issues.cpython/Lib/_py_abc.py
Lines 115 to 121 in 733e15f
The cache is never invalidated for subclassing just for registrations.
@samuelcolvin For pydantic I would just replace the
__subclasscheck__on the metaclass for the main pydanitc metaclass. This should clear up the bulk of the memory leak as well as likely pretty dramatically increase the actual speed since I doubt it needs to check every single child class on a miss. I would presume it in fact should never need to because all child classes directly descended from the BaseClass.corona10 commentedon Jun 26, 2022
The ratio of cache hit/miss looks super low for this scenario, can we switch caches into LRUCache?
zrothberg commentedon Jun 26, 2022
I honestly dont think it will fix the core issue. The main problem is just the way it walks down the class tree. This makes any sufficiently large class hierarchy impossibly slow and causes massive memory consumption. Switching to an LRU cache only solves the memory part but the above example of 10k comparisons still takes 2 mins to run on my macbook because it causes 10k lookups per issubclass call.
If you are generating classes the bulk of which never get compared in any natural way them getting involved in their parents issubclass call is unintuitive at best. Frankly I am not sure I fully understand the intent of it. I presume its for registered calls but if it is not and the intent is to allow subclasses to specialize how they check then it should just be considered bugged.
iritkatriel commentedon Apr 3, 2023
See also #94284.
96 remaining items
pythongh-92810: Fix merge conflicts
pythongh-92810: Fix merge conflicts
pythongh-92810: Fix merge conflicts
pythongh-92810: Fix blurb message
pythongh-92810: Fix compiler warning
pythongh-92810: Remove garbage
dolfinus commentedon May 28, 2026
#150540 removes support for this case, as a demonstration. Diff is much smaller now.
pythongh-92810: Lock-free cache implementation for ABCMeta
pythongh-92810: Lock-free cache implementation for ABCMeta
pythongh-92810: Lock-free cache implementation for ABCMeta
pythongh-92810: Lock-free cache implementation for ABCMeta
pythongh-92810: Lock-free cache implementation for ABCMeta
pythongh-92810: Lock-free cache implementation for ABCMeta
pythongh-92810: Lock-free cache implementation for ABCMeta