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..8e0286818477 100644 --- a/cuda_core/cuda/core/_memory/_ipc.pyx +++ b/cuda_core/cuda/core/_memory/_ipc.pyx @@ -46,13 +46,53 @@ 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 = {} +# 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() +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_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): + with _registry_lock: + return _registry_lookup_locked(key) + + cdef cydriver.CUmemAllocationHandleType IPC_HANDLE_TYPE = \ cydriver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR \ if platform.system() == "Linux" else \ @@ -600,7 +640,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 +693,65 @@ 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: + # 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 + # its UUID since it was read, validate again. + changed = handle._uuid is not current + if not changed and not conflict: + registry[key] = ref + # 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(<_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/helpers/memory.py b/cuda_core/tests/helpers/memory.py index 435fdaf436f1..8f12e5712e89 100644 --- a/cuda_core/tests/helpers/memory.py +++ b/cuda_core/tests/helpers/memory.py @@ -78,6 +78,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 drain_on_exit(stack, synchronizable): """Make ``stack`` synchronize ``synchronizable`` (a stream or a device) when it closes. diff --git a/cuda_core/tests/memory_ipc/test_errors.py b/cuda_core/tests/memory_ipc/test_errors.py index 2806931c1c27..84cbb5c30473 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 @@ -123,6 +135,34 @@ 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_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. + """ + # 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") + + 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 1dd339a692d2..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 @@ -31,6 +33,7 @@ import_pool_resource, is_pool_resource, pool_access_flags, + pool_supported_devices, ) from helpers.misc import run_in_threads @@ -45,7 +48,8 @@ # 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 +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 @@ -158,9 +162,12 @@ def reimport(): stack.enter_context(buffer) # 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() @@ -202,6 +209,289 @@ 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_imported_pool(stack, mr_type, device, int(alloc_handle)) + rival = enter_imported_pool(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) + + +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. + + ``__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_imported_pool(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_imported_pool(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_imported_pool(stack, mr_type, device, int(alloc_handle)) + assert successor.register(key) is successor + 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_imported_pool(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 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) + # Set when the registrations end or any thread fails, to stop the others. + done = threading.Event() + + 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 + 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 + finally: + done.set() + + run_in_threads([register] + [look_up] * THREADS, barrier=barrier) + def _import_concurrently(mr_type, device, alloc_handle): barrier = threading.Barrier(THREADS) @@ -359,6 +649,42 @@ 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"]) + 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-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_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()