Skip to content

Commit c0ee4bb

Browse files
gh-92810: Lock-free cache implementation for ABCMeta (#162361)
* gh-92810: Lock-free cache implementation for ABCMeta Replace the sets of weak references used for the ABC registry and the positive/negative isinstance caches with hash tables keyed by class identity. Cached isinstance() and issubclass() checks are served without locking or reference count updates on the free-threaded build, and a negative result is no longer propagated into the cache of every subclass of the ABC, which made such checks quadratic for large hierarchies.
1 parent 87fc280 commit c0ee4bb

10 files changed

Lines changed: 1029 additions & 365 deletions

File tree

‎Include/internal/pycore_global_objects_fini_generated.h‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Include/internal/pycore_global_strings.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ struct _Py_global_strings {
241241
STRUCT_FOR_ID(__str__)
242242
STRUCT_FOR_ID(__sub__)
243243
STRUCT_FOR_ID(__subclasscheck__)
244+
STRUCT_FOR_ID(__subclasses__)
244245
STRUCT_FOR_ID(__subclasshook__)
245246
STRUCT_FOR_ID(__truediv__)
246247
STRUCT_FOR_ID(__trunc__)

‎Include/internal/pycore_runtime_init_generated.h‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Include/internal/pycore_unicodeobject_generated.h‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Lib/abc.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def __init__(
105105
try:
106106
from _abc import (get_cache_token, _abc_init, _abc_register,
107107
_abc_instancecheck, _abc_subclasscheck, _get_dump,
108-
_reset_registry, _reset_caches)
108+
_reset_registry, _reset_caches, _set_subclasscheck)
109109
except ImportError:
110110
from _py_abc import ABCMeta, get_cache_token
111111
ABCMeta.__module__ = 'abc'
@@ -163,6 +163,10 @@ def _abc_caches_clear(cls):
163163
"""Clear the caches (for debugging or testing)."""
164164
_reset_caches(cls)
165165

166+
# Classes using the default __subclasscheck__ are checked
167+
# directly by the C implementation.
168+
_set_subclasscheck(ABCMeta.__subclasscheck__)
169+
166170

167171
def update_abstractmethods(cls):
168172
"""Recalculate the set of abstract methods of an abstract class.

‎Lib/test/test_abc.py‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,144 @@ class C:
556556
self.assertNotIsSubclass(C, A)
557557
self.assertNotIsSubclass(C, (A,))
558558

559+
def test_subclasshook_of_subclass(self):
560+
# The hook of a subclass of an ABC applies to the ABC too.
561+
class A(metaclass=abc_ABCMeta):
562+
pass
563+
class B(A):
564+
@classmethod
565+
def __subclasshook__(cls, C):
566+
if cls is B:
567+
return 'foo' in C.__dict__
568+
return NotImplemented
569+
class C:
570+
foo = 42
571+
class D:
572+
spam = 42
573+
self.assertIsSubclass(C, A)
574+
self.assertIsSubclass(C, B)
575+
self.assertNotIsSubclass(D, A)
576+
self.assertNotIsSubclass(D, B)
577+
self.assertIsInstance(C(), A)
578+
self.assertNotIsInstance(D(), A)
579+
580+
def test_subclasscheck_of_subclass_metaclass(self):
581+
# A __subclasscheck__ override on the metaclass of a subclass
582+
# is honoured when walking the subclass tree of an ABC.
583+
class Meta(abc_ABCMeta):
584+
def __subclasscheck__(cls, subclass):
585+
if subclass is int:
586+
return True
587+
return super().__subclasscheck__(subclass)
588+
class A(metaclass=abc_ABCMeta):
589+
pass
590+
class B(A, metaclass=Meta):
591+
pass
592+
self.assertIsSubclass(int, B)
593+
self.assertIsSubclass(int, A)
594+
self.assertNotIsSubclass(str, A)
595+
self.assertIsInstance(1, A)
596+
self.assertNotIsInstance('', A)
597+
598+
def test_subclasses_override_of_subclass(self):
599+
# A __subclasses__ override in a subclass is honoured.
600+
class Other:
601+
pass
602+
class A(metaclass=abc_ABCMeta):
603+
pass
604+
class B(A):
605+
@classmethod
606+
def __subclasses__(cls):
607+
return [Other]
608+
self.assertIsSubclass(Other, B)
609+
self.assertIsSubclass(Other, A)
610+
self.assertNotIsSubclass(int, A)
611+
612+
def test_registration_in_subclass_tree(self):
613+
class A(metaclass=abc_ABCMeta):
614+
pass
615+
class B(A):
616+
pass
617+
class C(B):
618+
pass
619+
class D:
620+
pass
621+
class E(D):
622+
pass
623+
self.assertNotIsSubclass(E, A)
624+
C.register(D)
625+
self.assertIsSubclass(D, C)
626+
self.assertIsSubclass(D, B)
627+
self.assertIsSubclass(D, A)
628+
self.assertIsSubclass(E, A)
629+
self.assertIsInstance(E(), A)
630+
self.assertNotIsSubclass(int, A)
631+
632+
def test_instancecheck_class_attribute(self):
633+
class A(metaclass=abc_ABCMeta):
634+
pass
635+
class B(A):
636+
pass
637+
class ClassProperty:
638+
@property
639+
def __class__(self):
640+
return B
641+
class GetAttribute:
642+
def __getattribute__(self, name):
643+
if name == '__class__':
644+
return B
645+
return object.__getattribute__(self, name)
646+
class ClassAttributeNotAType:
647+
__class__ = 42
648+
self.assertIsInstance(ClassProperty(), A)
649+
self.assertIsInstance(GetAttribute(), A)
650+
self.assertNotIsInstance(ClassProperty(), int)
651+
with self.assertRaises(TypeError):
652+
isinstance(ClassAttributeNotAType(), A)
653+
654+
def test_cache_with_transient_classes(self):
655+
# Classes come and go, and their addresses get reused; the
656+
# caches must never confuse a dead class with a new one.
657+
import gc
658+
class A(metaclass=abc_ABCMeta):
659+
pass
660+
for i in range(50):
661+
class Sub(A):
662+
pass
663+
class NotSub:
664+
pass
665+
self.assertIsSubclass(Sub, A)
666+
self.assertNotIsSubclass(NotSub, A)
667+
self.assertIsInstance(Sub(), A)
668+
self.assertNotIsInstance(NotSub(), A)
669+
A.register(NotSub)
670+
self.assertIsSubclass(NotSub, A)
671+
del Sub, NotSub
672+
gc.collect()
673+
674+
def test_negative_cache_not_populated_in_subclass_tree(self):
675+
# gh-92810: checking a class against an ABC must not add it to
676+
# the negative cache of every subclass of that ABC.
677+
if abc_ABCMeta is not abc.ABCMeta:
678+
self.skipTest('C implementation only')
679+
try:
680+
from _abc import _get_dump
681+
except ImportError:
682+
self.skipTest('C implementation only')
683+
class A(metaclass=abc_ABCMeta):
684+
pass
685+
subclasses = [type(f'B{i}', (A,), {}) for i in range(10)]
686+
class C:
687+
pass
688+
self.assertNotIsSubclass(C, A)
689+
self.assertEqual(len(_get_dump(A)[2]), 1)
690+
for B in subclasses:
691+
self.assertEqual(_get_dump(B)[2], set())
692+
# Results are cached at the top level only.
693+
self.assertNotIsSubclass(C, A)
694+
self.assertNotIsSubclass(C, subclasses[0])
695+
self.assertEqual(len(_get_dump(subclasses[0])[2]), 1)
696+
559697
def test_all_new_methods_are_called(self):
560698
class A(metaclass=abc_ABCMeta):
561699
pass
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import gc
2+
import os
3+
import threading
4+
import unittest
5+
from abc import ABC
6+
7+
from test.support import threading_helper
8+
9+
10+
class TestABC(unittest.TestCase):
11+
12+
@threading_helper.reap_threads
13+
@threading_helper.requires_working_threading()
14+
def test_concurrent_checks(self):
15+
# isinstance()/issubclass() from many threads while other threads
16+
# register classes, clear the caches and create and destroy
17+
# subclasses.
18+
class A(ABC):
19+
pass
20+
class B(A):
21+
pass
22+
class C(B):
23+
pass
24+
class Registered:
25+
pass
26+
class Other:
27+
pass
28+
A.register(Registered)
29+
instances = [B(), C(), Registered(), Other()]
30+
num_threads = 8
31+
iterations = 2000
32+
barrier = threading.Barrier(num_threads + 2)
33+
stop = threading.Event()
34+
errors = []
35+
36+
def checker():
37+
barrier.wait()
38+
try:
39+
for _ in range(iterations):
40+
for cls in (A, B, C):
41+
self.assertTrue(issubclass(C, cls))
42+
self.assertFalse(issubclass(Other, cls))
43+
self.assertFalse(isinstance(instances[3], cls))
44+
self.assertTrue(isinstance(instances[0], A))
45+
self.assertTrue(isinstance(instances[1], A))
46+
self.assertTrue(isinstance(instances[2], A))
47+
self.assertTrue(issubclass(Registered, A))
48+
self.assertFalse(isinstance(instances[0], C))
49+
except Exception as exc:
50+
errors.append(exc)
51+
finally:
52+
stop.set()
53+
54+
def mutator():
55+
barrier.wait()
56+
i = 0
57+
while not stop.is_set():
58+
# Transient classes get cached, registered and destroyed.
59+
Sub = type(f'Sub{i}', (B,), {})
60+
Plain = type(f'Plain{i}', (), {})
61+
self.assertTrue(issubclass(Sub, A))
62+
self.assertFalse(issubclass(Plain, A))
63+
A.register(Plain)
64+
self.assertTrue(issubclass(Plain, A))
65+
if i % 10 == 0:
66+
A._abc_caches_clear()
67+
B._abc_caches_clear()
68+
if i % 50 == 0:
69+
gc.collect()
70+
i += 1
71+
72+
threads = [threading.Thread(target=checker) for _ in range(num_threads)]
73+
threads += [threading.Thread(target=mutator) for _ in range(2)]
74+
with threading_helper.start_threads(threads):
75+
pass
76+
self.assertEqual(errors, [])
77+
78+
@threading_helper.reap_threads
79+
@threading_helper.requires_working_threading()
80+
def test_concurrent_registry_clear(self):
81+
class A(ABC):
82+
pass
83+
classes = [type(f'R{i}', (), {}) for i in range(32)]
84+
barrier = threading.Barrier(4)
85+
86+
def worker():
87+
barrier.wait()
88+
for _ in range(500):
89+
for cls in classes:
90+
A.register(cls)
91+
issubclass(cls, A)
92+
A._abc_registry_clear()
93+
A._abc_caches_clear()
94+
with open(os.devnull, 'w') as f:
95+
A._dump_registry(f)
96+
97+
threads = [threading.Thread(target=worker) for _ in range(4)]
98+
with threading_helper.start_threads(threads):
99+
pass
100+
101+
102+
if __name__ == "__main__":
103+
unittest.main()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Speed up :func:`isinstance` and :func:`issubclass` checks against
2+
:class:`abc.ABCMeta` classes, fix quadratic time and memory usage for large
3+
class hierarchies, and improve their scaling across threads in the
4+
free-threaded build. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)