From 15fef6edc0bce9693b10ff55eb869da5888978b0 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 19:14:07 -0800 Subject: [PATCH 1/6] test(cuda.core): run test worker threads through a shared helper Several tests started and joined worker threads by hand, each with its own error handling, and some got it wrong: test_ipc_concurrent_import never collected worker exceptions, so a failing import let the test pass, and test_ipc_import_release_race could hang if a worker failed before reaching its barrier, which the parent then reported as the very race under test. Add run_in_threads to helpers/misc.py. It runs each callable on its own thread, joins every started thread, and re-raises the first failure (not a BrokenBarrierError). A failing thread, or a thread that fails to start, aborts the shared barrier so the other workers do not block forever. With a timeout, a thread still running after its join raises TimeoutError. Use it in test_ipc_pool_duplicate_import (replacing _run_threads), test_ipc_concurrent_import, test_ipc_import_release_race, test_resource_live_count, and the two threaded tests in test_program_cache, whose thread_b assertions were previously swallowed. test_memory's concurrent VMM grow test keeps its own loop: on a timeout it deliberately leaves buffers open that a stuck thread may still use. Where a worker failure now raises, the drain that used to follow the join moves into a finally block, and the release race closes each imported buffer with a with block. Unit tests cover the helper, and tests/AGENTS.md points to it. Signed-off-by: Ralf Juengling --- cuda_core/tests/AGENTS.md | 5 ++ cuda_core/tests/helpers/misc.py | 48 ++++++++++++ .../tests/memory/test_resource_live_count.py | 26 ++----- .../memory_ipc/test_ipc_concurrent_import.py | 13 ++-- .../test_ipc_import_release_race.py | 28 +++---- .../test_ipc_pool_duplicate_import.py | 77 +++++++------------ cuda_core/tests/test_helpers.py | 70 +++++++++++++++++ cuda_core/tests/test_program_cache.py | 54 +++++-------- 8 files changed, 194 insertions(+), 127 deletions(-) diff --git a/cuda_core/tests/AGENTS.md b/cuda_core/tests/AGENTS.md index 95e9188705af..9598ddc6e731 100644 --- a/cuda_core/tests/AGENTS.md +++ b/cuda_core/tests/AGENTS.md @@ -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), diff --git a/cuda_core/tests/helpers/misc.py b/cuda_core/tests/helpers/misc.py index ec879755cd25..5b799fb7f9c3 100644 --- a/cuda_core/tests/helpers/misc.py +++ b/cuda_core/tests/helpers/misc.py @@ -1,9 +1,57 @@ # 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 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``. Such a thread cannot be stopped, so callers must not + release anything it may still be using. + """ + 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) + if errors: + raise next((e for e in errors if not isinstance(e, threading.BrokenBarrierError)), errors[0]) + running = [thread.name for thread in started if thread.is_alive()] + if running: + raise TimeoutError(f"threads still running after {timeout} s: {running}") + + 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 diff --git a/cuda_core/tests/memory/test_resource_live_count.py b/cuda_core/tests/memory/test_resource_live_count.py index 892f11395c7c..7e0827e24f64 100644 --- a/cuda_core/tests/memory/test_resource_live_count.py +++ b/cuda_core/tests/memory/test_resource_live_count.py @@ -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, @@ -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 diff --git a/cuda_core/tests/memory_ipc/test_ipc_concurrent_import.py b/cuda_core/tests/memory_ipc/test_ipc_concurrent_import.py index a430d10dd527..3c48126dc0eb 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_concurrent_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_concurrent_import.py @@ -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 @@ -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: diff --git a/cuda_core/tests/memory_ipc/test_ipc_import_release_race.py b/cuda_core/tests/memory_ipc/test_ipc_import_release_race.py index 7e6a19b977ae..b2dd99acd1bb 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_import_release_race.py +++ b/cuda_core/tests/memory_ipc/test_ipc_import_release_race.py @@ -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 @@ -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() 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..2992fedb90f7 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 @@ -13,6 +13,7 @@ """ import contextlib +import functools import gc import multiprocessing as mp import threading @@ -25,6 +26,7 @@ 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.misc import run_in_threads from cuda.bindings import driver from cuda.core import Buffer, Device, DeviceMemoryResource @@ -49,14 +51,6 @@ def _enter_import(stack, mr_type, device, alloc_handle): return stack.enter_context(contextlib.closing(import_pool_resource(mr_type, device, alloc_handle))) -def _run_threads(threads): - """Start every thread, then join every thread.""" - for thread in threads: - thread.start() - for thread in threads: - thread.join() - - @contextlib.contextmanager def _child_device(): """Set the child's current device, and assert the owned-pool count returns to its baseline.""" @@ -139,39 +133,30 @@ def _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor): barrier = threading.Barrier(2) reimported = [] reimported_buffers = [] - errors = [] def release(): - try: - barrier.wait() - outstanding.close() - except Exception as e: - errors.append(e) - barrier.abort() + barrier.wait() + outstanding.close() def reimport(): - try: - Device().set_current() - barrier.wait() - # Start once the release is under way, inside its delay. - time.sleep(RELEASE_DELAY_US / 4 / 1e6) - # A raw file descriptor carries no UUID, so this is a real import, - # through an object the releasing thread never sees. - mr = import_pool_resource(mr_type, device, int(alloc_handle)) - reimported.append(mr) - reimported_buffers.append(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) - except Exception as e: - errors.append(e) - barrier.abort() - - _run_threads([threading.Thread(target=release), threading.Thread(target=reimport)]) - # Own whatever the thread made before looking at its errors. - for mr in reimported: - stack.enter_context(contextlib.closing(mr)) - for buffer in reimported_buffers: - stack.enter_context(buffer) - if errors: - raise errors[0] + Device().set_current() + barrier.wait() + # Start once the release is under way, inside its delay. + time.sleep(RELEASE_DELAY_US / 4 / 1e6) + # A raw file descriptor carries no UUID, so this is a real import, + # through an object the releasing thread never sees. + mr = import_pool_resource(mr_type, device, int(alloc_handle)) + reimported.append(mr) + reimported_buffers.append(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) + + try: + run_in_threads([release, reimport], barrier=barrier) + finally: + # Own whatever the thread made, also when a thread failed. + for mr in reimported: + stack.enter_context(contextlib.closing(mr)) + for buffer in reimported_buffers: + stack.enter_context(buffer) # The release has finished: its cleanup must have left the new import alone. (mr,) = reimported @@ -222,24 +207,20 @@ def register_during_collection(phase, info): def _import_concurrently(mr_type, device, alloc_handle): barrier = threading.Barrier(THREADS) results = [None] * THREADS - errors = [] def importer(index): - try: - Device().set_current() - barrier.wait() - results[index] = import_pool_resource(mr_type, device, alloc_handle) - except Exception as e: - errors.append(e) - barrier.abort() + Device().set_current() + barrier.wait() + results[index] = import_pool_resource(mr_type, device, alloc_handle) - _run_threads([threading.Thread(target=importer, args=(i,)) for i in range(THREADS)]) - if errors: + try: + run_in_threads([functools.partial(importer, i) for i in range(THREADS)], barrier=barrier) + except BaseException: # The imports that succeeded would otherwise stay open. for mr in results: if mr is not None: mr.close() - raise errors[0] + raise return results diff --git a/cuda_core/tests/test_helpers.py b/cuda_core/tests/test_helpers.py index 5cbf9c40bf14..dbd338d06f23 100644 --- a/cuda_core/tests/test_helpers.py +++ b/cuda_core/tests/test_helpers.py @@ -4,6 +4,7 @@ import ctypes import sys +import threading import time import types from contextlib import closing @@ -14,6 +15,7 @@ from helpers.latch import LatchKernel from helpers.logging import TimestampedLogger from helpers.memory import create_managed_memory_resource_or_skip +from helpers.misc import run_in_threads from helpers.oom_diagnostics import ( DEFAULT_FILENAME, OOM_MARKER, @@ -523,3 +525,71 @@ def test_managed_mr_helper_constructs_when_pool_is_usable(monkeypatch, concurren factory = _patch_managed_mr_factory(monkeypatch, concurrent_managed_access) assert create_managed_memory_resource_or_skip(*args, **kwargs) is factory.return_value factory.assert_called_once_with(*args, **kwargs) + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_run_in_threads_reraises_a_failure_after_joining_every_thread(): + finished = threading.Event() + + def fails(): + raise ValueError("worker failed") + + def finishes(): + time.sleep(0.05) + finished.set() + + with pytest.raises(ValueError, match="worker failed"): + run_in_threads([fails, finishes]) + assert finished.is_set() + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_run_in_threads_aborts_the_barrier_for_the_waiting_threads(): + barrier = threading.Barrier(3) + + def fails(): + raise ValueError("before the barrier") + + try: + # The waiting threads raise BrokenBarrierError, but the original failure is re-raised. + with pytest.raises(ValueError, match="before the barrier"): + run_in_threads([fails, barrier.wait, barrier.wait], barrier=barrier, timeout=10) + assert barrier.broken + finally: + # Release threads still waiting if the helper did not, so the process can exit. + barrier.abort() + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_run_in_threads_reports_a_thread_that_does_not_finish(): + release = threading.Event() + try: + with pytest.raises(TimeoutError, match="still running"): + run_in_threads([lambda: release.wait(30)], timeout=0.1) + finally: + release.set() + + +@pytest.mark.thread_unsafe(reason="patches threading.Thread.start") +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_run_in_threads_aborts_the_barrier_when_a_thread_fails_to_start(monkeypatch): + barrier = threading.Barrier(2) + real_start = threading.Thread.start + started = [] + + def start(self): + if started: + raise RuntimeError("cannot start") + started.append(self) + real_start(self) + + monkeypatch.setattr(threading.Thread, "start", start) + try: + # The started thread would otherwise wait at the barrier for a thread that never starts. + with pytest.raises(RuntimeError, match="cannot start"): + run_in_threads([barrier.wait, barrier.wait], barrier=barrier, timeout=10) + assert barrier.broken + assert not started[0].is_alive() + finally: + # Release the started thread if the helper did not, so the process can exit. + barrier.abort() diff --git a/cuda_core/tests/test_program_cache.py b/cuda_core/tests/test_program_cache.py index 04437e4c0be0..fec51558be45 100644 --- a/cuda_core/tests/test_program_cache.py +++ b/cuda_core/tests/test_program_cache.py @@ -3,10 +3,12 @@ # SPDX-License-Identifier: Apache-2.0 import abc +import functools import os import time import pytest +from helpers.misc import run_in_threads from cuda.core import _linker @@ -1969,13 +1971,9 @@ def coordinated_unlink(path): a_unlinked.set() assert b_reseeded.wait(timeout=5), "thread B didn't reseed in time" - delete_error: list[BaseException] = [] - def thread_a(): try: del cache[b"victim"] - except BaseException as exc: # pragma: no cover - surfaces below - delete_error.append(exc) finally: # Don't strand thread B if __delitem__ raised before the hook ran. a_unlinked.set() @@ -1987,17 +1985,10 @@ def thread_b(): _file_stream._unlink_with_sharing_retry = coordinated_unlink try: - ta = threading.Thread(target=thread_a) - tb = threading.Thread(target=thread_b) - ta.start() - tb.start() - ta.join(timeout=10) - tb.join(timeout=10) + run_in_threads([thread_a, thread_b], timeout=10) finally: _file_stream._unlink_with_sharing_retry = real_unlink - assert not delete_error, f"__delitem__ raised: {delete_error[0]!r}" - assert not ta.is_alive() and not tb.is_alive(), "race threads didn't finish" # Without the clamp, this would be -800. With it, max(0, 100-900) = 0. # The tracker still undercounts disk truth (which holds 'survivor' = 100), # but the next reseed will correct that, whereas a negative tracker would @@ -2495,35 +2486,26 @@ def test_inmemory_cache_concurrent_threads_stay_consistent(): n_readers = 4 ops_per_thread = 200 payload = b"v" * 64 - errors: list[BaseException] = [] barrier = threading.Barrier(n_writers + n_readers) def writer(tid: int) -> None: - try: - barrier.wait() - for i in range(ops_per_thread): - cache[f"w{tid}-{i}".encode()] = payload - except BaseException as exc: - errors.append(exc) + barrier.wait() + for i in range(ops_per_thread): + cache[f"w{tid}-{i}".encode()] = payload def reader(tid: int) -> None: - try: - barrier.wait() - for i in range(ops_per_thread): - # Touch a write key so reads sometimes hit and sometimes miss. - cache.get(f"w{i % n_writers}-{i}".encode()) - except BaseException as exc: - errors.append(exc) - - threads = [threading.Thread(target=writer, args=(t,)) for t in range(n_writers)] - threads += [threading.Thread(target=reader, args=(t,)) for t in range(n_readers)] - for t in threads: - t.start() - for t in threads: - t.join(timeout=30) - assert not t.is_alive(), "thread deadlocked" - - assert errors == [] + barrier.wait() + for i in range(ops_per_thread): + # Touch a write key so reads sometimes hit and sometimes miss. + cache.get(f"w{i % n_writers}-{i}".encode()) + + # A deadlocked thread fails the join timeout. + run_in_threads( + [functools.partial(writer, t) for t in range(n_writers)] + + [functools.partial(reader, t) for t in range(n_readers)], + barrier=barrier, + timeout=30, + ) # Internal accounting must agree with the cap and with __len__. assert cache._total_bytes <= 4096 assert len(cache) == len(cache._entries) # no orphan entries From 8b6929668a816c778e3dd4d04da6a3d475aa204a Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 19:38:58 -0800 Subject: [PATCH 2/6] test(cuda.core): drain imported pool frees before IPC test children exit 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. Several IPC test children broke that order: - test_ipc_pool_kind synchronized before closing, so the free stayed pending at exit. - TestIpcImportedPinnedBufferOnSecondDevice synchronized device 1, but unpickling had bound the buffer's free to device 0's default stream. - TestImportOversizedBufferDescriptorSize's expected rejection enqueues the free of what it mapped, and the harness never drained it. - test_event_ipc never closed its imported buffer, and test_device_uuid returned without a drain. - Many children drained only on success, so a failed assertion between the import and the close skipped both. Add drain_on_exit(stack, synchronizable) to helpers/memory.py. Registered on an ExitStack before the imported buffers, it synchronizes after they close, also when the body raises. Also move _enter_import from test_ipc_pool_duplicate_import to helpers/memory.py as enter_imported_pool, now that test_ipc_pool_kind uses it too. The children enter their imported buffers and pools on a stack with drain_on_exit; TestBufferPeerAccessAfterImport, which switches devices, repeats its close-and-drain tail in a finally block instead. VMM imports are unaffected: closing a VMM buffer synchronizes before it unmaps. Signed-off-by: Ralf Juengling --- cuda_core/tests/helpers/memory.py | 23 ++++ .../tests/memory_ipc/test_device_uuid.py | 25 ++-- cuda_core/tests/memory_ipc/test_errors.py | 3 + cuda_core/tests/memory_ipc/test_event_ipc.py | 3 + .../memory_ipc/test_ipc_duplicate_import.py | 29 +++-- .../test_ipc_pool_duplicate_import.py | 43 ++++--- .../tests/memory_ipc/test_ipc_pool_kind.py | 79 ++++++------ cuda_core/tests/memory_ipc/test_memory_ipc.py | 78 ++++++------ .../tests/memory_ipc/test_peer_access.py | 76 ++++++------ .../tests/memory_ipc/test_send_buffers.py | 16 ++- cuda_core/tests/memory_ipc/test_serialize.py | 113 +++++++++--------- 11 files changed, 266 insertions(+), 222 deletions(-) diff --git a/cuda_core/tests/helpers/memory.py b/cuda_core/tests/helpers/memory.py index b32d60b3c4a9..435fdaf436f1 100644 --- a/cuda_core/tests/helpers/memory.py +++ b/cuda_core/tests/helpers/memory.py @@ -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 @@ -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() diff --git a/cuda_core/tests/memory_ipc/test_device_uuid.py b/cuda_core/tests/memory_ipc/test_device_uuid.py index 97499a64c974..a3cc9e523364 100644 --- a/cuda_core/tests/memory_ipc/test_device_uuid.py +++ b/cuda_core/tests/memory_ipc/test_device_uuid.py @@ -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): diff --git a/cuda_core/tests/memory_ipc/test_errors.py b/cuda_core/tests/memory_ipc/test_errors.py index e7a00327576b..2806931c1c27 100644 --- a/cuda_core/tests/memory_ipc/test_errors.py +++ b/cuda_core/tests/memory_ipc/test_errors.py @@ -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) diff --git a/cuda_core/tests/memory_ipc/test_event_ipc.py b/cuda_core/tests/memory_ipc/test_event_ipc.py index c712ab6b2b6b..4df6fcb7c425 100644 --- a/cuda_core/tests/memory_ipc/test_event_ipc.py +++ b/cuda_core/tests/memory_ipc/test_event_ipc.py @@ -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") diff --git a/cuda_core/tests/memory_ipc/test_ipc_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_duplicate_import.py index 870e42f5b670..fcf237e2fe1c 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_duplicate_import.py +++ b/cuda_core/tests/memory_ipc/test_ipc_duplicate_import.py @@ -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 @@ -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") 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 2992fedb90f7..1dd339a692d2 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 @@ -25,7 +25,13 @@ 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 ( + drain_on_exit, + enter_imported_pool, + import_pool_resource, + is_pool_resource, + pool_access_flags, +) from helpers.misc import run_in_threads from cuda.bindings import driver @@ -46,11 +52,6 @@ pytestmark = pytest.mark.parallel_threads_limit(2) -def _enter_import(stack, mr_type, device, alloc_handle): - """Import the pool for ``alloc_handle`` and register it to close on ``stack``.""" - return stack.enter_context(contextlib.closing(import_pool_resource(mr_type, device, alloc_handle))) - - @contextlib.contextmanager def _child_device(): """Set the child's current device, and assert the owned-pool count returns to its baseline.""" @@ -63,8 +64,8 @@ def _child_device(): def _import_twice(stack, mr_type, device, alloc_handle): # A raw file descriptor carries no UUID, so the registry cannot dedupe. - first = _enter_import(stack, mr_type, device, int(alloc_handle)) - second = _enter_import(stack, mr_type, device, int(alloc_handle)) + first = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) + second = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) assert first is not second assert int(first.handle) == int(second.handle) return first, second @@ -72,11 +73,10 @@ def _import_twice(stack, mr_type, device, alloc_handle): def child_close_one_import(mr_type, alloc_handle, descriptor): # The stack closes the buffer, then both resources; the first is closed - # early on purpose, and closing it again is a no-op. It drains the stream - # last, so the imported free completes before the exporter frees its buffer. + # early on purpose, and closing it again is a no-op. with _child_device() as (device, baseline), contextlib.ExitStack() as stack: stream = device.default_stream - stack.callback(stream.sync) + drain_on_exit(stack, stream) first, second = _import_twice(stack, mr_type, device, alloc_handle) assert _live_owned_mempool_count() == baseline + 1 @@ -90,11 +90,10 @@ def child_close_one_import(mr_type, alloc_handle, descriptor): def child_close_both_imports_with_outstanding_buffer(mr_type, alloc_handle, descriptor): # The closes below are the sequence under test; the stack repeats them as - # no-ops, and releases whatever a failed assertion leaves open. It drains the - # stream last, so a failure partway still completes the imported frees. + # no-ops, and releases whatever a failed assertion leaves open. with _child_device() as (device, baseline), assert_no_cuda_warning(), contextlib.ExitStack() as stack: stream = device.default_stream - stack.callback(stream.sync) + drain_on_exit(stack, stream) first, second = _import_twice(stack, mr_type, device, alloc_handle) assert _live_owned_mempool_count() == baseline + 1 # The buffer keeps the pool alive after both resources are closed. @@ -122,7 +121,7 @@ def _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor): # stream after it has synchronized the pending frees. with contextlib.ExitStack() as stack: stack.enter_context(contextlib.closing(stream)) - stack.callback(stream.sync) + drain_on_exit(stack, stream) # The buffer holds the last reference to the pool once its resource is # closed, so closing the buffer releases the pool. @@ -180,7 +179,7 @@ def child_reimport_races_last_release(mr_type, alloc_handle, descriptor): def child_register_reentered_by_gc(mr_type, alloc_handle): # The stack closes the imports, then the nested resource. with _child_device() as (device, _baseline), contextlib.ExitStack() as stack: - nested = _enter_import(stack, mr_type, device, int(alloc_handle)) + nested = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) nested_uuid = uuid.uuid4() nested.register(nested_uuid) @@ -197,7 +196,7 @@ def register_during_collection(phase, info): gc.set_threshold(1) for _ in range(REENTRY_ITERATIONS): # A raw file descriptor carries no UUID, so each import registers a new one. - mr = _enter_import(stack, mr_type, device, int(alloc_handle)) + mr = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) assert mr.register(uuid.uuid4()) is mr finally: gc.set_threshold(*threshold) @@ -247,10 +246,10 @@ def child_concurrent_uuid_imports(mr_type, alloc_handle): def _import_by_path(stack, import_path, mr_type, device, alloc_handle): """Import the pool as ``import_path`` names; ``stack`` closes every resource the import made.""" if import_path == "single": - return [_enter_import(stack, mr_type, device, alloc_handle)] + return [enter_imported_pool(stack, mr_type, device, alloc_handle)] if import_path == "raw_handle": # A raw file descriptor carries no UUID, so each import is a real import. - return [_enter_import(stack, mr_type, device, int(alloc_handle)) for _ in range(THREADS)] + return [enter_imported_pool(stack, mr_type, device, int(alloc_handle)) for _ in range(THREADS)] assert import_path == "concurrent_uuid", import_path return [stack.enter_context(contextlib.closing(mr)) for mr in _import_concurrently(mr_type, device, alloc_handle)] @@ -299,10 +298,8 @@ def child_reimport_after_release_with_pending_free(mr_type, alloc_handle, descri # latch can release itself and let the free retire unobserved. latch = LatchKernel(device, timeout_sec=4 * child_timeout_sec()) stack.callback(latch.close) - # On every path, release the latch and then drain the stream: the - # imported frees must complete before the exporter frees its allocation, - # and a held latch would stall the drain. - stack.callback(stream.sync) + drain_on_exit(stack, stream) + # Registered after the drain so that it runs first: a held latch would stall the drain. stack.callback(latch.release) _release_import_holding_free(import_path, mr_type, device, alloc_handle, descriptor, stream, latch) _reimport_and_check_grant(import_path, mr_type, device, alloc_handle, descriptor, stream, latch) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py index 333453dcc2e5..b7edc0192265 100644 --- a/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py +++ b/cuda_core/tests/memory_ipc/test_ipc_pool_kind.py @@ -19,6 +19,8 @@ from helpers.constants import POOL_SIZE from helpers.contexts import assert_no_cuda_warning from helpers.memory import ( + drain_on_exit, + enter_imported_pool, import_pool_resource, is_pool_resource, pool_access_flags, @@ -87,12 +89,11 @@ def child_mismatched_import_raises(mr_type, alloc_handle, descriptor): assert _live_owned_mempool_count() == baseline # The rejected imports did not register the UUID, so the matching class imports it. - mr = import_pool_resource(mr_type, device, alloc_handle) - buffer = Buffer.from_ipc_descriptor(mr, descriptor, stream=stream) - buffer.fill(7, stream=stream) - stream.sync() - buffer.close() - mr.close() + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + mr = enter_imported_pool(stack, mr_type, device, alloc_handle) + buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) + buffer.fill(7, stream=stream) assert _live_owned_mempool_count() == baseline @@ -104,22 +105,23 @@ def child_rejected_import_keeps_existing_import(mr_type, alloc_handle, descripto # The driver returns the same pool for every import in a process, so the # rejected import must not destroy the pool or revoke any device's access # to it, including peer access and while a buffer from it is alive. - mr = import_pool_resource(mr_type, device, int(alloc_handle)) - if mr_type is DeviceMemoryResource: - mr.peer_accessible_by = [ - dev for dev in Device.get_all_devices() if dev.device_id != device.device_id and dev.can_access_peer(device) - ] - buffer = Buffer.from_ipc_descriptor(mr, descriptor, stream=stream) - access = _access_by_device(mr) - assert access[device.device_id] == driver.CUmemAccess_flags.CU_MEM_ACCESS_FLAGS_PROT_READWRITE + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + mr = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) + if mr_type is DeviceMemoryResource: + mr.peer_accessible_by = [ + dev + for dev in Device.get_all_devices() + if dev.device_id != device.device_id and dev.can_access_peer(device) + ] + buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) + access = _access_by_device(mr) + assert access[device.device_id] == driver.CUmemAccess_flags.CU_MEM_ACCESS_FLAGS_PROT_READWRITE - _assert_import_raises(mr_type, device, int(alloc_handle)) - assert _access_by_device(mr) == access + _assert_import_raises(mr_type, device, int(alloc_handle)) + assert _access_by_device(mr) == access - buffer.fill(7, stream=stream) - stream.sync() - buffer.close() - mr.close() + buffer.fill(7, stream=stream) def child_imported_numa_id(alloc_handle, numa_id): @@ -134,18 +136,16 @@ def child_matching_import(mr_type, alloc_handle, descriptor): device.set_current() stream = device.default_stream - # The raw file descriptor and the IPCAllocationHandle are the two import paths. - from_fd = import_pool_resource(mr_type, device, int(alloc_handle)) - from_handle = import_pool_resource(mr_type, device, alloc_handle) - assert isinstance(from_fd, mr_type) - assert isinstance(from_handle, mr_type) + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + # The raw file descriptor and the IPCAllocationHandle are the two import paths. + from_fd = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) + from_handle = enter_imported_pool(stack, mr_type, device, alloc_handle) + assert isinstance(from_fd, mr_type) + assert isinstance(from_handle, mr_type) - buffer = Buffer.from_ipc_descriptor(from_fd, descriptor, stream=stream) - buffer.fill(7, stream=stream) - stream.sync() - buffer.close() - from_fd.close() - from_handle.close() + buffer = stack.enter_context(Buffer.from_ipc_descriptor(from_fd, descriptor, stream=stream)) + buffer.fill(7, stream=stream) def child_import_without_location_query(mr_type, alloc_handle, descriptor): @@ -163,15 +163,14 @@ def child_import_without_location_query(mr_type, alloc_handle, descriptor): # runs the other class's initialization on the wrong kind of pool, which # can fail on some topologies (a pinned import of a device pool grants # every device access, which needs peer access; #3540). - mr = import_pool_resource(mr_type, device, int(alloc_handle)) - if mr_type is PinnedMemoryResource: - # Without the location query the pool's node is unknown (see numa_id). - assert mr.numa_id == 0 - buffer = Buffer.from_ipc_descriptor(mr, descriptor, stream=stream) - buffer.fill(7, stream=stream) - stream.sync() - buffer.close() - mr.close() + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + mr = enter_imported_pool(stack, mr_type, device, int(alloc_handle)) + if mr_type is PinnedMemoryResource: + # Without the location query the pool's node is unknown (see numa_id). + assert mr.numa_id == 0 + buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) + buffer.fill(7, stream=stream) class _IpcPoolFixtures: diff --git a/cuda_core/tests/memory_ipc/test_memory_ipc.py b/cuda_core/tests/memory_ipc/test_memory_ipc.py index ae6ea00adcfb..b30b5873eb01 100644 --- a/cuda_core/tests/memory_ipc/test_memory_ipc.py +++ b/cuda_core/tests/memory_ipc/test_memory_ipc.py @@ -9,6 +9,7 @@ from helpers.child_processes import child_timeout_sec, kill_subprocesses from helpers.constants import POOL_SIZE from helpers.memory import ( + drain_on_exit, import_pool_resource, is_pool_resource, pool_access_flags, @@ -87,14 +88,14 @@ def child_main(self, device, mr, queue): device.set_current() if is_pool_resource(mr): assert mr.is_mapped - buffer = queue.get(timeout=CHILD_TIMEOUT_SEC) - assert buffer.is_mapped stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.verify_buffer(buffer, seed=False) - pgen.fill_buffer(buffer, seed=True) - buffer.close() - stream.sync() + with ExitStack() as stack: + drain_on_exit(stack, stream) + buffer = stack.enter_context(queue.get(timeout=CHILD_TIMEOUT_SEC)) + assert buffer.is_mapped + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.verify_buffer(buffer, seed=False) + pgen.fill_buffer(buffer, seed=True) class TestIPCMempoolMultiple: @@ -142,17 +143,16 @@ def child_main(self, device, mr, seed, queue): # Note: passing the mr registers it so that buffers can be passed # directly. device.set_current() - buffer1 = queue.get(timeout=CHILD_TIMEOUT_SEC) - buffer2 = queue.get(timeout=CHILD_TIMEOUT_SEC) stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - if seed == 1: - pgen.fill_buffer(buffer1, seed=1) - elif seed == 2: - pgen.fill_buffer(buffer2, seed=2) - buffer1.close() - buffer2.close() - stream.sync() + with ExitStack() as stack: + drain_on_exit(stack, stream) + buffer1 = stack.enter_context(queue.get(timeout=CHILD_TIMEOUT_SEC)) + buffer2 = stack.enter_context(queue.get(timeout=CHILD_TIMEOUT_SEC)) + pgen = PatternGen(device, NBYTES, stream=stream) + if seed == 1: + pgen.fill_buffer(buffer1, seed=1) + elif seed == 2: + pgen.fill_buffer(buffer2, seed=2) class TestIPCSharedAllocationHandleAndBufferDescriptors: @@ -206,11 +206,11 @@ def child_main(self, device, token, seed, queue): mr = _import_token(device, token) buffer_descriptor = queue.get(timeout=CHILD_TIMEOUT_SEC) stream = device.default_stream - buffer = Buffer.from_ipc_descriptor(mr, buffer_descriptor, stream=stream) - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer, seed=seed) - buffer.close() - stream.sync() + with ExitStack() as stack: + drain_on_exit(stack, stream) + buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, buffer_descriptor, stream=stream)) + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer, seed=seed) class TestIPCSharedAllocationHandleAndBufferObjects: @@ -264,12 +264,12 @@ def child_main(self, device, token, seed, queue): _import_token(device, token) # Now get buffers. - buffer = queue.get(timeout=CHILD_TIMEOUT_SEC) stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer, seed=seed) - buffer.close() - stream.sync() + with ExitStack() as stack: + drain_on_exit(stack, stream) + buffer = stack.enter_context(queue.get(timeout=CHILD_TIMEOUT_SEC)) + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer, seed=seed) class TestIpcImportedBufferDeviceAccess: @@ -312,11 +312,11 @@ def test_main(self, ipc_device, ipc_memory_resource): def child_main(self, device, mr, queue): device.set_current() - buffer = queue.get(timeout=CHILD_TIMEOUT_SEC) stream = device.default_stream - prefix_view(buffer, NBYTES).fill(self.FILL_VALUE, stream=stream) - buffer.close() - stream.sync() + with ExitStack() as stack: + drain_on_exit(stack, stream) + buffer = stack.enter_context(queue.get(timeout=CHILD_TIMEOUT_SEC)) + prefix_view(buffer, NBYTES).fill(self.FILL_VALUE, stream=stream) def _pinned_pool_access(mr): @@ -418,9 +418,13 @@ def test_main(self, ipc_mempool_device_x2): PatternGen(dev1, NBYTES, stream=stream).verify_buffer(buffer, value=self.FILL_VALUE) def child_main(self, buffer): - device = Device(1) - device.set_current() - stream = device.default_stream - prefix_view(buffer, NBYTES).fill(self.FILL_VALUE, stream=stream) - stream.sync() - buffer.close() + with ExitStack() as stack: + # Unpickling bound the buffer's free to the default stream of device + # 0, current at the time, so drain device 0, not the stream used here. + drain_on_exit(stack, Device(0)) + stack.enter_context(buffer) + device = Device(1) + device.set_current() + stream = device.default_stream + prefix_view(buffer, NBYTES).fill(self.FILL_VALUE, stream=stream) + stream.sync() diff --git a/cuda_core/tests/memory_ipc/test_peer_access.py b/cuda_core/tests/memory_ipc/test_peer_access.py index 6f9e2cb870ab..dfb1c2e58f16 100644 --- a/cuda_core/tests/memory_ipc/test_peer_access.py +++ b/cuda_core/tests/memory_ipc/test_peer_access.py @@ -105,43 +105,45 @@ def test_main(self, ipc_mempool_device_x2, grant_access_in_parent): mr.close() def child_main(self, mr, buffer): - # Verify MR and buffer are mapped - Device(1).set_current() - assert mr.is_mapped is True - assert buffer.is_mapped is True - assert mr.device_id == 1 - assert buffer.device_id == 1 - - # Test 1: Buffer accessible from resident device (dev1) - should always work dev1 = Device(1) - dev1.set_current() - stream1 = dev1.default_stream - PatternGen(dev1, NBYTES, stream=stream1).verify_buffer(buffer, seed=False) - - # Test 2: Buffer NOT accessible from dev0 initially (peer access not preserved) - dev0 = Device(0) - dev0.set_current() - stream0 = dev0.default_stream - with pytest.raises(CUDAError, match="CUDA_ERROR_INVALID_VALUE"): - PatternGen(dev0, NBYTES, stream=stream0).verify_buffer(buffer, seed=False) - - # Test 3: Set peer access and verify buffer becomes accessible - dev1.set_current() - mr.peer_accessible_by = [0] - assert mr.peer_accessible_by == {dev0} - dev0.set_current() - PatternGen(dev0, NBYTES, stream=stream0).verify_buffer(buffer, seed=False) - - # Test 4: Revoke peer access and verify buffer becomes inaccessible - dev1.set_current() - mr.peer_accessible_by = [] - assert mr.peer_accessible_by == set() - dev0.set_current() - with pytest.raises(CUDAError, match="CUDA_ERROR_INVALID_VALUE"): + try: + # Verify MR and buffer are mapped + dev1.set_current() + assert mr.is_mapped is True + assert buffer.is_mapped is True + assert mr.device_id == 1 + assert buffer.device_id == 1 + + # Test 1: Buffer accessible from resident device (dev1) - should always work + stream1 = dev1.default_stream + PatternGen(dev1, NBYTES, stream=stream1).verify_buffer(buffer, seed=False) + + # Test 2: Buffer NOT accessible from dev0 initially (peer access not preserved) + dev0 = Device(0) + dev0.set_current() + stream0 = dev0.default_stream + with pytest.raises(CUDAError, match="CUDA_ERROR_INVALID_VALUE"): + PatternGen(dev0, NBYTES, stream=stream0).verify_buffer(buffer, seed=False) + + # Test 3: Set peer access and verify buffer becomes accessible + dev1.set_current() + mr.peer_accessible_by = [0] + assert mr.peer_accessible_by == {dev0} + dev0.set_current() PatternGen(dev0, NBYTES, stream=stream0).verify_buffer(buffer, seed=False) - dev1.set_current() - buffer.close() - # TODO(seberg): 2026-06: mr close may be unsafe with incomplete `buf.close()` - dev1.sync() - mr.close() + # Test 4: Revoke peer access and verify buffer becomes inaccessible + dev1.set_current() + mr.peer_accessible_by = [] + assert mr.peer_accessible_by == set() + dev0.set_current() + with pytest.raises(CUDAError, match="CUDA_ERROR_INVALID_VALUE"): + PatternGen(dev0, NBYTES, stream=stream0).verify_buffer(buffer, seed=False) + finally: + # Also when a check failed: unpickling bound the buffer's free to + # dev1, so close and drain it there before the exporter frees it. + dev1.set_current() + buffer.close() + # TODO(seberg): 2026-06: mr close may be unsafe with incomplete `buf.close()` + dev1.sync() + mr.close() diff --git a/cuda_core/tests/memory_ipc/test_send_buffers.py b/cuda_core/tests/memory_ipc/test_send_buffers.py index 89efd2d0af98..17103245c51c 100644 --- a/cuda_core/tests/memory_ipc/test_send_buffers.py +++ b/cuda_core/tests/memory_ipc/test_send_buffers.py @@ -1,12 +1,14 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import contextlib import multiprocessing as mp from itertools import cycle import pytest from helpers.buffers import PatternGen from helpers.child_processes import child_timeout_sec, kill_subprocesses +from helpers.memory import drain_on_exit from cuda.core import Device, VirtualMemoryResource @@ -63,12 +65,14 @@ def test_main(self, ipc_device, ipc_memory_resource_factory, nmrs): def child_main(self, device, buffers): device.set_current() stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - for buffer in buffers: - pgen.verify_buffer(buffer, seed=False) - pgen.fill_buffer(buffer, seed=True) - buffer.close() - stream.sync() + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + for buffer in buffers: + stack.enter_context(buffer) + pgen = PatternGen(device, NBYTES, stream=stream) + for buffer in buffers: + pgen.verify_buffer(buffer, seed=False) + pgen.fill_buffer(buffer, seed=True) class TestIpcReexport: diff --git a/cuda_core/tests/memory_ipc/test_serialize.py b/cuda_core/tests/memory_ipc/test_serialize.py index bb1a1fd50e5f..f64ba51aa433 100644 --- a/cuda_core/tests/memory_ipc/test_serialize.py +++ b/cuda_core/tests/memory_ipc/test_serialize.py @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import contextlib import multiprocessing as mp import multiprocessing.reduction import os @@ -8,7 +9,7 @@ import pytest from helpers.buffers import PatternGen from helpers.child_processes import child_timeout_sec, kill_subprocesses -from helpers.memory import import_pool_resource, is_pool_resource +from helpers.memory import drain_on_exit, import_pool_resource, is_pool_resource from cuda.core import Buffer, Device, DeviceMemoryResource, PinnedMemoryResource, VirtualMemoryResource @@ -86,19 +87,18 @@ def child_main(self, conn): mr = conn.recv() assert isinstance(mr, VirtualMemoryResource) - # Receive the buffers. - buffer1 = conn.recv() # directly - buffer_desc = conn.recv() stream = device.default_stream - buffer2 = Buffer.from_ipc_descriptor(mr, buffer_desc, stream=stream) # by descriptor + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + # Receive the buffers. + buffer1 = stack.enter_context(conn.recv()) # directly + buffer_desc = conn.recv() + buffer2 = stack.enter_context(Buffer.from_ipc_descriptor(mr, buffer_desc, stream=stream)) # by descriptor - # Modify the buffers. - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer1, seed=True) - pgen.fill_buffer(buffer2, seed=True) - buffer1.close() - buffer2.close() - stream.sync() + # Modify the buffers. + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer1, seed=True) + pgen.fill_buffer(buffer2, seed=True) class TestObjectSerializationWithMR: @@ -146,19 +146,19 @@ def child_main(self, pipe, _): mr = pipe[0].get(timeout=CHILD_TIMEOUT_SEC) pipe[1].put(getattr(mr, "uuid", None)) - # Buffer. - buffer = pipe[0].get(timeout=CHILD_TIMEOUT_SEC) - if is_pool_resource(mr): - assert buffer.memory_resource.handle == mr.handle - else: - # A VMM resource pickles as (device, options); the buffer's rebuilt - # resource is equivalent, not identical. - assert buffer.memory_resource.config == mr.config stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer, seed=True) - buffer.close() - stream.sync() + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + # Buffer. + buffer = stack.enter_context(pipe[0].get(timeout=CHILD_TIMEOUT_SEC)) + if is_pool_resource(mr): + assert buffer.memory_resource.handle == mr.handle + else: + # A VMM resource pickles as (device, options); the buffer's rebuilt + # resource is equivalent, not identical. + assert buffer.memory_resource.config == mr.config + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer, seed=True) class TestObjectPassing: @@ -199,36 +199,37 @@ def test_main(self, ipc_device, ipc_memory_resource): def child_main(self, alloc_handle, mr1, buffer_desc, buffer): device = Device() device.set_current() - if isinstance(mr1, PinnedMemoryResource): - with pytest.raises(TypeError): - DeviceMemoryResource.from_allocation_handle(device, alloc_handle) - mr2 = PinnedMemoryResource.from_allocation_handle(alloc_handle) - elif isinstance(mr1, DeviceMemoryResource): - with pytest.raises(TypeError): - PinnedMemoryResource.from_allocation_handle(alloc_handle) - mr2 = DeviceMemoryResource.from_allocation_handle(device, alloc_handle) - else: - # A VirtualMemoryResource has no allocation handle; the resource - # argument itself is the rebuilt resource. - assert alloc_handle is None - assert isinstance(mr1, VirtualMemoryResource) - mr2 = mr1 stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - - # Import the allocation again, from the descriptor through the resource - # rebuilt from the allocation handle. Both buffers alias the same memory. - buffer2 = Buffer.from_ipc_descriptor(mr2, buffer_desc, stream=stream) - - # Verify initial content - pgen.verify_buffer(buffer, seed=False) - pgen.verify_buffer(buffer2, seed=False) - - # Modify the buffer and verify through both imports - pgen.fill_buffer(buffer, seed=True) - pgen.verify_buffer(buffer, seed=True) - pgen.verify_buffer(buffer2, seed=True) - - buffer2.close() - buffer.close() - stream.sync() + with contextlib.ExitStack() as stack: + # The buffer argument was unpickled with this device current, so its + # free is on this default stream too. + drain_on_exit(stack, stream) + stack.enter_context(buffer) + if isinstance(mr1, PinnedMemoryResource): + with pytest.raises(TypeError): + DeviceMemoryResource.from_allocation_handle(device, alloc_handle) + mr2 = PinnedMemoryResource.from_allocation_handle(alloc_handle) + elif isinstance(mr1, DeviceMemoryResource): + with pytest.raises(TypeError): + PinnedMemoryResource.from_allocation_handle(alloc_handle) + mr2 = DeviceMemoryResource.from_allocation_handle(device, alloc_handle) + else: + # A VirtualMemoryResource has no allocation handle; the resource + # argument itself is the rebuilt resource. + assert alloc_handle is None + assert isinstance(mr1, VirtualMemoryResource) + mr2 = mr1 + pgen = PatternGen(device, NBYTES, stream=stream) + + # Import the allocation again, from the descriptor through the resource + # rebuilt from the allocation handle. Both buffers alias the same memory. + buffer2 = stack.enter_context(Buffer.from_ipc_descriptor(mr2, buffer_desc, stream=stream)) + + # Verify initial content + pgen.verify_buffer(buffer, seed=False) + pgen.verify_buffer(buffer2, seed=False) + + # Modify the buffer and verify through both imports + pgen.fill_buffer(buffer, seed=True) + pgen.verify_buffer(buffer, seed=True) + pgen.verify_buffer(buffer2, seed=True) From 08ab4c41c6ee7e05dd1a0b114fa22b4e51cb6c75 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 20:01:12 -0800 Subject: [PATCH 3/6] test(cuda.core): apply the drain and thread-runner patterns to the remaining tests The worker pool IPC tests now drain the import's free on failure too, and two more threaded tests run through run_in_threads. --- cuda_core/tests/memory_ipc/test_workerpool.py | 32 +++++++++++-------- cuda_core/tests/test_memory.py | 22 +++++-------- cuda_core/tests/test_program.py | 18 ++++------- 3 files changed, 33 insertions(+), 39 deletions(-) diff --git a/cuda_core/tests/memory_ipc/test_workerpool.py b/cuda_core/tests/memory_ipc/test_workerpool.py index ef7916ef2ae7..701ba8cf0827 100644 --- a/cuda_core/tests/memory_ipc/test_workerpool.py +++ b/cuda_core/tests/memory_ipc/test_workerpool.py @@ -1,12 +1,14 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import contextlib import multiprocessing as mp import pickle from itertools import cycle import pytest from helpers.buffers import PatternGen +from helpers.memory import drain_on_exit from cuda.core import Buffer, Device, VirtualMemoryResource @@ -56,10 +58,12 @@ def process_buffer(self, buffer): device = Device(buffer.memory_resource.device_id) device.set_current() stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer, seed=True) - buffer.close() - stream.sync() + # Drain the import's free after the buffer closes, also if the fill fails. + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + stack.enter_context(buffer) + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer, seed=True) class TestIpcWorkerPoolUsingIPCDescriptors: @@ -106,11 +110,11 @@ def process_buffer(self, mr_idx, buffer_desc): device = Device(mr.device_id) device.set_current() stream = device.default_stream - buffer = Buffer.from_ipc_descriptor(mr, buffer_desc, stream=stream) - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer, seed=True) - buffer.close() - stream.sync() + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + buffer = stack.enter_context(Buffer.from_ipc_descriptor(mr, buffer_desc, stream=stream)) + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer, seed=True) class TestIpcWorkerPoolUsingRegistry: @@ -158,9 +162,9 @@ def test_main(self, ipc_device, ipc_memory_resource_factory, nmrs): def process_buffer(self, device, buffer_s): device.set_current() - buffer = pickle.loads(buffer_s) # noqa: S301 stream = device.default_stream - pgen = PatternGen(device, NBYTES, stream=stream) - pgen.fill_buffer(buffer, seed=True) - buffer.close() - stream.sync() + with contextlib.ExitStack() as stack: + drain_on_exit(stack, stream) + buffer = stack.enter_context(pickle.loads(buffer_s)) # noqa: S301 + pgen = PatternGen(device, NBYTES, stream=stream) + pgen.fill_buffer(buffer, seed=True) diff --git a/cuda_core/tests/test_memory.py b/cuda_core/tests/test_memory.py index 347f8126cefe..bbf9670935c3 100644 --- a/cuda_core/tests/test_memory.py +++ b/cuda_core/tests/test_memory.py @@ -3,6 +3,7 @@ import concurrent.futures import ctypes +import functools import gc import multiprocessing as mp import sys @@ -44,6 +45,7 @@ skip_if_managed_mempool_unsupported, skip_if_pinned_memory_unsupported, ) +from helpers.misc import run_in_threads from helpers.nanosleep_kernel import NanosleepKernel from cuda.core import ( @@ -1739,30 +1741,22 @@ def test_vmm_concurrent_grows_of_aliased_buffers_are_memory_safe(init_cuda): device = _vmm_device_or_skip() mr = _vmm_resource(device) nthreads = 4 - errors = [] def work(buf, i, gate): - try: - gate.wait() - for j in range(6): - mr.modify_allocation(buf, (i * 8 + j + 2) * 2 * MIB).close() - except BaseException as exc: # pragma: no cover - surfaced below - errors.append(exc) + gate.wait() + for j in range(6): + mr.modify_allocation(buf, (i * 8 + j + 2) * 2 * MIB).close() with assert_no_cuda_warning(): for _ in range(8): root = mr.allocate(2 * MIB) alias = mr.modify_allocation(root, 8 * MIB) gate = threading.Barrier(nthreads) - threads = [threading.Thread(target=work, args=(root if i % 2 else alias, i, gate)) for i in range(nthreads)] - for t in threads: - t.start() - for t in threads: - t.join(timeout=CHILD_TIMEOUT_SEC) - assert not any(t.is_alive() for t in threads), "a grow thread did not finish" + targets = [functools.partial(work, root if i % 2 else alias, i, gate) for i in range(nthreads)] + # A failure or timeout leaves the buffers open: a stuck thread may still use them. + run_in_threads(targets, barrier=gate, timeout=CHILD_TIMEOUT_SEC) alias.close() root.close() - assert errors == [] @pytest.mark.agent_authored(model="claude-fable-5-1") diff --git a/cuda_core/tests/test_program.py b/cuda_core/tests/test_program.py index 4376519a90b9..108584173122 100644 --- a/cuda_core/tests/test_program.py +++ b/cuda_core/tests/test_program.py @@ -9,9 +9,11 @@ import subprocess import sys import tempfile +import threading import warnings import pytest +from helpers.misc import run_in_threads from cuda.bindings._internal.utils import FunctionNotFoundError from cuda.core import _linker @@ -1174,27 +1176,21 @@ def _denied(*_args, **_kwargs): @pytest.mark.agent_authored(model="cursor-grok-4.6") def test_nvrtc_debug_concurrent_compile_uses_unique_temp_files(init_cuda): """Same kernel compiled concurrently gets distinct mkstemp paths (issue #2422).""" - import os - import threading - from concurrent.futures import ThreadPoolExecutor - code = 'extern "C" __global__ void matmul() {}' n = 2 barrier = threading.Barrier(n) + progs = [] + names = [] def _compile_one(): Device().set_current() barrier.wait() prog = Program(code, "c++", ProgramOptions(debug=True, arch="sm_80")) - name = prog.compile("ptx").name - return prog, name - - with ThreadPoolExecutor(max_workers=n) as pool: - futures = [pool.submit(_compile_one) for _ in range(n)] - results = [fut.result() for fut in futures] + progs.append(prog) + names.append(prog.compile("ptx").name) - progs, names = zip(*results) try: + run_in_threads([_compile_one] * n, barrier=barrier) assert len(set(names)) == n for name in names: assert os.path.isfile(name) From 3c63d1dd03a48bd5aff3f34a8004d7ae0497f145 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 20:19:46 -0800 Subject: [PATCH 4/6] test(cuda.core): abort the barrier when run_in_threads times out A worker still waiting at the barrier after a timeout would block until interpreter shutdown, because the helper's threads are non-daemon. Abort the barrier before raising TimeoutError so such a worker raises BrokenBarrierError and exits without running the code after its wait. --- cuda_core/tests/helpers/misc.py | 7 ++++++- cuda_core/tests/test_helpers.py | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/cuda_core/tests/helpers/misc.py b/cuda_core/tests/helpers/misc.py index 5b799fb7f9c3..8a3b57d97ed0 100644 --- a/cuda_core/tests/helpers/misc.py +++ b/cuda_core/tests/helpers/misc.py @@ -19,7 +19,10 @@ def run_in_threads(targets, *, barrier=None, timeout=None): With ``timeout``, each join waits at most that many seconds, and a thread still running afterwards (for example a deadlocked one) raises ``TimeoutError``. Such a thread cannot be stopped, so callers must not - release anything it may still be using. + 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 = [] @@ -49,6 +52,8 @@ def run(target): raise next((e for e in errors if not isinstance(e, threading.BrokenBarrierError)), errors[0]) running = [thread.name for thread in started if thread.is_alive()] if running: + if barrier is not None: + barrier.abort() raise TimeoutError(f"threads still running after {timeout} s: {running}") diff --git a/cuda_core/tests/test_helpers.py b/cuda_core/tests/test_helpers.py index dbd338d06f23..e4435d315303 100644 --- a/cuda_core/tests/test_helpers.py +++ b/cuda_core/tests/test_helpers.py @@ -570,6 +570,29 @@ def test_run_in_threads_reports_a_thread_that_does_not_finish(): release.set() +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_run_in_threads_aborts_the_barrier_when_a_thread_times_out(): + barrier = threading.Barrier(2) + waiters = [] + after_wait = [] + + def wait_at_barrier(): + waiters.append(threading.current_thread()) + barrier.wait() + after_wait.append(True) + + try: + # The second party never arrives, so the first worker would block forever. + with pytest.raises(TimeoutError, match="still running"): + run_in_threads([wait_at_barrier, lambda: None], barrier=barrier, timeout=0.2) + waiters[0].join(10) + assert not waiters[0].is_alive() + assert after_wait == [] + finally: + # Release the waiter if the helper did not, so the process can exit. + barrier.abort() + + @pytest.mark.thread_unsafe(reason="patches threading.Thread.start") @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_run_in_threads_aborts_the_barrier_when_a_thread_fails_to_start(monkeypatch): From 77bfb2c311569177448398a39a80bea8f3b341bb Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 08:56:39 -0800 Subject: [PATCH 5/6] test(cuda.core): report a stuck thread before another thread's failure in run_in_threads When one worker failed and another outlived the join timeout, the helper raised only the failure. Raise TimeoutError first, chained to the failure, so callers still learn that a thread may be using their resources. --- cuda_core/tests/helpers/misc.py | 16 ++++++++++------ cuda_core/tests/test_helpers.py | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/cuda_core/tests/helpers/misc.py b/cuda_core/tests/helpers/misc.py index 8a3b57d97ed0..3fdd8ba841bd 100644 --- a/cuda_core/tests/helpers/misc.py +++ b/cuda_core/tests/helpers/misc.py @@ -13,12 +13,13 @@ def run_in_threads(targets, *, barrier=None, timeout=None): 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 before - this returns or raises. + 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``. Such a thread cannot be stopped, so callers must not + ``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 @@ -48,13 +49,16 @@ def run(target): finally: for thread in started: thread.join(timeout) - if errors: - raise next((e for e in errors if not isinstance(e, threading.BrokenBarrierError)), errors[0]) + failure = ( + next((e for e in errors if not isinstance(e, threading.BrokenBarrierError)), errors[0]) if errors else None + ) running = [thread.name for thread in started if thread.is_alive()] if running: if barrier is not None: barrier.abort() - raise TimeoutError(f"threads still running after {timeout} s: {running}") + 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): diff --git a/cuda_core/tests/test_helpers.py b/cuda_core/tests/test_helpers.py index e4435d315303..5a1869d9cf48 100644 --- a/cuda_core/tests/test_helpers.py +++ b/cuda_core/tests/test_helpers.py @@ -570,6 +570,21 @@ def test_run_in_threads_reports_a_thread_that_does_not_finish(): release.set() +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_run_in_threads_reports_a_stuck_thread_before_another_threads_failure(): + release = threading.Event() + + def fails(): + raise ValueError("worker failed") + + try: + with pytest.raises(TimeoutError, match="still running") as excinfo: + run_in_threads([fails, lambda: release.wait(30)], timeout=0.2) + assert isinstance(excinfo.value.__cause__, ValueError) + finally: + release.set() + + @pytest.mark.agent_authored(model="claude-sonnet-5-5") def test_run_in_threads_aborts_the_barrier_when_a_thread_times_out(): barrier = threading.Barrier(2) From 156a572457ce0e0cfc5aaa715c692e3b766fd65d Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 09:15:56 -0800 Subject: [PATCH 6/6] test(cuda.core): check thread liveness before reading failures in run_in_threads A worker that failed right after a timed-out join could be missed: the failure was read while the error list was still empty, and the worker was no longer alive by the time liveness was checked, so the helper returned normally. Check liveness first. --- cuda_core/tests/helpers/misc.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cuda_core/tests/helpers/misc.py b/cuda_core/tests/helpers/misc.py index 3fdd8ba841bd..a33fcfbee946 100644 --- a/cuda_core/tests/helpers/misc.py +++ b/cuda_core/tests/helpers/misc.py @@ -49,10 +49,11 @@ def run(target): 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 = ( next((e for e in errors if not isinstance(e, threading.BrokenBarrierError)), errors[0]) if errors else None ) - running = [thread.name for thread in started if thread.is_alive()] if running: if barrier is not None: barrier.abort()