From 3daf1f1587bbc56cd93b9ce6145995af3a8ffe63 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 08:47:27 -0800 Subject: [PATCH 1/9] test(cuda.core): check access on every GPU after the racing re-import The release of an imported pool revokes device access one GPU at a time, so the test that re-imports a pool while the last owner is released must check that access survives on every GPU the pool grants it to, not only the current one. Add pool_supported_devices to name those GPUs. --- cuda_core/tests/helpers/memory.py | 13 +++++++++++++ .../memory_ipc/test_ipc_pool_duplicate_import.py | 7 +++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/cuda_core/tests/helpers/memory.py b/cuda_core/tests/helpers/memory.py index b32d60b3c4a9..e3168aad845b 100644 --- a/cuda_core/tests/helpers/memory.py +++ b/cuda_core/tests/helpers/memory.py @@ -76,6 +76,19 @@ def import_pool_resource(cls, device, alloc_handle): return DeviceMemoryResource.from_allocation_handle(device, alloc_handle) +def pool_supported_devices(mr_type, device): + """Devices on which an imported pool of ``mr_type`` grants access in this process. + + A pinned (host-NUMA) pool grants device access to every device that supports + host NUMA memory pools; a device pool grants access to its own device. Keep + this in sync with ``_PMR_grant_device_access``. + """ + if mr_type is PinnedMemoryResource: + return [d for d in Device.get_all_devices() if d.properties.host_numa_memory_pools_supported] + assert mr_type is DeviceMemoryResource, mr_type + return [device] + + def pool_access_flags(mr, device): """The ``CUmemAccess_flags`` that ``device`` has on the memory pool of ``mr`` in this process.""" location = driver.CUmemLocation() diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py index 075bdec233ba..ebeea8e4fe06 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py @@ -24,7 +24,7 @@ from helpers.child_processes import child_timeout_sec, run_child from helpers.contexts import assert_no_cuda_warning from helpers.latch import LatchKernel -from helpers.memory import import_pool_resource, is_pool_resource, pool_access_flags +from helpers.memory import import_pool_resource, is_pool_resource, pool_access_flags, pool_supported_devices from cuda.bindings import driver from cuda.core import Buffer, Device, DeviceMemoryResource @@ -174,9 +174,12 @@ def reimport(): raise errors[0] # The release has finished: its cleanup must have left the new import alone. + # The final release revokes access one GPU at a time, so check every GPU the + # pool grants access to, not only the default one. (mr,) = reimported (buffer,) = reimported_buffers - assert pool_access_flags(mr, device) == driver.CUmemAccess_flags.CU_MEM_ACCESS_FLAGS_PROT_READWRITE + for access_device in pool_supported_devices(mr_type, device): + assert pool_access_flags(mr, access_device) == driver.CUmemAccess_flags.CU_MEM_ACCESS_FLAGS_PROT_READWRITE buffer.fill(7, stream=stream) stream.sync() From a9637c9cad5698ff28e18f320b4cfe56bf17128b Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 09:07:02 -0800 Subject: [PATCH 2/9] fix(cuda.core): register an IPC pool with one step that runs no Python code MP_register looked a UUID up in a WeakValueDictionary and then inserted into it. Both are Python code, as is hashing a uuid.UUID, so a garbage-collection callback or finalizer can run between the lookup and the insertion and register the same UUID on the same thread. The registry lock is reentrant, so that call proceeds, inserts its resource and returns it, and the outer call then overwrites the entry: two resources own one driver pool and the registry holds only one of them. Key the registry by uuid.UUID.bytes, which a dict hashes and compares in C, and store a weakref.KeyedRef of the resource. MP_register does everything that can run Python code before it takes the lock. Under the lock it looks the key up, inserts the reference and sets the handle's UUID without running any Python code, so nothing can re-enter between the lookup and the insertion and there is no intermediate state or rollback. The removal callback takes the lock as well, which is safe because the lock is a leaf. Imports can share one IPCAllocationHandle; if another registration gave it its UUID between validation and the lock, the call validates again. register() and from_registry() now raise TypeError for a key that is not a uuid.UUID. Test the registration by interrupting it at every use of its key: a UUID subclass runs a nested registration, a nested registration followed by a close, or a failure at the k-th hash, comparison or bytes read, for k until the registration no longer reads the key, with separate and with shared handles. That needs no hook in the implementation. Also register one UUID from a garbage-collection callback while another import registers it, and check that the entry of a dropped resource is removed and its UUID can be reused. --- cuda_core/cuda/core/_memory/_ipc.pxd | 4 +- cuda_core/cuda/core/_memory/_ipc.pyi | 1 + cuda_core/cuda/core/_memory/_ipc.pyx | 103 +++++++--- cuda_core/tests/memory_ipc/test_errors.py | 12 ++ .../test_ipc_pool_duplicate_import.py | 182 +++++++++++++++++- 5 files changed, 273 insertions(+), 29 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_ipc.pxd b/cuda_core/cuda/core/_memory/_ipc.pxd index 2f47e521cdfc..228b0577482c 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pxd +++ b/cuda_core/cuda/core/_memory/_ipc.pxd @@ -11,8 +11,8 @@ from cuda.core._rt cimport FileDescriptorHandle # Holds _MemPool objects imported by this process. This enables # buffer serialization, as buffers can reduce to a pair comprising the memory # resource UUID (the key into this registry) and the serialized buffer -# descriptor. -cdef object registry +# descriptor. Maps ``uuid.UUID.bytes`` to a weak reference of the resource. +cdef dict registry # The IPC handle type for this platform. IPC is currently only supported on diff --git a/cuda_core/cuda/core/_memory/_ipc.pyi b/cuda_core/cuda/core/_memory/_ipc.pyi index ebeb839b058e..cd54e6373de0 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyi +++ b/cuda_core/cuda/core/_memory/_ipc.pyi @@ -215,5 +215,6 @@ class VirtualMemoryFabricBufferDescriptor(_VirtualMemoryDescriptor): def __eq__(self, other) -> bool: ... def __hash__(self) -> int: ... +def _registry_remove(ref): ... def _reduce_allocation_handle(alloc_handle: IPCAllocationHandle) -> tuple[object, ...]: ... def _reconstruct_allocation_handle(cls: type, df: object, uuid: uuid.UUID | None) -> IPCAllocationHandle: ... diff --git a/cuda_core/cuda/core/_memory/_ipc.pyx b/cuda_core/cuda/core/_memory/_ipc.pyx index 1719dc94e676..65d04f37740c 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -46,13 +46,41 @@ if TYPE_CHECKING: __all__ = [] -cdef object registry = weakref.WeakValueDictionary() -# Serializes MP_register. Reentrant: inserting into the registry allocates a -# weak reference, which can run a garbage-collection callback or finalizer that -# registers another resource on the same thread. +# Maps uuid.UUID.bytes to a weakref.KeyedRef of the registered resource. The key +# is bytes so that the dict hashes and compares it in C, without running Python. +cdef dict registry = {} +# Serializes registry writes (MP_register and the removal of dead entries). +# Reads do not take it. No Python code may run while it is held: a collection +# can start in Python code, and its callbacks and finalizers can register or +# drop resources on this thread. That includes hashing or comparing a +# uuid.UUID, calling a WeakValueDictionary method, raising, and dropping the +# last reference to a resource. Anything that can run Python goes before +# the lock, and errors are raised after it is released. cdef object _registry_lock = threading.RLock() +def _registry_remove(ref): + # Runs wherever the last reference to a registered resource is dropped. The + # registry lock is a leaf lock, so taking it here cannot deadlock. + key = ref.key + with _registry_lock: + # A newer entry may have replaced this one. + if registry.get(key) is ref: + del registry[key] + + +cdef bytes _registry_key(key): + if not isinstance(key, uuid.UUID): + raise TypeError(f"the key of a memory resource must be a uuid.UUID, got {type(key).__name__}") + return key.bytes + + +cdef inline _MemPool _registry_lookup(bytes key): + """The live resource registered under ``key``, or None.""" + ref = registry.get(key) + return None if ref is None else ref() + + cdef cydriver.CUmemAllocationHandleType IPC_HANDLE_TYPE = \ cydriver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR \ if platform.system() == "Linux" else \ @@ -600,7 +628,9 @@ cdef _MemPool MP_from_allocation_handle( # Quick exit for registry hits. uuid = getattr(alloc_handle, 'uuid', None) # no-cython-lint - mr = registry.get(uuid) + cdef _MemPool mr = None + if uuid is not None: + mr = _registry_lookup(_registry_key(uuid)) if mr is not None: _check_registered_type(mr, cls, uuid) MP_check_open(<_MemPool>mr) @@ -651,34 +681,55 @@ cdef _MemPool MP_from_allocation_handle( cdef _MemPool MP_from_registry(uuid): - cdef _MemPool mr - try: - mr = registry[uuid] - MP_check_open(mr) - return mr - except KeyError: - raise RuntimeError(f"Memory resource {uuid} was not found") from None + cdef _MemPool mr = _registry_lookup(_registry_key(uuid)) + if mr is None: + raise RuntimeError(f"Memory resource {uuid} was not found") + MP_check_open(mr) + return mr cdef _MemPool MP_register(_MemPool self, uuid): MP_check_open(self) - # The lookup and the insertion must be one step: without the GIL, two - # threads can both miss and register different resources for one UUID. - with _registry_lock: - existing = registry.get(uuid) + cdef IPCAllocationHandle handle = None + cdef _MemPool existing + cdef object current = None + cdef bint changed + cdef bint conflict = False + # Everything that can run Python code happens before the lock. + cdef bytes key = _registry_key(uuid) + ref = weakref.KeyedRef(self, _registry_remove, key) + if self.is_ipc_enabled: + handle = self._ipc_data._alloc_handle + while True: + changed = False + if handle is not None: + current = handle._uuid + conflict = current is not None and current != uuid + # The lookup and the insertion are one step: without the GIL, two threads + # could otherwise both miss and register different resources for one + # UUID, and a nested registration cannot run between them because no + # Python code runs here. See the comment at _registry_lock. + with _registry_lock: + existing = _registry_lookup(key) + if existing is None and handle is not None: + # Imports can share one handle. If another registration gave it + # its UUID since it was read, validate again. + changed = handle._uuid is not current + if not changed and not conflict: + registry[key] = ref + handle._uuid = uuid + return self if existing is not None: - MP_check_open(<_MemPool>existing) + MP_check_open(existing) return existing - if not self.is_ipc_enabled: + if handle is None: raise RuntimeError("Memory resource is not IPC-enabled") - if self.uuid is not None and self.uuid != uuid: - raise ValueError( - f"Cannot register memory resource with UUID {uuid}: " - f"the resource already has UUID {self.uuid}" - ) - registry[uuid] = self - self._ipc_data._alloc_handle._uuid = uuid - return self + if changed: + continue + raise ValueError( + f"Cannot register memory resource with UUID {uuid}: " + f"the resource already has UUID {current}" + ) cdef IPCAllocationHandle MP_export_mempool(_MemPool self): diff --git a/cuda_core/tests/memory_ipc/test_errors.py b/cuda_core/tests/memory_ipc/test_errors.py index e7a00327576b..ef0939f66097 100644 --- a/cuda_core/tests/memory_ipc/test_errors.py +++ b/cuda_core/tests/memory_ipc/test_errors.py @@ -90,6 +90,18 @@ def test_register_rejects_non_ipc_memory_resource(mempool_device): DeviceMemoryResource.from_registry(key) +@pytest.mark.agent_authored(model="claude-opus-5-5") +@pytest.mark.parametrize("key", ["not-a-uuid", 1, None], ids=["str", "int", "none"]) +def test_registry_rejects_a_key_that_is_not_a_uuid(mempool_device, key): + """The registry is keyed by UUID bytes; any other key is a TypeError, not an AttributeError.""" + mr = DeviceMemoryResource(mempool_device) + + with pytest.raises(TypeError, match="uuid.UUID"): + mr.register(key) + with pytest.raises(TypeError, match="uuid.UUID"): + DeviceMemoryResource.from_registry(key) + + # For the VirtualMR parameter case: # This test is not currently run in any CI job @pytest.mark.human_authored diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py index ebeea8e4fe06..6343a56d3f2b 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py @@ -37,7 +37,7 @@ # The owner's release sleeps this long in the race test, so the re-import overlaps it. RELEASE_DELAY_US = 50_000 RACE_ITERATIONS = 3 -REENTRY_ITERATIONS = 20 +REENTRY_ITERATIONS = 100 # these tests spawn new processes and files which fails for very many threads; # child processes and IPC fixtures are shared across workers (#2784); cap at two threads @@ -221,6 +221,168 @@ def register_during_collection(phase, info): gc.set_threshold(*threshold) gc.callbacks.remove(register_during_collection) + _register_one_uuid_during_collections(stack, mr_type, device, alloc_handle) + + +def _register_one_uuid_during_collections(stack, mr_type, device, alloc_handle): + # Two imports register one UUID, and every collection that starts while the + # first registers makes the second register it too. However the two + # interleave, both calls must return the one resource the registry holds. + registering = [] + nested_results = [] + + def register_during_collection(phase, info): + if phase == "start" and registering: + key, rival = registering + nested_results.append((key, rival.register(key))) + + threshold = gc.get_threshold() + gc.callbacks.append(register_during_collection) + try: + gc.set_threshold(1) + for _ in range(REENTRY_ITERATIONS): + mr = _enter_import(stack, mr_type, device, int(alloc_handle)) + rival = _enter_import(stack, mr_type, device, int(alloc_handle)) + key = uuid.uuid4() + registering[:] = [key, rival] + try: + registered = mr.register(key) + finally: + registering.clear() + assert registered is mr or registered is rival + assert mr_type.from_registry(key) is registered + assert all(result is registered for k, result in nested_results if k == key) + finally: + gc.set_threshold(*threshold) + gc.callbacks.remove(register_during_collection) + + +class _TripwireUUID(uuid.UUID): + """A UUID that calls ``tripwire`` whenever Python code reads its value. + + ``__hash__``, ``__eq__`` and ``bytes`` are how code that keeps a UUID in a + registry reaches the value. Each is a point where a garbage-collection + callback or finalizer could run in the middle of a registration, so a test + can inject code at every such point without a hook in the implementation. + """ + + def __init__(self, tripwire): + super().__init__(int=uuid.uuid4().int) + object.__setattr__(self, "_tripwire", tripwire) + + def __hash__(self): + self._tripwire() + return super().__hash__() + + def __eq__(self, other): + self._tripwire() + return super().__eq__(other) + + @property + def bytes(self): + self._tripwire() + return super().bytes + + +def _register_interrupted_at(index, register, action): + """Call ``register(key)``, running ``action(key)`` at the ``index``-th use of ``key`` inside it. + + Returns ``(key, fired, outcome)``: whether ``action`` ran, and what the call + returned or raised. + """ + state = {"armed": True, "remaining": index, "fired": False} + + def tripwire(): + if not state["armed"] or state["fired"]: + return + state["remaining"] -= 1 + if state["remaining"] == 0: + state["fired"] = True + action(key) + + key = _TripwireUUID(tripwire) + try: + outcome = register(key) + except Exception as e: # the outcome under test + outcome = e + finally: + state["armed"] = False + return key, state["fired"], outcome + + +def _run_interrupted_registration(mr_type, device, alloc_handle, case, shared_handle, index): + """Register one UUID with an import that is interrupted at the ``index``-th use of the key. + + Returns whether the interruption happened. ``case`` is what the + interruption does: ``keep`` registers the same UUID with another import, + ``close`` does that and then closes the winner, and ``fail`` raises. + """ + with contextlib.ExitStack() as stack: + first = _enter_import(stack, mr_type, device, int(alloc_handle)) + # Two imports share a handle only when one is built from the other's + # handle, which carries no UUID until one of them registers. + second_source = first.allocation_handle if shared_handle else int(alloc_handle) + second = _enter_import(stack, mr_type, device, second_source) + assert (second.allocation_handle is first.allocation_handle) == shared_handle + nested = [] + + def interrupt(key): + if case == "fail": + raise MemoryError("simulated failure at a use of the key") + nested.append(second.register(key)) + if case == "close": + second.close() + + key, fired, outcome = _register_interrupted_at(index, first.register, interrupt) + + if not fired: + assert outcome is first + return False + if case == "fail": + assert isinstance(outcome, MemoryError) + # The failed call must leave the resource as it was. + assert first.uuid is None + with pytest.raises(RuntimeError, match="was not found"): + mr_type.from_registry(key) + other = uuid.uuid4() + assert first.register(other) is first + assert first.uuid == other + return True + (winner,) = nested + if case == "keep": + assert winner.uuid == key + assert outcome is winner + assert mr_type.from_registry(key) is winner + else: + # The call found the closed winner, as it would for any closed hit. + assert outcome is winner or isinstance(outcome, RuntimeError) + return True + + +def child_register_interrupted_at_every_key_use(mr_type, alloc_handle, case, shared_handle): + with _child_device() as (device, _baseline): + index = 1 + while _run_interrupted_registration(mr_type, device, alloc_handle, case, shared_handle, index): + index += 1 + # Without a first interruption the sweep would prove nothing. + assert index > 1, "the registration never used its key" + + +def child_dead_registry_entry_is_removed(mr_type, alloc_handle): + with _child_device() as (device, _baseline), contextlib.ExitStack() as stack: + key = uuid.uuid4() + dead = import_pool_resource(mr_type, device, int(alloc_handle)) + assert dead.register(key) is dead + dead.close() + del dead + with pytest.raises(RuntimeError, match="was not found"): + mr_type.from_registry(key) + + # The UUID is free again for another import. + successor = _enter_import(stack, mr_type, device, int(alloc_handle)) + assert successor.register(key) is successor + assert mr_type.from_registry(key) is successor + def _import_concurrently(mr_type, device, alloc_handle): barrier = threading.Barrier(THREADS) @@ -384,6 +546,24 @@ def test_registration_reentered_from_garbage_collection(self, ipc_device, pool_r ipc_device.set_current() run_child(child_register_reentered_by_gc, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-opus-5-5") + @pytest.mark.parametrize("shared_handle", [False, True], ids=["separate_handles", "shared_handle"]) + @pytest.mark.parametrize("case", ["keep", "close", "fail"]) + def test_registration_interrupted_at_every_use_of_its_key(self, ipc_device, pool_resource, case, shared_handle): + ipc_device.set_current() + run_child( + child_register_interrupted_at_every_key_use, + type(pool_resource), + pool_resource.allocation_handle, + case, + shared_handle, + ) + + @pytest.mark.agent_authored(model="claude-opus-5-5") + def test_registry_entry_of_a_dropped_resource_is_removed(self, ipc_device, pool_resource): + ipc_device.set_current() + run_child(child_dead_registry_entry_is_removed, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-opus-5-5") def test_concurrent_imports_of_one_uuid_share_a_resource(self, ipc_device, pool_resource): ipc_device.set_current() From 76678b3f822b567cf4ee81cab09c0f4caca33cda Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 09:23:31 -0800 Subject: [PATCH 3/9] docs(cuda.core): note the one way a collection can start under the IPC registry lock If inserting into the registry fails, building the traceback allocates objects while _registry_lock is held, and on Python 3.11 that can start a garbage collection. Record the exception next to the rule that no Python code runs under the lock. --- cuda_core/cuda/core/_memory/_ipc.pyx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cuda_core/cuda/core/_memory/_ipc.pyx b/cuda_core/cuda/core/_memory/_ipc.pyx index 65d04f37740c..1b92a9b1f95b 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -55,7 +55,9 @@ cdef dict registry = {} # drop resources on this thread. That includes hashing or comparing a # uuid.UUID, calling a WeakValueDictionary method, raising, and dropping the # last reference to a resource. Anything that can run Python goes before -# the lock, and errors are raised after it is released. +# the lock, and errors are raised after it is released. One exception remains: +# if the insertion fails (for example with MemoryError), building the traceback +# allocates objects, which on Python 3.11 can start a collection under the lock. cdef object _registry_lock = threading.RLock() From 1aeab59c89d6f0a297017029398a39c02b93af4f Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 09:50:20 -0800 Subject: [PATCH 4/9] fix(cuda.core): set an IPC allocation handle's UUID only once MP_register assigned the handle's UUID on every successful registration. When the handle already held an equal but distinct uuid.UUID object, the assignment released the old object under the registry lock. The handle's UUID is read without that lock, by MP_register before it takes the lock and by IPCAllocationHandle.uuid, so on a free-threaded build a reader could load the old object, lose it to the release, and take a reference to freed memory. Releasing it under the lock could also run the __del__ of a uuid.UUID subclass there, where no Python code may run. Both cases are reachable through register(): an exported resource has a UUID from creation and can be registered under an equal one, and a handle shared by two imports keeps its UUID after the import that registered it is dropped. Assign the UUID only when the handle has none. The field then changes once, from None to an object that lives as long as the handle, so an unlocked read cannot see a released object. Test both routes by registering under an equal but distinct UUID and checking that the resource still returns the original object. Co-Authored-By: Claude Fable 5.2 --- cuda_core/cuda/core/_memory/_ipc.pyx | 9 +++++- cuda_core/tests/memory_ipc/test_errors.py | 26 +++++++++++++++++ .../test_ipc_pool_duplicate_import.py | 28 +++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/cuda_core/cuda/core/_memory/_ipc.pyx b/cuda_core/cuda/core/_memory/_ipc.pyx index 1b92a9b1f95b..52e5ea30f14a 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -719,7 +719,14 @@ cdef _MemPool MP_register(_MemPool self, uuid): changed = handle._uuid is not current if not changed and not conflict: registry[key] = ref - handle._uuid = uuid + # Write the UUID once. The handle's UUID is read without + # this lock (above and in IPCAllocationHandle.uuid), so + # replacing an equal UUID would release an object that + # another thread may be taking a reference to. Releasing it + # here could also run a uuid.UUID subclass's __del__ under + # the lock. + if current is None: + handle._uuid = uuid return self if existing is not None: MP_check_open(existing) diff --git a/cuda_core/tests/memory_ipc/test_errors.py b/cuda_core/tests/memory_ipc/test_errors.py index ef0939f66097..8628d9ae406e 100644 --- a/cuda_core/tests/memory_ipc/test_errors.py +++ b/cuda_core/tests/memory_ipc/test_errors.py @@ -135,6 +135,32 @@ def test_register_rejects_mismatched_uuid(ipc_memory_resource): assert mr.register(mr.uuid) is mr +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_register_keeps_the_uuid_object_the_resource_already_has(ipc_memory_resource): + """register() under an equal UUID keeps the UUID object the resource already has. + + The UUID of an allocation handle is read without a lock. Replacing the + object would release the old one while another thread may be taking a + reference to it, which is a use-after-free on a free-threaded build. + """ + mr = ipc_memory_resource + if not is_pool_resource(mr): + pytest.skip("allocation handles and the registry are pool-only") + + original = mr.uuid + assert original is not None + equal = uuid.UUID(bytes=original.bytes) + assert equal is not original + # Not registered yet, so the call below inserts rather than returning a hit. + with pytest.raises(RuntimeError, match="was not found"): + type(mr).from_registry(equal) + + assert mr.register(equal) is mr + + assert mr.uuid is original + assert type(mr).from_registry(equal) is mr + + @pytest.mark.skipif(os.name == "nt", reason="IPC allocation handles are not supported on Windows") @pytest.mark.agent_authored(model="gpt-5.6") def test_ipc_allocation_handle_state_tracks_close(): diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py index 6343a56d3f2b..4383e9c983cf 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py @@ -384,6 +384,29 @@ def child_dead_registry_entry_is_removed(mr_type, alloc_handle): assert mr_type.from_registry(key) is successor +def child_shared_handle_keeps_its_uuid_object(mr_type, alloc_handle): + with _child_device() as (device, _baseline), contextlib.ExitStack() as stack: + first = import_pool_resource(mr_type, device, int(alloc_handle)) + # Built from the first import's handle while it carries no UUID, so the + # two imports share that handle. + second = _enter_import(stack, mr_type, device, first.allocation_handle) + assert second.allocation_handle is first.allocation_handle + key = uuid.uuid4() + assert first.register(key) is first + first.close() + del first + with pytest.raises(RuntimeError, match="was not found"): + mr_type.from_registry(key) + + # The handle outlived its first owner and still has the UUID. Registering + # the second import under an equal UUID must not replace that object: + # the handle's UUID is read without a lock. + equal = uuid.UUID(bytes=key.bytes) + assert second.register(equal) is second + assert second.uuid is key + assert mr_type.from_registry(equal) is second + + def _import_concurrently(mr_type, device, alloc_handle): barrier = threading.Barrier(THREADS) results = [None] * THREADS @@ -564,6 +587,11 @@ def test_registry_entry_of_a_dropped_resource_is_removed(self, ipc_device, pool_ ipc_device.set_current() run_child(child_dead_registry_entry_is_removed, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-fable-5-2") + def test_shared_handle_keeps_its_uuid_object_after_its_first_owner(self, ipc_device, pool_resource): + ipc_device.set_current() + run_child(child_shared_handle_keeps_its_uuid_object, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-opus-5-5") def test_concurrent_imports_of_one_uuid_share_a_resource(self, ipc_device, pool_resource): ipc_device.set_current() From 50d49d19e58e0719e259e76467e6f9d4e95e4012 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 11:08:57 -0800 Subject: [PATCH 5/9] fix(cuda.core): read the IPC registry under its lock Without the GIL, a registry lookup outside _registry_lock had two problems: - Cython compiles get() on a typed dict into a borrowed lookup followed by a separate reference-count increment. A concurrent removal of a dead entry could free the weak reference in between. - A registration inserts the entry and then sets the handle's UUID. A lookup between the two returned a registered resource whose UUID was None. _registry_lookup now takes the lock, so every access to the registry is under it. The lock is reentrant; MP_register already calls the lookup while holding it. The new test registers and drops resources under one UUID on one thread while other threads look the UUID up. On a free-threaded CPython 3.14 build without the fix it failed in every run, with segfaults and with hits whose UUID was None. With the fix it passed in 20 runs. With the GIL it only checks that the lookups succeed. Co-Authored-By: Claude Fable 5.2 --- cuda_core/cuda/core/_memory/_ipc.pyx | 30 +++++---- .../test_ipc_pool_duplicate_import.py | 65 +++++++++++++++++++ 2 files changed, 84 insertions(+), 11 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_ipc.pyx b/cuda_core/cuda/core/_memory/_ipc.pyx index 52e5ea30f14a..3e2bd862f421 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -49,15 +49,20 @@ __all__ = [] # Maps uuid.UUID.bytes to a weakref.KeyedRef of the registered resource. The key # is bytes so that the dict hashes and compares it in C, without running Python. cdef dict registry = {} -# Serializes registry writes (MP_register and the removal of dead entries). -# Reads do not take it. No Python code may run while it is held: a collection -# can start in Python code, and its callbacks and finalizers can register or -# drop resources on this thread. That includes hashing or comparing a -# uuid.UUID, calling a WeakValueDictionary method, raising, and dropping the -# last reference to a resource. Anything that can run Python goes before -# the lock, and errors are raised after it is released. One exception remains: -# if the insertion fails (for example with MemoryError), building the traceback -# allocates objects, which on Python 3.11 can start a collection under the lock. +# Guards every access to the registry, reads included. Without the GIL a read +# needs it for two reasons. Cython reads a typed dict through a borrowed +# reference, which a concurrent removal can free before the read takes its own +# reference. And a registration inserts the entry and then sets the handle's +# UUID, so a reader must not run between the two. +# +# No Python code may run while it is held: a collection can start in Python +# code, and its callbacks and finalizers can register or drop resources on this +# thread. That includes hashing or comparing a uuid.UUID, calling a +# WeakValueDictionary method, raising, and dropping the last reference to a +# resource. Anything that can run Python goes before the lock, and errors are +# raised after it is released. One exception remains: if the insertion fails +# (for example with MemoryError), building the traceback allocates objects, +# which on Python 3.11 can start a collection under the lock. cdef object _registry_lock = threading.RLock() @@ -79,8 +84,11 @@ cdef bytes _registry_key(key): cdef inline _MemPool _registry_lookup(bytes key): """The live resource registered under ``key``, or None.""" - ref = registry.get(key) - return None if ref is None else ref() + # Takes the lock itself, so that no caller can read the registry without + # it. The lock is reentrant: MP_register calls this while holding it. + with _registry_lock: + ref = registry.get(key) + return None if ref is None else ref() cdef cydriver.CUmemAllocationHandleType IPC_HANDLE_TYPE = \ diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py index 4383e9c983cf..b12437a4a340 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py @@ -38,6 +38,7 @@ RELEASE_DELAY_US = 50_000 RACE_ITERATIONS = 3 REENTRY_ITERATIONS = 100 +LOOKUP_RACE_SECONDS = 0.5 # these tests spawn new processes and files which fails for very many threads; # child processes and IPC fixtures are shared across workers (#2784); cap at two threads @@ -407,6 +408,65 @@ def child_shared_handle_keeps_its_uuid_object(mr_type, alloc_handle): assert mr_type.from_registry(equal) is second +def child_lookups_race_registrations(mr_type, alloc_handle): + # Lookups run against registrations and against the removal of dead + # entries. Without the GIL, a lookup outside the registry lock could use a + # removed entry after it was freed, or find a resource whose UUID was not + # set yet. With the GIL neither can happen, and this test only checks + # that the lookups succeed. The test runs for a fixed time rather than a + # fixed number of registrations: with the GIL, the lookups leave the + # registering thread little time to run. + with _child_device() as (device, _baseline): + key = uuid.uuid4() + fd = int(alloc_handle) + barrier = threading.Barrier(THREADS + 1) + done = threading.Event() + errors = [] + + def register(): + try: + Device().set_current() + barrier.wait() + deadline = time.monotonic() + LOOKUP_RACE_SECONDS + while not done.is_set() and time.monotonic() < deadline: + # A raw file descriptor carries no UUID, so every import is + # a new resource with a handle of its own. + mr = import_pool_resource(mr_type, device, fd) + mr.register(key) + # Removes the entry, unless a lookup holds the resource. + del mr + except Exception as e: + errors.append(e) + barrier.abort() + finally: + done.set() + + def look_up(): + try: + Device().set_current() + barrier.wait() + while not done.is_set(): + try: + mr = mr_type.from_registry(key) + except RuntimeError as e: + if "was not found" not in str(e): + raise + continue + assert mr.uuid is key + # Holding it would keep its entry from being removed. + del mr + except Exception as e: + errors.append(e) + barrier.abort() + done.set() + + threads = [threading.Thread(target=register)] + threads += [threading.Thread(target=look_up) for _ in range(THREADS)] + _run_threads(threads) + if errors: + raise errors[0] + + def _import_concurrently(mr_type, device, alloc_handle): barrier = threading.Barrier(THREADS) results = [None] * THREADS @@ -592,6 +652,11 @@ def test_shared_handle_keeps_its_uuid_object_after_its_first_owner(self, ipc_dev ipc_device.set_current() run_child(child_shared_handle_keeps_its_uuid_object, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-opus-5-5") + def test_lookups_racing_registrations_find_registered_resources(self, ipc_device, pool_resource): + ipc_device.set_current() + run_child(child_lookups_race_registrations, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.agent_authored(model="claude-opus-5-5") def test_concurrent_imports_of_one_uuid_share_a_resource(self, ipc_device, pool_resource): ipc_device.set_current() From 30b2371feadf344556e0a064a7d5c9cd8dc9920e Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 11:33:27 -0800 Subject: [PATCH 6/9] test(cuda.core): give the equal-UUID registration test a resource of its own Free-threaded CI runs tests with pytest-run-parallel, whose threads share fixtures. With a shared ipc_memory_resource, one thread registered the resource before another checked that it was not registered yet, so the test failed under --parallel-threads. Each thread now creates its own resource with ipc_memory_resource_factory. Co-Authored-By: Claude Opus 5.5 --- cuda_core/tests/memory_ipc/test_errors.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cuda_core/tests/memory_ipc/test_errors.py b/cuda_core/tests/memory_ipc/test_errors.py index 13f6fa30e30e..84cbb5c30473 100644 --- a/cuda_core/tests/memory_ipc/test_errors.py +++ b/cuda_core/tests/memory_ipc/test_errors.py @@ -136,14 +136,16 @@ def test_register_rejects_mismatched_uuid(ipc_memory_resource): @pytest.mark.agent_authored(model="claude-fable-5-2") -def test_register_keeps_the_uuid_object_the_resource_already_has(ipc_memory_resource): +def test_register_keeps_the_uuid_object_the_resource_already_has(ipc_memory_resource_factory): """register() under an equal UUID keeps the UUID object the resource already has. The UUID of an allocation handle is read without a lock. Replacing the object would release the old one while another thread may be taking a reference to it, which is a use-after-free on a free-threaded build. """ - mr = ipc_memory_resource + # A resource of its own: pytest-run-parallel shares fixtures between its + # threads, and another thread could register a shared resource first. + mr = ipc_memory_resource_factory() if not is_pool_resource(mr): pytest.skip("allocation handles and the registry are pool-only") From 4ad816c8f15e10ad52870f3504b298e371b5a310 Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Tue, 24 Nov 2026 12:29:37 -0800 Subject: [PATCH 7/9] fix(cuda.core): avoid reentering the IPC registry lock Use the lock-held lookup helper during registration. Entering a second lock scope can allocate bound context manager methods and start a collection on Python 3.11 while the registry lock is held. A finalizer can then deadlock with weakref cleanup. Signed-off-by: Ralf W. Grosse-Kunstleve --- cuda_core/cuda/core/_memory/_ipc.pyx | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/cuda_core/cuda/core/_memory/_ipc.pyx b/cuda_core/cuda/core/_memory/_ipc.pyx index 3e2bd862f421..03237ddc383c 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -82,13 +82,15 @@ cdef bytes _registry_key(key): return key.bytes +cdef inline _MemPool _registry_lookup_locked(bytes key): + """Return the live resource, or None. The caller must hold _registry_lock.""" + ref = registry.get(key) + return None if ref is None else ref() + + cdef inline _MemPool _registry_lookup(bytes key): - """The live resource registered under ``key``, or None.""" - # Takes the lock itself, so that no caller can read the registry without - # it. The lock is reentrant: MP_register calls this while holding it. with _registry_lock: - ref = registry.get(key) - return None if ref is None else ref() + return _registry_lookup_locked(key) cdef cydriver.CUmemAllocationHandleType IPC_HANDLE_TYPE = \ @@ -720,7 +722,8 @@ cdef _MemPool MP_register(_MemPool self, uuid): # UUID, and a nested registration cannot run between them because no # Python code runs here. See the comment at _registry_lock. with _registry_lock: - existing = _registry_lookup(key) + # Entering another lock scope here can allocate and trigger GC. + existing = _registry_lookup_locked(key) if existing is None and handle is not None: # Imports can share one handle. If another registration gave it # its UUID since it was read, validate again. From 59b41126054ce8f5d8bd11f8d09fc0f58931b47a Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Tue, 24 Nov 2026 13:32:36 -0800 Subject: [PATCH 8/9] test(cuda.core): exercise GC during IPC pool registration On CPython 3.11, wait for another thread to look up a registered pool when garbage collection starts during registration. A nested registry lock can start GC while the lock is held and block that lookup. Signed-off-by: Ralf W. Grosse-Kunstleve --- .../test_ipc_pool_duplicate_import.py | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py index 9f916a0a0e44..1e8c7c4c6e59 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py @@ -16,9 +16,11 @@ import functools import gc import multiprocessing as mp +import sys import threading import time import uuid +from concurrent.futures import ThreadPoolExecutor, wait import helpers import pytest @@ -243,6 +245,54 @@ def register_during_collection(phase, info): gc.callbacks.remove(register_during_collection) +def child_gc_during_registration_allows_registry_lookup(mr_type, alloc_handle): + with ( + _child_device() as (device, _baseline), + contextlib.ExitStack() as stack, + ThreadPoolExecutor(max_workers=1) as worker, + ): + registered = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) + candidate = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) + registered_key = uuid.uuid4() + key = uuid.uuid4() + assert registered.register(registered_key) is registered + + # Start the worker before arming GC. Its lookup needs the same lock as + # weakref cleanup, so a GC callback waiting for it detects the inversion. + look_up = functools.partial(mr_type.from_registry, registered_key) + assert worker.submit(look_up).result() is registered + register = candidate.register + registering_thread = threading.get_ident() + lookup_timeout = child_timeout_sec() / 3 + lookups = [] + lookup_blocked = False + registering = False + + def look_up_during_collection(phase, info): + nonlocal lookup_blocked + if phase == "start" and registering and not lookup_blocked and threading.get_ident() == registering_thread: + future = worker.submit(look_up) + lookups.append(future) + _, pending = wait((future,), timeout=lookup_timeout) + lookup_blocked = bool(pending) + + threshold = gc.get_threshold() + gc.collect() + gc.callbacks.append(look_up_during_collection) + try: + gc.set_threshold(1) + registering = True + assert register(key) is candidate + finally: + registering = False + gc.set_threshold(*threshold) + gc.callbacks.remove(look_up_during_collection) + + assert lookups, "GC did not run during registration" + assert not lookup_blocked, "a registry lookup blocked the GC callback during registration" + assert all(future.result() is registered for future in lookups) + + class _TripwireUUID(uuid.UUID): """A UUID that calls ``tripwire`` whenever Python code reads its value. @@ -599,6 +649,14 @@ def test_registration_reentered_from_garbage_collection(self, ipc_device, pool_r ipc_device.set_current() run_child(child_register_reentered_by_gc, type(pool_resource), pool_resource.allocation_handle) + @pytest.mark.skipif(sys.version_info[:2] != (3, 11), reason="requires CPython 3.11's allocation-triggered GC") + @pytest.mark.agent_authored(model="gpt-6.2-sol") + def test_gc_during_registration_allows_registry_lookup(self, ipc_device, pool_resource): + ipc_device.set_current() + run_child( + child_gc_during_registration_allows_registry_lookup, type(pool_resource), pool_resource.allocation_handle + ) + @pytest.mark.agent_authored(model="claude-opus-5-5") @pytest.mark.parametrize("shared_handle", [False, True], ids=["separate_handles", "shared_handle"]) @pytest.mark.parametrize("case", ["keep", "close", "fail"]) From 0e3e3637924bcd39a0500759d4d1f794d3fe0df6 Mon Sep 17 00:00:00 2001 From: "Ralf W. Grosse-Kunstleve" Date: Tue, 24 Nov 2026 14:17:30 -0800 Subject: [PATCH 9/9] docs(cuda.core): clarify the IPC registry lock constraint Signed-off-by: Ralf W. Grosse-Kunstleve --- cuda_core/cuda/core/_memory/_ipc.pyx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cuda_core/cuda/core/_memory/_ipc.pyx b/cuda_core/cuda/core/_memory/_ipc.pyx index 03237ddc383c..8e0286818477 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -722,7 +722,9 @@ cdef _MemPool MP_register(_MemPool self, uuid): # UUID, and a nested registration cannot run between them because no # Python code runs here. See the comment at _registry_lock. with _registry_lock: - # Entering another lock scope here can allocate and trigger GC. + # Reuse the held lock. On CPython 3.11, binding the context manager + # methods for another lock scope can allocate GC-tracked objects + # and start a collection here. existing = _registry_lookup_locked(key) if existing is None and handle is not None: # Imports can share one handle. If another registration gave it