Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cuda_core/cuda/core/_memory/_ipc.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions cuda_core/cuda/core/_memory/_ipc.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...
125 changes: 99 additions & 26 deletions cuda_core/cuda/core/_memory/_ipc.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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):
Expand Down
13 changes: 13 additions & 0 deletions cuda_core/tests/helpers/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
40 changes: 40 additions & 0 deletions cuda_core/tests/memory_ipc/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down
Loading
Loading