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
5 changes: 5 additions & 0 deletions cuda_core/tests/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ Follow these rules when adding or moving shared test code:
when the test needs to communicate with a running child or inspect its lifetime;
use `kill_subprocesses` before assertions and `track_child_processes` for
fixture cleanup so a stuck child cannot block IPC resource teardown.
- Run worker threads with `run_in_threads` from `helpers.misc` instead of
hand-written start/join loops. An exception in a thread otherwise only ends
that thread and the test can pass. The helper re-raises the first failure,
aborts a shared `threading.Barrier` so the other workers do not hang, and
with `timeout` fails on a thread that does not finish.
- Use the skip guards in `helpers/memory.py` instead of per-module copies:
`skip_if_mempool_unsupported`, `skip_if_managed_mempool_unsupported` (a
property check only; it never constructs a managed resource),
Expand Down
23 changes: 23 additions & 0 deletions cuda_core/tests/helpers/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

"""Memory-related test helpers (skip guards and resource factories)."""

import contextlib

import pytest

from cuda.core import Device, DeviceMemoryResource, ManagedMemoryResource, PinnedMemoryResource
Expand Down Expand Up @@ -76,6 +78,27 @@ def import_pool_resource(cls, device, alloc_handle):
return DeviceMemoryResource.from_allocation_handle(device, alloc_handle)


def drain_on_exit(stack, synchronizable):
"""Make ``stack`` synchronize ``synchronizable`` (a stream or a device) when it closes.

Closing a buffer imported from a memory pool enqueues a stream-ordered
``cuMemFreeAsync``, and the importer's free must complete before the
exporter frees the allocation. Call this before entering the imported
buffers on ``stack``: an ExitStack unwinds in reverse, so the sync then runs
after they close, also when the body raises.
"""
stack.callback(synchronizable.sync)


def enter_imported_pool(stack, cls, device, alloc_handle):
"""Import the pool like :func:`import_pool_resource`, and register it to close on ``stack``.

``stack`` is a :class:`contextlib.ExitStack`. A pool resource is not a
context manager, so it is entered through :func:`contextlib.closing`.
"""
return stack.enter_context(contextlib.closing(import_pool_resource(cls, device, alloc_handle)))


def pool_access_flags(mr, device):
"""The ``CUmemAccess_flags`` that ``device`` has on the memory pool of ``mr`` in this process."""
location = driver.CUmemLocation()
Expand Down
58 changes: 58 additions & 0 deletions cuda_core/tests/helpers/misc.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,67 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import threading

import pytest


def run_in_threads(targets, *, barrier=None, timeout=None):
"""Run each callable in ``targets`` on its own thread, and re-raise the first failure.

An exception in a thread would otherwise only end that thread. A thread that
raises aborts ``barrier``, if given, so the threads waiting at it raise
``threading.BrokenBarrierError`` instead of blocking forever; the original
exception is re-raised, not the broken barrier. If starting a thread fails,
the barrier is aborted the same way. Every started thread is joined (up to
``timeout``) before this returns or raises.

With ``timeout``, each join waits at most that many seconds, and a thread
still running afterwards (for example a deadlocked one) raises
``TimeoutError``, also when another thread failed; the failure is its
``__cause__``. Such a thread cannot be stopped, so callers must not
release anything it may still be using. The barrier is aborted first, so a
thread waiting at it (or reaching it later) raises
``threading.BrokenBarrierError`` and exits instead of blocking until the
interpreter shuts down. It does not run the code after its wait.
"""
errors = []

def run(target):
try:
target()
# pytest.fail and pytest.skip raise BaseException subclasses.
except BaseException as e:
errors.append(e)
if barrier is not None:
barrier.abort()

threads = [threading.Thread(target=run, args=(target,)) for target in targets]
started = []
try:
for thread in threads:
thread.start()
started.append(thread)
except BaseException:
if barrier is not None:
barrier.abort()
raise
finally:
for thread in started:
thread.join(timeout)
# Check liveness before reading ``errors``: a thread that has exited has already recorded its failure.
running = [thread.name for thread in started if thread.is_alive()]
failure = (
Comment thread
juenglin marked this conversation as resolved.
Resolved
next((e for e in errors if not isinstance(e, threading.BrokenBarrierError)), errors[0]) if errors else None
)
Comment thread
juenglin marked this conversation as resolved.
Resolved
if running:
if barrier is not None:
barrier.abort()
raise TimeoutError(f"threads still running after {timeout} s: {running}") from failure
if failure is not None:
raise failure


def try_create_condition(g, default_value=1):
"""Create a GraphCondition on graph *g*, skipping the test if unsupported."""
from cuda.core._utils.cuda_utils import CUDAError
Expand Down
26 changes: 8 additions & 18 deletions cuda_core/tests/memory/test_resource_live_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
"""

import gc
import threading

import pytest
from helpers.constants import POOL_SIZE
from helpers.memory import VMM_HANDLE_TYPE, skip_if_mempool_unsupported
from helpers.misc import run_in_threads

from cuda.core import (
DeviceMemoryResource,
Expand Down Expand Up @@ -115,25 +115,15 @@ def test_concurrent_owned_pool_construct_and_drop_returns_to_start(init_cuda):
before = _live_owned_mempool_count()
n_threads = 4
n_per_thread = 10
# An exception in a worker only kills that thread, which would leave the
# count balanced and the test passing; collect them and fail explicitly.
errors = []

def worker():
try:
init_cuda.set_current()
for _ in range(n_per_thread):
mr = _owned_pool(init_cuda)
del mr
except Exception as e:
errors.append(e)

threads = [threading.Thread(target=worker) for _ in range(n_threads)]
for t in threads:
t.start()
for t in threads:
t.join()
assert not errors, f"worker thread(s) raised: {errors!r}"
init_cuda.set_current()
for _ in range(n_per_thread):
mr = _owned_pool(init_cuda)
del mr

# A worker that raised would leave the count balanced; this fails the test instead.
run_in_threads([worker] * n_threads)
# Let any deferred deallocation settle.
gc.collect()
assert _live_owned_mempool_count() == before
25 changes: 15 additions & 10 deletions cuda_core/tests/memory_ipc/test_device_uuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,21 @@ def _receive(obj):
return {"device_id": obj.device_id, "device_uuid": obj.uuid}
if not isinstance(obj, Buffer):
return {"received": type(obj).__name__}
mr = obj.memory_resource
report = {"device_id": obj.device_id, "device_uuid": Device(obj.device_id).uuid}
host = (ctypes.c_ubyte * NBYTES)()
handle_return(driver.cuMemcpyDtoH(ctypes.addressof(host), int(obj.handle), NBYTES))
report["data"] = bytes(host)
if isinstance(mr, VirtualMemoryResource):
report["peer_uuids"] = [Device(peer).uuid for peer in mr.config.peers]
report["peer_access"] = [_access_flags(obj, peer) for peer in mr.config.peers]
obj.close()
return report
try:
mr = obj.memory_resource
report = {"device_id": obj.device_id, "device_uuid": Device(obj.device_id).uuid}
host = (ctypes.c_ubyte * NBYTES)()
handle_return(driver.cuMemcpyDtoH(ctypes.addressof(host), int(obj.handle), NBYTES))
report["data"] = bytes(host)
if isinstance(mr, VirtualMemoryResource):
report["peer_uuids"] = [Device(peer).uuid for peer in mr.config.peers]
report["peer_access"] = [_access_flags(obj, peer) for peer in mr.config.peers]
return report
finally:
obj.close()
# Unpickling bound the free to the default stream of the device it made
# current; drain it before the exporter frees its allocation.
Device().sync()


def _access_flags(buf, device_id):
Expand Down
3 changes: 3 additions & 0 deletions cuda_core/tests/memory_ipc/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ def child_main(self, pipe, device, mr):
exc_info = type(e), str(e)
else:
exc_info = None, None
# An import rejected after mapping (an oversized descriptor) enqueues the
# free of its mapping; drain it before the exporter frees its allocation.
self.device.sync()
pipe[1].put(exc_info)


Expand Down
3 changes: 3 additions & 0 deletions cuda_core/tests/memory_ipc/test_event_ipc.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ def child_main(self, log, q_in, q_out):
prefix_view(buffer, NBYTES).copy_from(twos, stream=stream2)
log("signaling parent")
q_out.put(None)
# Free the imported buffer after the copy; the sync drains both before
# the exporter frees its allocation.
buffer.close(stream2)
log("waiting")
stream2.sync()
log("done")
Expand Down
13 changes: 6 additions & 7 deletions cuda_core/tests/memory_ipc/test_ipc_concurrent_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import pytest
from helpers.child_processes import child_timeout_sec, kill_subprocesses
from helpers.misc import run_in_threads

from cuda.core import Buffer, Device

Expand Down Expand Up @@ -50,13 +51,11 @@ def importer():
barrier.wait()
Buffer.from_ipc_descriptor(mr, descriptor, stream=device.default_stream).close()

threads = [threading.Thread(target=importer) for _ in range(THREADS)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()

device.sync()
try:
run_in_threads([importer] * THREADS, barrier=barrier)
finally:
# Drain the imported frees before the exporter frees its allocation.
device.sync()


class TestIpcConcurrentImport:
Expand Down
29 changes: 16 additions & 13 deletions cuda_core/tests/memory_ipc/test_ipc_duplicate_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import pytest
from helpers.child_processes import child_timeout_sec, kill_subprocesses
from helpers.logging import TimestampedLogger
from helpers.memory import drain_on_exit

from cuda.core import Buffer, Device

Expand All @@ -37,22 +38,24 @@ def child_main(log, queue):
buffer_desc1 = queue.get()
buffer_desc2 = queue.get()

# Import the same buffer twice - should return same handle due to cache
buffer1 = Buffer.from_ipc_descriptor(mr, buffer_desc1, stream=device.default_stream)
buffer2 = Buffer.from_ipc_descriptor(mr, buffer_desc2, stream=device.default_stream)
# The closes below are the sequence under test; the stack repeats them as
# no-ops, and releases the first import if the second fails.
with contextlib.ExitStack() as stack:
drain_on_exit(stack, device)
# Import the same buffer twice - should return same handle due to cache
buffer1 = stack.enter_context(Buffer.from_ipc_descriptor(mr, buffer_desc1, stream=device.default_stream))
buffer2 = stack.enter_context(Buffer.from_ipc_descriptor(mr, buffer_desc2, stream=device.default_stream))

log(f"buffer1.handle = {buffer1.handle}")
log(f"buffer2.handle = {buffer2.handle}")
log(f"same handle: {buffer1.handle == buffer2.handle}")
log(f"buffer1.handle = {buffer1.handle}")
log(f"buffer2.handle = {buffer2.handle}")
log(f"same handle: {buffer1.handle == buffer2.handle}")

# Close both - should not crash
buffer1.close()
log("buffer1 closed")
# Close both - should not crash
buffer1.close()
log("buffer1 closed")

buffer2.close()
log("buffer2 closed")

device.sync()
buffer2.close()
log("buffer2 closed")
log("done")


Expand Down
28 changes: 10 additions & 18 deletions cuda_core/tests/memory_ipc/test_ipc_import_release_race.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
"""

import contextlib
import functools
import multiprocessing as mp
import threading
import time

import pytest
from helpers.child_processes import child_timeout_sec, kill_subprocesses
from helpers.misc import run_in_threads

from cuda.core import Buffer, Device

Expand All @@ -45,36 +47,26 @@ def child_main(queue):
nbytes = queue.get()

barrier = threading.Barrier(THREADS)
errors = []
iterations = [0] * THREADS

def worker(index):
Device().set_current()
stream = Device().create_stream()
local = Device().memory_resource.allocate(nbytes, stream=stream)
barrier.wait()
deadline = time.monotonic() + DURATION_SEC
try:
while time.monotonic() < deadline and not errors:
buffer = Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)
local.copy_from(buffer, stream=stream)
stream.sync()
buffer.close()
barrier.wait()
deadline = time.monotonic() + DURATION_SEC
# A failing worker aborts the barrier, which stops the others early.
while time.monotonic() < deadline and not barrier.broken:
with Buffer.from_ipc_descriptor(mr, descriptor, stream=stream) as buffer:
local.copy_from(buffer, stream=stream)
stream.sync()
iterations[index] += 1
except Exception as e:
errors.append(e)
finally:
local.close(stream)
stream.sync()

threads = [threading.Thread(target=worker, args=(i,)) for i in range(THREADS)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()

if errors:
raise errors[0]
run_in_threads([functools.partial(worker, i) for i in range(THREADS)], barrier=barrier)
assert all(iterations), iterations
device.sync()

Expand Down
Loading
Loading