diff --git a/cuda_core/AGENTS.md b/cuda_core/AGENTS.md index 863785d22281..cae2714d2f9e 100644 --- a/cuda_core/AGENTS.md +++ b/cuda_core/AGENTS.md @@ -159,6 +159,9 @@ the literal floor. call-site consistency. - Prefer explicit error propagation over silent fallback paths. - If you change public behavior, update tests and docs under `docs/source/`. +- Do not add test-only hooks (`*_for_testing` functions, test-only globals, + parameters, or branches) to production code; see "Keep test hooks out of + production code" in `tests/AGENTS.md` for the alternatives. ## Concurrency and free-threading @@ -282,7 +285,7 @@ below are for contributors. Reviewers and agents should flag violations. bug (#1489, #2417), not a policy choice: `noexcept` helpers must not allocate, or must catch what they call. - **Testing**: inject restoration failures with - `cuda.core._rt._set_context_restore_fault_for_testing`; assert + `cuda.core._utils._testing.set_context_restore_fault`; assert reports with `pytest.warns(CUDAWarning)` or `warnings.catch_warnings`, never by matching stderr text. diff --git a/cuda_core/cuda/core/_cpp/rt/DESIGN.md b/cuda_core/cuda/core/_cpp/rt/DESIGN.md index 9973118cb3c8..7f3854fd30d6 100644 --- a/cuda_core/cuda/core/_cpp/rt/DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/DESIGN.md @@ -398,7 +398,8 @@ as a generic error) leaves the detail behind, and a later error on the same thread with the same status code picks it up. `enter_context` clears stale detail at the next context-scoped operation. Issue #2760 removes this thread-local state in favor of explicit status returns. Tests inject restoration failures with -`set_context_restore_fault_for_testing()`. +`cuda.core._utils._testing.set_context_restore_fault()`, which arms a test +wrapper around the function table's `cuCtxSetCurrent` entry. ### Reporting from non-propagating paths diff --git a/cuda_core/cuda/core/_cpp/rt/api.hpp b/cuda_core/cuda/core/_cpp/rt/api.hpp index 97355aea4a8d..c2c0689edb8b 100644 --- a/cuda_core/cuda/core/_cpp/rt/api.hpp +++ b/cuda_core/cuda/core/_cpp/rt/api.hpp @@ -309,11 +309,6 @@ size_t va_reservation_size(const VaReservationHandle &h) noexcept; long long live_owned_mempool_count() noexcept; long long live_va_reservation_count() noexcept; -// Test hook: the owner of an imported pool sleeps this long after its last -// reference is released and before it revokes access, so that a re-import can -// be made to race the release. 0 (the default) disables the delay. -void set_ipc_pool_release_delay_for_testing(unsigned int microseconds) noexcept; - // Map the whole allocation at ptr inside the reservation via cuMemMap and // apply the allocation's access descriptors. The mapping structurally depends // on both handles. When the last reference is released, cuMemUnmap is called diff --git a/cuda_core/cuda/core/_cpp/rt/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index fd632991be7b..c2b1203b9059 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -17,17 +17,6 @@ namespace cuda_core::rt { using namespace detail; -namespace { -// Thread-local fault injected into the next context restoration (tests only). -thread_local CUresult context_restore_fault = CUDA_SUCCESS; -} // namespace - -void -set_context_restore_fault_for_testing(CUresult status) noexcept -{ - context_restore_fault = status; -} - namespace detail { // Make a context current and record the state needed to restore it. // An empty handle is a no-op: the operation runs in the caller's current @@ -60,13 +49,6 @@ enter_context(const ContextHandle &h_context, CUcontext *previous, int *changed) CUresult restore_context(CUcontext previous) noexcept { - if (context_restore_fault != CUDA_SUCCESS) { - // Test hook: behave as if cuCtxSetCurrent(previous) failed, leaving the - // target context current exactly as a real failure would. - CUresult fault = context_restore_fault; - context_restore_fault = CUDA_SUCCESS; - return fault; - } GILReleaseGuard gil; return DRIVER_CALL(cuCtxSetCurrent, previous); } diff --git a/cuda_core/cuda/core/_cpp/rt/error.hpp b/cuda_core/cuda/core/_cpp/rt/error.hpp index 251e7388f0c4..9557bba97e5b 100644 --- a/cuda_core/cuda/core/_cpp/rt/error.hpp +++ b/cuda_core/cuda/core/_cpp/rt/error.hpp @@ -80,9 +80,4 @@ void clear_last_error_detail() noexcept; // fill and does not suggest a missed cuInit() call. Implemented in error.cpp. void note_driver_table_failure(const char *reason) noexcept; -// Tests only: make the next context restoration on this thread fail with -// `status`, leaving the target context current as a real failure would. -// Implemented in context.cpp -void set_context_restore_fault_for_testing(CUresult status) noexcept; - } // namespace cuda_core::rt diff --git a/cuda_core/cuda/core/_cpp/rt/memory.cpp b/cuda_core/cuda/core/_cpp/rt/memory.cpp index 53653963447c..ae242b9c88cf 100644 --- a/cuda_core/cuda/core/_cpp/rt/memory.cpp +++ b/cuda_core/cuda/core/_cpp/rt/memory.cpp @@ -9,13 +9,11 @@ #include "error.hpp" #include "internal.hpp" #include -#include #include #include #include #include #include -#include #include #ifndef _WIN32 #include @@ -40,17 +38,8 @@ struct MemoryPoolBox { // Read by the test suite to gate the per-test gc.collect(); atomic for // free-threaded builds. std::atomic g_live_owned_mempools{0}; - -// See set_ipc_pool_release_delay_for_testing. -std::atomic g_ipc_pool_release_delay_us{0}; } // namespace -void -set_ipc_pool_release_delay_for_testing(unsigned int microseconds) noexcept -{ - g_ipc_pool_release_delay_us.store(microseconds, std::memory_order_relaxed); -} - // Helper to clear peer access before destroying a memory pool. // Works around nvbug 5698116: recycled pool handles inherit peer access state. // The driver validates a request as a whole and rejects it if any entry cannot @@ -193,9 +182,6 @@ create_mempool_handle_ipc(int fd, CUmemAllocationHandleType handle_type) std::size_t imports = b->imports.load(std::memory_order_relaxed); if (imports > 0) { GILReleaseGuard gil; - if (unsigned int delay = g_ipc_pool_release_delay_us.load(std::memory_order_relaxed)) { - std::this_thread::sleep_for(std::chrono::microseconds(delay)); - } clear_mempool_peer_access(b->resource, -1); const std::size_t total = imports; std::size_t failed = 0; diff --git a/cuda_core/cuda/core/_rt.pyi b/cuda_core/cuda/core/_rt.pyi index ad50dd4bd1e9..e119da114e0d 100644 --- a/cuda_core/cuda/core/_rt.pyi +++ b/cuda_core/cuda/core/_rt.pyi @@ -49,25 +49,3 @@ PreparedAttachmentDeleter: TypeAlias = Incomplete PreparedChildGraphUpdateState: TypeAlias = Incomplete PreparedExecAttachmentState: TypeAlias = Incomplete PreparedExecAttachmentDeleter: TypeAlias = Incomplete - -def _set_context_restore_fault_for_testing(status: int): - """Make the next context restoration on this thread fail with ``status``. - - Test hook for the context save/restore paths in the handle layer. The - injected failure leaves the target context current, exactly as a failing - ``cuCtxSetCurrent`` would, so callers must restore the context themselves. - """ -def _set_ipc_pool_release_delay_for_testing(microseconds: int): - """Delay the release of an imported pool's owner by ``microseconds``. - - Test hook: once the owner's last reference is released, it sleeps before it - revokes access and destroys the pool's imports, so that a re-import can be - made to race the release. 0 disables the delay. - """ -def _attach_rollback_failure_for_testing(status: int): - """Attach a failed CUDA call to the exception being handled, or report it. - - Test hook for ``attach_rollback_failure()``. Called inside an ``except`` - block it adds a note to the exception being handled (Python 3.11+); anywhere - else it emits a ``CUDAWarning``. - """ diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index c8f165203c31..51e37acdb01f 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -57,15 +57,9 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": const char* operation, long code) noexcept nogil void attach_rollback_failure "cuda_core::rt::attach_rollback_failure" ( const char* operation, cydriver.CUresult status, const char* detail) noexcept nogil - # Alias for calls made from this module: calling the pxd-declared name here - # would make Cython emit a conflicting static prototype for it. - void _attach_rollback_failure_local "cuda_core::rt::attach_rollback_failure" ( - const char* operation, cydriver.CUresult status, const char* detail) noexcept nogil const char* take_last_error_detail "cuda_core::rt::take_last_error_detail" ( cydriver.CUresult status) noexcept nogil void clear_last_error_detail "cuda_core::rt::clear_last_error_detail" () noexcept nogil - void set_context_restore_fault_for_testing "cuda_core::rt::set_context_restore_fault_for_testing" ( - cydriver.CUresult status) noexcept nogil # Context handles ContextHandle create_context_handle_ref "cuda_core::rt::create_context_handle_ref" ( @@ -194,8 +188,6 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": const VaReservationHandle& h) noexcept nogil long long live_owned_mempool_count "cuda_core::rt::live_owned_mempool_count" () noexcept nogil long long live_va_reservation_count "cuda_core::rt::live_va_reservation_count" () noexcept nogil - void set_ipc_pool_release_delay_for_testing "cuda_core::rt::set_ipc_pool_release_delay_for_testing" ( - unsigned int microseconds) noexcept nogil VaMappingHandle create_va_mapping_handle "cuda_core::rt::create_va_mapping_handle" ( cydriver.CUdeviceptr ptr, const MemAllocationHandle& h_alloc, const VaReservationHandle& h_res) except+ nogil @@ -347,34 +339,3 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": initialize_deferred_cleanup() - - -def _set_context_restore_fault_for_testing(int status): - """Make the next context restoration on this thread fail with ``status``. - - Test hook for the context save/restore paths in the handle layer. The - injected failure leaves the target context current, exactly as a failing - ``cuCtxSetCurrent`` would, so callers must restore the context themselves. - """ - set_context_restore_fault_for_testing(status) - - -def _set_ipc_pool_release_delay_for_testing(unsigned int microseconds): - """Delay the release of an imported pool's owner by ``microseconds``. - - Test hook: once the owner's last reference is released, it sleeps before it - revokes access and destroys the pool's imports, so that a re-import can be - made to race the release. 0 disables the delay. - """ - set_ipc_pool_release_delay_for_testing(microseconds) - - -def _attach_rollback_failure_for_testing(int status): - """Attach a failed CUDA call to the exception being handled, or report it. - - Test hook for ``attach_rollback_failure()``. Called inside an ``except`` - block it adds a note to the exception being handled (Python 3.11+); anywhere - else it emits a ``CUDAWarning``. - """ - _attach_rollback_failure_local( - b"cuTestOperation", status, b"failed while testing") diff --git a/cuda_core/cuda/core/_utils/_testing.pyi b/cuda_core/cuda/core/_utils/_testing.pyi new file mode 100644 index 000000000000..c028c8438ed9 --- /dev/null +++ b/cuda_core/cuda/core/_utils/_testing.pyi @@ -0,0 +1,129 @@ +# This file was generated by stubgen-pyx v0.2.23 from cuda_core/cuda/core/_utils/_testing.pyx + +"""Test-only helpers that reach into ``cuda.core`` internals. + +This module is **not** part of the public ``cuda.core`` API. It is built into +the package (like other private ``_utils`` modules) purely for the test suite, +so that production modules need no test hooks of their own. + +Weak handles +------------ + +Weak handles let tests observe, deterministically, when the strong references +that keep a CUDA resource alive have all been released -- without relying on +driver- or hardware-specific side effects (for example, whether freed device +memory happens to remain readable). + +Every resource handle is owned by a C++ ``std::shared_ptr``. A **weak handle** +is a non-owning ``std::weak_ptr`` observer of that control block: truthy while +some strong owner remains, falsy once the last one is gone. Use :func:`weak_handle` +to obtain a weak handle from a supported front-end object. + +To support another type, add a ``cdef _weak_from_`` that reads its ``cdef`` +handle field (see ``*.pxd``), assigns to :ctype:`OpaqueHandle`, and extend the +``isinstance`` chain in :func:`weak_handle`. Types whose slots hold arbitrary +Python owners via ``make_opaque_py`` are not covered here -- use +:class:`weakref.ref` on a weak-referenceable owner object in tests instead. + +Driver function wrappers +------------------------ + +The C++ layer calls the driver through a table of function pointers that it +fills once per process, on its first driver call, from +``cuda.bindings._internal.driver._inspect_function_pointers()``. +:func:`install_driver_fn_wrappers` replaces that function so that the fill +stores test wrappers for selected entries. Each wrapper calls the real driver +function unless a test arms it. Install the wrappers before ``cuda.core``'s +first driver call in the process: conftest.py does so for the test session, +and a spawned child must do so itself. The setters raise unless the table was +filled with the wrappers, so a test cannot silently run unarmed. Arm a wrapper +only after the process's first driver call through ``cuda.core``, for example +after creating a device or a stream. +""" +from _typeshed import Incomplete +from typing_extensions import TypeAlias + +_inspect_without_wrappers = None +_wrappers_installed = False +OpaqueWeakHandle: TypeAlias = Incomplete + +class WeakHandle: + """Non-owning weak handle for a resource's shared control block. + + Truthy while some strong owner of the underlying resource handle remains, + falsy once the last strong reference is released. Obtain instances via + :func:`weak_handle` rather than constructing directly. + """ + def __bool__(self): ... + def expired(self): + """Return ``True`` once every strong owner of the handle is gone.""" + def use_count(self): + """Number of strong owners currently sharing the handle.""" + +def weak_handle(obj): + """Return a :class:`WeakHandle` observing the resource behind ``obj``. + + Currently supports :class:`~cuda.core.Buffer` (allocation handle) and + :class:`~cuda.core.graph.GraphDefinition` (graph hierarchy handle). See + the module docstring for how to add more types. + + Raises + ------ + ValueError + If ``obj`` is a :class:`~cuda.core.Buffer` with no active allocation. + TypeError + If ``obj`` is not a supported type. + """ +def attach_rollback_failure_for_testing(status: int): + """Attach a failed CUDA call to the exception being handled, or report it. + + Calls ``attach_rollback_failure()`` for a fictitious ``cuTestOperation``. + Called inside an ``except`` block it adds a note to the exception being + handled (Python 3.11+); anywhere else it emits a ``CUDAWarning``. + """ +def _inspect_with_wrappers(): ... +def install_driver_fn_wrappers(): + """Make the C++ driver function table use the test wrappers in this process. + + Call before ``cuda.core`` makes its first driver call; see the module + docstring. Calling it again has no effect. + """ +def arm_pool_release_gate(pool: int, timeout_sec: float, grace_sec: float): + """Hold the next release of ``pool`` while the pool is imported again. + + The C++ layer calls ``cuMemPoolSetAccess`` only to revoke access just + before it destroys a pool (or an imported pool's imports), after its last + reference is gone. The first such call on ``pool`` after arming blocks + until a ``cuMemPoolImportFromShareableHandle`` from the C++ layer returns + ``pool``, or until ``timeout_sec`` passes. Once that import has returned, + it stays blocked until :func:`open_pool_release_gate` is called, or until + ``grace_sec`` passes, and then proceeds. Later calls pass through. + + Open the gate once the import has finished. An import that correctly waits + for the release cannot finish first, so the grace period ends the hold; an + import that does not wait finishes, opens the gate, and the release then + revokes access after the import was granted it, so the test sees the + damage. Use :func:`wait_pool_release_gate_entered` to start the import once + the release is held, and :func:`disarm_pool_release_gate` to check that the + import overlapped the release. + """ +def open_pool_release_gate(): + """Let a held release proceed once the import that overlapped it has finished.""" +def wait_pool_release_gate_entered(timeout_sec: float): + """Wait until a release is held by the gate; return ``False`` on timeout or disarm.""" +def disarm_pool_release_gate(): + """Disarm the gate and let a held release proceed. + + Return ``True`` if a release was held and an import of the pool returned + while it was held, so the import overlapped the release. + """ +def set_context_restore_fault(status: int): + """Make ``cuda.core``'s next switch back to the current context fail on this thread. + + The next ``cuCtxSetCurrent`` that the C++ layer makes on this thread to the + context that is current now returns ``status`` without switching, so the + context it switched to stays current, exactly as a real failure would. The + C++ layer switches contexts only to enter an operation's context and to + restore the caller's afterwards, and it does not switch to a context that + is already current, so only a restoration can fail. 0 disarms the fault. + """ diff --git a/cuda_core/cuda/core/_utils/_testing.pyx b/cuda_core/cuda/core/_utils/_testing.pyx new file mode 100644 index 000000000000..fbe35d71da08 --- /dev/null +++ b/cuda_core/cuda/core/_utils/_testing.pyx @@ -0,0 +1,416 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Test-only helpers that reach into ``cuda.core`` internals. + +This module is **not** part of the public ``cuda.core`` API. It is built into +the package (like other private ``_utils`` modules) purely for the test suite, +so that production modules need no test hooks of their own. + +Weak handles +------------ + +Weak handles let tests observe, deterministically, when the strong references +that keep a CUDA resource alive have all been released -- without relying on +driver- or hardware-specific side effects (for example, whether freed device +memory happens to remain readable). + +Every resource handle is owned by a C++ ``std::shared_ptr``. A **weak handle** +is a non-owning ``std::weak_ptr`` observer of that control block: truthy while +some strong owner remains, falsy once the last one is gone. Use :func:`weak_handle` +to obtain a weak handle from a supported front-end object. + +To support another type, add a ``cdef _weak_from_`` that reads its ``cdef`` +handle field (see ``*.pxd``), assigns to :ctype:`OpaqueHandle`, and extend the +``isinstance`` chain in :func:`weak_handle`. Types whose slots hold arbitrary +Python owners via ``make_opaque_py`` are not covered here -- use +:class:`weakref.ref` on a weak-referenceable owner object in tests instead. + +Driver function wrappers +------------------------ + +The C++ layer calls the driver through a table of function pointers that it +fills once per process, on its first driver call, from +``cuda.bindings._internal.driver._inspect_function_pointers()``. +:func:`install_driver_fn_wrappers` replaces that function so that the fill +stores test wrappers for selected entries. Each wrapper calls the real driver +function unless a test arms it. Install the wrappers before ``cuda.core``'s +first driver call in the process: conftest.py does so for the test session, +and a spawned child must do so itself. The setters raise unless the table was +filled with the wrappers, so a test cannot silently run unarmed. Arm a wrapper +only after the process's first driver call through ``cuda.core``, for example +after creating a device or a stream. +""" + +from libc.stdint cimport intptr_t + +from cuda.bindings cimport cydriver +from cuda.core._memory._buffer cimport Buffer +from cuda.core.graph._graph_definition cimport GraphDefinition +from cuda.core._rt cimport OpaqueHandle, attach_rollback_failure +from cuda.core._utils.cuda_utils cimport HANDLE_RETURN + +import cuda.bindings._internal.driver as _driver_loader + + +# Cython cannot spell ``weak_ptr[const void]`` inline (the ``const void`` +# template argument fails to parse), so the weak type and its one constructor +# are provided by a small inline C++ shim local to this test-only module. This +# keeps the production resource_handles translation units untouched. +cdef extern from *: + """ + #include + namespace cuda_core_test { + using OpaqueWeakHandle = std::weak_ptr; + static inline OpaqueWeakHandle make_weak(const std::shared_ptr& h) { + return OpaqueWeakHandle(h); + } + } // namespace cuda_core_test + """ + cppclass OpaqueWeakHandle "cuda_core_test::OpaqueWeakHandle": + OpaqueWeakHandle() + bint expired() + long use_count() + OpaqueWeakHandle make_weak "cuda_core_test::make_weak" (const OpaqueHandle& h) + + +cdef class WeakHandle: + """Non-owning weak handle for a resource's shared control block. + + Truthy while some strong owner of the underlying resource handle remains, + falsy once the last strong reference is released. Obtain instances via + :func:`weak_handle` rather than constructing directly. + """ + + cdef OpaqueWeakHandle _w + + def __bool__(self): + return not self._w.expired() + + def expired(self): + """Return ``True`` once every strong owner of the handle is gone.""" + return self._w.expired() + + def use_count(self): + """Number of strong owners currently sharing the handle.""" + return self._w.use_count() + + +cdef WeakHandle _weak_from_opaque(OpaqueHandle h): + # Build the weak handle from a (temporary) strong handle. The strong copy + # lives only for the duration of this call, so it does not perturb the + # reference count the weak handle later reports. + cdef WeakHandle wh = WeakHandle.__new__(WeakHandle) + wh._w = make_weak(h) + return wh + + +cdef WeakHandle _weak_from_buffer(Buffer buf): + cdef OpaqueHandle h = buf._h_ptr + if not h: + raise ValueError("Buffer has no active allocation") + return _weak_from_opaque(h) + + +cdef WeakHandle _weak_from_graph_definition(GraphDefinition graph): + cdef OpaqueHandle h = graph._h_graph + if not h: + raise ValueError("GraphDefinition has no active graph") + return _weak_from_opaque(h) + + +def weak_handle(obj): + """Return a :class:`WeakHandle` observing the resource behind ``obj``. + + Currently supports :class:`~cuda.core.Buffer` (allocation handle) and + :class:`~cuda.core.graph.GraphDefinition` (graph hierarchy handle). See + the module docstring for how to add more types. + + Raises + ------ + ValueError + If ``obj`` is a :class:`~cuda.core.Buffer` with no active allocation. + TypeError + If ``obj`` is not a supported type. + """ + if isinstance(obj, Buffer): + return _weak_from_buffer(obj) + if isinstance(obj, GraphDefinition): + return _weak_from_graph_definition(obj) + raise TypeError( + f"weak_handle() does not support {type(obj).__name__!r}; " + "supported types: Buffer, GraphDefinition" + ) + + +# Keeps the ``_for_testing`` suffix because it shares its name with the cimported +# ``attach_rollback_failure``, which this wrapper calls. +def attach_rollback_failure_for_testing(int status): + """Attach a failed CUDA call to the exception being handled, or report it. + + Calls ``attach_rollback_failure()`` for a fictitious ``cuTestOperation``. + Called inside an ``except`` block it adds a note to the exception being + handled (Python 3.11+); anywhere else it emits a ``CUDAWarning``. + """ + attach_rollback_failure(b"cuTestOperation", status, b"failed while testing") + + +# The wrappers run on driver calls from any thread, with or without the GIL, +# and during interpreter shutdown, so they are plain C++ and never call Python. +cdef extern from *: + """ + #include + #include + #include + #include + #include + #include + namespace cuda_core_test { + // The real pointers are atomic because the fill may run on two threads at + // once in a free-threaded build, and each run calls the wrap functions. + using CtxSetCurrentFn = CUresult(CUDAAPI *)(CUcontext); + static std::atomic real_ctx_set_current{nullptr}; + static thread_local CUresult ctx_set_current_fault = CUDA_SUCCESS; + static thread_local CUcontext ctx_set_current_fault_target = nullptr; + + static CUresult CUDAAPI faulty_ctx_set_current(CUcontext ctx) { + if (ctx_set_current_fault != CUDA_SUCCESS && ctx == ctx_set_current_fault_target) { + CUresult fault = ctx_set_current_fault; + ctx_set_current_fault = CUDA_SUCCESS; + return fault; + } + return real_ctx_set_current.load()(ctx); + } + static std::intptr_t wrap_ctx_set_current(std::intptr_t real) { + real_ctx_set_current.store(reinterpret_cast(real)); + return reinterpret_cast(&faulty_ctx_set_current); + } + static void set_ctx_set_current_fault(CUresult status, CUcontext target) { + ctx_set_current_fault = status; + ctx_set_current_fault_target = target; + } + + // The pool release gate: the first cuMemPoolSetAccess on the target pool + // after arming blocks until an import returns that pool (or a timeout), + // then until the test opens the gate (or a grace period passes). + // Only the armed path touches the mutex; the gate is never destroyed, so a + // deleter that runs during process exit cannot reach a destroyed mutex. + struct PoolReleaseGate { + std::mutex mutex; + std::condition_variable changed; + CUmemoryPool pool = nullptr; + std::chrono::duration timeout{0}; + std::chrono::duration grace{0}; + bool entered = false; // a release reached the gate since arming + bool held = false; // that release is still blocked in the gate + bool imported = false; + bool opened = false; + bool disarmed = false; + }; + static PoolReleaseGate &pool_release_gate() { + static PoolReleaseGate *gate = new PoolReleaseGate; + return *gate; + } + // Armed until the release enters the gate; watching until disarmed. + static std::atomic pool_release_gate_armed{false}; + static std::atomic pool_release_gate_watching{false}; + + using MemPoolSetAccessFn = CUresult(CUDAAPI *)(CUmemoryPool, const CUmemAccessDesc *, size_t); + static std::atomic real_mempool_set_access{nullptr}; + + static CUresult CUDAAPI gated_mempool_set_access( + CUmemoryPool pool, const CUmemAccessDesc *map, size_t count) { + if (pool_release_gate_armed.load()) { + PoolReleaseGate &gate = pool_release_gate(); + std::unique_lock lock(gate.mutex); + if (pool_release_gate_armed.load() && pool == gate.pool) { + pool_release_gate_armed.store(false); // one-shot: later calls pass through + gate.entered = true; + gate.held = true; + gate.changed.notify_all(); + gate.changed.wait_for(lock, gate.timeout, [&] { return gate.imported || gate.disarmed; }); + if (gate.imported) { + gate.changed.wait_for(lock, gate.grace, [&] { return gate.opened || gate.disarmed; }); + } + // The release proceeds: a later import did not overlap it. + gate.held = false; + } + } + return real_mempool_set_access.load()(pool, map, count); + } + static std::intptr_t wrap_mempool_set_access(std::intptr_t real) { + real_mempool_set_access.store(reinterpret_cast(real)); + return reinterpret_cast(&gated_mempool_set_access); + } + + using MemPoolImportFn = CUresult(CUDAAPI *)(CUmemoryPool *, void *, CUmemAllocationHandleType, unsigned long long); + static std::atomic real_mempool_import{nullptr}; + + static CUresult CUDAAPI signaling_mempool_import( + CUmemoryPool *pool, void *handle, CUmemAllocationHandleType type, unsigned long long flags) { + CUresult status = real_mempool_import.load()(pool, handle, type, flags); + if (status == CUDA_SUCCESS && pool_release_gate_watching.load()) { + PoolReleaseGate &gate = pool_release_gate(); + std::lock_guard lock(gate.mutex); + // Only an import made while the release is held counts. + if (gate.held && !gate.disarmed && *pool == gate.pool) { + gate.imported = true; + gate.changed.notify_all(); + } + } + return status; + } + static std::intptr_t wrap_mempool_import(std::intptr_t real) { + real_mempool_import.store(reinterpret_cast(real)); + return reinterpret_cast(&signaling_mempool_import); + } + + static void arm_pool_release_gate(CUmemoryPool pool, double timeout_sec, double grace_sec) { + PoolReleaseGate &gate = pool_release_gate(); + std::lock_guard lock(gate.mutex); + gate.pool = pool; + gate.timeout = std::chrono::duration(timeout_sec); + gate.grace = std::chrono::duration(grace_sec); + gate.entered = false; + gate.held = false; + gate.imported = false; + gate.opened = false; + gate.disarmed = false; + pool_release_gate_watching.store(true); + pool_release_gate_armed.store(true); + } + static bool wait_pool_release_gate_entered(double timeout_sec) { + PoolReleaseGate &gate = pool_release_gate(); + std::unique_lock lock(gate.mutex); + return gate.changed.wait_for( + lock, std::chrono::duration(timeout_sec), [&] { return gate.entered || gate.disarmed; }) + && gate.entered; + } + static void open_pool_release_gate() { + PoolReleaseGate &gate = pool_release_gate(); + std::lock_guard lock(gate.mutex); + gate.opened = true; + gate.changed.notify_all(); + } + static bool disarm_pool_release_gate() { + PoolReleaseGate &gate = pool_release_gate(); + std::lock_guard lock(gate.mutex); + pool_release_gate_armed.store(false); + pool_release_gate_watching.store(false); + const bool overlapped = gate.entered && gate.imported; + gate.disarmed = true; + gate.changed.notify_all(); // release a held release or waiter + return overlapped; + } + } // namespace cuda_core_test + """ + intptr_t _wrap_ctx_set_current "cuda_core_test::wrap_ctx_set_current" (intptr_t real) noexcept + void _set_ctx_set_current_fault "cuda_core_test::set_ctx_set_current_fault" ( + cydriver.CUresult status, cydriver.CUcontext target) noexcept nogil + intptr_t _wrap_mempool_set_access "cuda_core_test::wrap_mempool_set_access" (intptr_t real) noexcept + intptr_t _wrap_mempool_import "cuda_core_test::wrap_mempool_import" (intptr_t real) noexcept + void _arm_pool_release_gate "cuda_core_test::arm_pool_release_gate" ( + cydriver.CUmemoryPool pool, double timeout_sec, double grace_sec) noexcept nogil + bint _wait_pool_release_gate_entered "cuda_core_test::wait_pool_release_gate_entered" ( + double timeout_sec) noexcept nogil + void _open_pool_release_gate "cuda_core_test::open_pool_release_gate" () noexcept nogil + bint _disarm_pool_release_gate "cuda_core_test::disarm_pool_release_gate" () noexcept nogil + + +_inspect_without_wrappers = None +_wrappers_installed = False + + +def _inspect_with_wrappers(): + global _wrappers_installed + pointers = dict(_inspect_without_wrappers()) + pointers["__cuCtxSetCurrent"] = _wrap_ctx_set_current(pointers["__cuCtxSetCurrent"]) + pointers["__cuMemPoolSetAccess"] = _wrap_mempool_set_access(pointers["__cuMemPoolSetAccess"]) + pointers["__cuMemPoolImportFromShareableHandle"] = _wrap_mempool_import( + pointers["__cuMemPoolImportFromShareableHandle"]) + _wrappers_installed = True + return pointers + + +def install_driver_fn_wrappers(): + """Make the C++ driver function table use the test wrappers in this process. + + Call before ``cuda.core`` makes its first driver call; see the module + docstring. Calling it again has no effect. + """ + global _inspect_without_wrappers + if _inspect_without_wrappers is None: + _inspect_without_wrappers = _driver_loader._inspect_function_pointers + _driver_loader._inspect_function_pointers = _inspect_with_wrappers + + +cdef int _require_driver_fn_wrappers() except -1: + if not _wrappers_installed: + raise RuntimeError( + "cuda.core's driver function table does not hold the test wrappers yet. " + "Either install_driver_fn_wrappers() was not called before cuda.core's first driver call " + "in this process, or cuda.core has not made a driver call yet; arm the wrapper after one" + ) + return 0 + + +def arm_pool_release_gate(intptr_t pool, double timeout_sec, double grace_sec): + """Hold the next release of ``pool`` while the pool is imported again. + + The C++ layer calls ``cuMemPoolSetAccess`` only to revoke access just + before it destroys a pool (or an imported pool's imports), after its last + reference is gone. The first such call on ``pool`` after arming blocks + until a ``cuMemPoolImportFromShareableHandle`` from the C++ layer returns + ``pool``, or until ``timeout_sec`` passes. Once that import has returned, + it stays blocked until :func:`open_pool_release_gate` is called, or until + ``grace_sec`` passes, and then proceeds. Later calls pass through. + + Open the gate once the import has finished. An import that correctly waits + for the release cannot finish first, so the grace period ends the hold; an + import that does not wait finishes, opens the gate, and the release then + revokes access after the import was granted it, so the test sees the + damage. Use :func:`wait_pool_release_gate_entered` to start the import once + the release is held, and :func:`disarm_pool_release_gate` to check that the + import overlapped the release. + """ + _require_driver_fn_wrappers() + _arm_pool_release_gate(pool, timeout_sec, grace_sec) + + +def open_pool_release_gate(): + """Let a held release proceed once the import that overlapped it has finished.""" + _open_pool_release_gate() + + +def wait_pool_release_gate_entered(double timeout_sec): + """Wait until a release is held by the gate; return ``False`` on timeout or disarm.""" + cdef bint entered + with nogil: + entered = _wait_pool_release_gate_entered(timeout_sec) + return entered + + +def disarm_pool_release_gate(): + """Disarm the gate and let a held release proceed. + + Return ``True`` if a release was held and an import of the pool returned + while it was held, so the import overlapped the release. + """ + return _disarm_pool_release_gate() + + +def set_context_restore_fault(int status): + """Make ``cuda.core``'s next switch back to the current context fail on this thread. + + The next ``cuCtxSetCurrent`` that the C++ layer makes on this thread to the + context that is current now returns ``status`` without switching, so the + context it switched to stays current, exactly as a real failure would. The + C++ layer switches contexts only to enter an operation's context and to + restore the caller's afterwards, and it does not switch to a context that + is already current, so only a restoration can fail. 0 disarms the fault. + """ + cdef cydriver.CUcontext current = NULL + if status: + _require_driver_fn_wrappers() + HANDLE_RETURN(cydriver.cuCtxGetCurrent(¤t)) + _set_ctx_set_current_fault(status, current) diff --git a/cuda_core/cuda/core/_utils/_weak_handles.pyi b/cuda_core/cuda/core/_utils/_weak_handles.pyi deleted file mode 100644 index 737e4a9ef6c2..000000000000 --- a/cuda_core/cuda/core/_utils/_weak_handles.pyi +++ /dev/null @@ -1,54 +0,0 @@ -# This file was generated by stubgen-pyx v0.2.23 from cuda_core/cuda/core/_utils/_weak_handles.pyx - -"""Test-only weak handles for resource-handle lifetime checks. - -This module is **not** part of the public ``cuda.core`` API. It is built into -the package (like other private ``_utils`` modules) purely so the test suite can -observe, deterministically, when the strong references that keep a CUDA resource -alive have all been released -- without relying on driver- or hardware-specific -side effects (for example, whether freed device memory happens to remain -readable). - -Every resource handle is owned by a C++ ``std::shared_ptr``. A **weak handle** -is a non-owning ``std::weak_ptr`` observer of that control block: truthy while -some strong owner remains, falsy once the last one is gone. Use :func:`weak_handle` -to obtain a weak handle from a supported front-end object. - -To support another type, add a ``cdef _weak_from_`` that reads its ``cdef`` -handle field (see ``*.pxd``), assigns to :ctype:`OpaqueHandle`, and extend the -``isinstance`` chain in :func:`weak_handle`. Types whose slots hold arbitrary -Python owners via ``make_opaque_py`` are not covered here -- use -:class:`weakref.ref` on a weak-referenceable owner object in tests instead. -""" -from _typeshed import Incomplete -from typing_extensions import TypeAlias - -OpaqueWeakHandle: TypeAlias = Incomplete - -class WeakHandle: - """Non-owning weak handle for a resource's shared control block. - - Truthy while some strong owner of the underlying resource handle remains, - falsy once the last strong reference is released. Obtain instances via - :func:`weak_handle` rather than constructing directly. - """ - def __bool__(self): ... - def expired(self): - """Return ``True`` once every strong owner of the handle is gone.""" - def use_count(self): - """Number of strong owners currently sharing the handle.""" - -def weak_handle(obj): - """Return a :class:`WeakHandle` observing the resource behind ``obj``. - - Currently supports :class:`~cuda.core.Buffer` (allocation handle) and - :class:`~cuda.core.graph.GraphDefinition` (graph hierarchy handle). See - the module docstring for how to add more types. - - Raises - ------ - ValueError - If ``obj`` is a :class:`~cuda.core.Buffer` with no active allocation. - TypeError - If ``obj`` is not a supported type. - """ diff --git a/cuda_core/cuda/core/_utils/_weak_handles.pyx b/cuda_core/cuda/core/_utils/_weak_handles.pyx deleted file mode 100644 index c0c456ed7286..000000000000 --- a/cuda_core/cuda/core/_utils/_weak_handles.pyx +++ /dev/null @@ -1,117 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Test-only weak handles for resource-handle lifetime checks. - -This module is **not** part of the public ``cuda.core`` API. It is built into -the package (like other private ``_utils`` modules) purely so the test suite can -observe, deterministically, when the strong references that keep a CUDA resource -alive have all been released -- without relying on driver- or hardware-specific -side effects (for example, whether freed device memory happens to remain -readable). - -Every resource handle is owned by a C++ ``std::shared_ptr``. A **weak handle** -is a non-owning ``std::weak_ptr`` observer of that control block: truthy while -some strong owner remains, falsy once the last one is gone. Use :func:`weak_handle` -to obtain a weak handle from a supported front-end object. - -To support another type, add a ``cdef _weak_from_`` that reads its ``cdef`` -handle field (see ``*.pxd``), assigns to :ctype:`OpaqueHandle`, and extend the -``isinstance`` chain in :func:`weak_handle`. Types whose slots hold arbitrary -Python owners via ``make_opaque_py`` are not covered here -- use -:class:`weakref.ref` on a weak-referenceable owner object in tests instead. -""" - -from cuda.core._memory._buffer cimport Buffer -from cuda.core.graph._graph_definition cimport GraphDefinition -from cuda.core._rt cimport OpaqueHandle - - -# Cython cannot spell ``weak_ptr[const void]`` inline (the ``const void`` -# template argument fails to parse), so the weak type and its one constructor -# are provided by a small inline C++ shim local to this test-only module. This -# keeps the production resource_handles translation units untouched. -cdef extern from *: - """ - #include - namespace cuda_core_test { - using OpaqueWeakHandle = std::weak_ptr; - static inline OpaqueWeakHandle make_weak(const std::shared_ptr& h) { - return OpaqueWeakHandle(h); - } - } // namespace cuda_core_test - """ - cppclass OpaqueWeakHandle "cuda_core_test::OpaqueWeakHandle": - OpaqueWeakHandle() - bint expired() - long use_count() - OpaqueWeakHandle make_weak "cuda_core_test::make_weak" (const OpaqueHandle& h) - - -cdef class WeakHandle: - """Non-owning weak handle for a resource's shared control block. - - Truthy while some strong owner of the underlying resource handle remains, - falsy once the last strong reference is released. Obtain instances via - :func:`weak_handle` rather than constructing directly. - """ - - cdef OpaqueWeakHandle _w - - def __bool__(self): - return not self._w.expired() - - def expired(self): - """Return ``True`` once every strong owner of the handle is gone.""" - return self._w.expired() - - def use_count(self): - """Number of strong owners currently sharing the handle.""" - return self._w.use_count() - - -cdef WeakHandle _weak_from_opaque(OpaqueHandle h): - # Build the weak handle from a (temporary) strong handle. The strong copy - # lives only for the duration of this call, so it does not perturb the - # reference count the weak handle later reports. - cdef WeakHandle wh = WeakHandle.__new__(WeakHandle) - wh._w = make_weak(h) - return wh - - -cdef WeakHandle _weak_from_buffer(Buffer buf): - cdef OpaqueHandle h = buf._h_ptr - if not h: - raise ValueError("Buffer has no active allocation") - return _weak_from_opaque(h) - - -cdef WeakHandle _weak_from_graph_definition(GraphDefinition graph): - cdef OpaqueHandle h = graph._h_graph - if not h: - raise ValueError("GraphDefinition has no active graph") - return _weak_from_opaque(h) - - -def weak_handle(obj): - """Return a :class:`WeakHandle` observing the resource behind ``obj``. - - Currently supports :class:`~cuda.core.Buffer` (allocation handle) and - :class:`~cuda.core.graph.GraphDefinition` (graph hierarchy handle). See - the module docstring for how to add more types. - - Raises - ------ - ValueError - If ``obj`` is a :class:`~cuda.core.Buffer` with no active allocation. - TypeError - If ``obj`` is not a supported type. - """ - if isinstance(obj, Buffer): - return _weak_from_buffer(obj) - if isinstance(obj, GraphDefinition): - return _weak_from_graph_definition(obj) - raise TypeError( - f"weak_handle() does not support {type(obj).__name__!r}; " - "supported types: Buffer, GraphDefinition" - ) diff --git a/cuda_core/tests/AGENTS.md b/cuda_core/tests/AGENTS.md index 9598ddc6e731..460f127412d4 100644 --- a/cuda_core/tests/AGENTS.md +++ b/cuda_core/tests/AGENTS.md @@ -142,6 +142,50 @@ Follow these rules when adding or moving shared test code: - In directories without `__init__.py`, keep test-module basenames unique within this test suite. +## Keep test hooks out of production code + +Production modules under `cuda/core/` must not contain code that exists only +for tests. Do not add: + +- `*_for_testing` functions, setters, or Python wrappers in production modules; +- globals, thread-locals, or atomics that a production code path reads only so + a test can inject a fault, a delay, or a callback; +- `bint ..._for_testing` parameters or other test-only branches; +- `extern` declarations or aliases that exist only to serve a test wrapper. + +To make a hard-to-reach path testable, use the first option that works: + +1. **Drive it through the public API** or real conditions, for example an + oversized allocation, a closed resource, or a second device. +2. **Pass an object the code under test calls back into.** A `uuid.UUID` + subclass whose `__hash__` runs an action, or a `gc.callbacks` entry, can + interrupt a specific step deterministically (see + `tests/memory_ipc/test_ipc_pool_duplicate_import.py`). +3. **Observe or call internals from `cuda/core/_utils/_testing.pyx`.** This + test-only module `cimport`s private declarations, for example weak handles + built from `cdef` handle fields, or a wrapper around a `cdef` function + declared in a `.pxd`. Extend it rather than adding a module. +4. **Wrap a driver function.** To make a driver call fail or wait, add a + wrapper to the driver function wrappers in `_testing.pyx`; see + `set_context_restore_fault` and `arm_pool_release_gate`. Write the + wrapper in C++ in the inline block: it can run without the GIL, from any + thread, and during interpreter shutdown. When disarmed it must only check + an atomic or a thread-local and then call the driver. Its setter must call + `_require_driver_fn_wrappers()` when arming. `conftest.py` installs the + wrappers for the session, but a spawned child does not run `conftest.py` + and must call `install_driver_fn_wrappers()` before its first driver call. + To make two threads overlap, block one wrapper until another wrapper + observes the event it waits for, as `arm_pool_release_gate` does, instead + of sleeping for a fixed time; bound each wait with a timeout and assert + afterwards that the event, not the timeout, ended it. Then temporarily + revert the fix the test guards and confirm the test fails: proving the + overlap does not prove the test can see the bug. + +If none of these works, raise it in review before adding a hook, and explain +why. `_capture_callback_with_tail_failure_for_testing` in +`graph/_graph_builder.pyx` is a remaining legacy hook; do not use it as prior +art. + ## Skip only real setup failures `pytest.skip(reason)` records the test as SKIPPED with `reason` in the diff --git a/cuda_core/tests/conftest.py b/cuda_core/tests/conftest.py index a176de5479d6..2ea748e70aa3 100644 --- a/cuda_core/tests/conftest.py +++ b/cuda_core/tests/conftest.py @@ -56,8 +56,12 @@ _device, ) from cuda.core._memory._buffer import _live_owned_mempool_count, _live_va_reservation_count +from cuda.core._utils._testing import install_driver_fn_wrappers from cuda.core._utils.cuda_utils import handle_return +# Before any test makes a driver call through cuda.core; see cuda.core._utils._testing. +install_driver_fn_wrappers() + def pytest_collection_finish(session): # The per-test gc.collect() in init_cuda (below) must not re-traverse the diff --git a/cuda_core/tests/graph/test_graph_definition_lifetime.py b/cuda_core/tests/graph/test_graph_definition_lifetime.py index d0cc71797d90..e2c98df38809 100644 --- a/cuda_core/tests/graph/test_graph_definition_lifetime.py +++ b/cuda_core/tests/graph/test_graph_definition_lifetime.py @@ -898,7 +898,7 @@ def test_inflight_launch_retains_attachments_until_completion(init_cuda, make_mr outlives ``buf.close()`` until the launch completes and the graph is gone. For a virtual memory buffer that release also unmaps the range. """ - from cuda.core._utils._weak_handles import weak_handle + from cuda.core._utils._testing import weak_handle dev = Device() mr = make_mr(dev) @@ -962,7 +962,7 @@ def test_memcpy_node_retains_vmm_range_across_grow(init_cuda): buffer creates an alias; closing both buffers leaves the node as the last owner, so the range stays mapped until the graph that retains it is gone. """ - from cuda.core._utils._weak_handles import weak_handle + from cuda.core._utils._testing import weak_handle dev = Device() mr = _virtual_memory_resource(dev) @@ -1611,12 +1611,12 @@ def test_memcpy_buffer_allocations_released_after_graph_destroyed(init_cuda): """Destroying the graph frees both memcpy operand allocations. Each operand's device-pointer handle is observed via a weak handle - (see ``cuda.core._utils._weak_handles``), so release is checked at the + (see ``cuda.core._utils._testing``), so release is checked at the reference-count level rather than through a driver side effect. With both Buffer wrappers closed, the node attachment is the only remaining owner; destroying the graph releases it and the weak handles expire. """ - from cuda.core._utils._weak_handles import weak_handle + from cuda.core._utils._testing import weak_handle skip_if_mempool_unsupported() dev = Device() diff --git a/cuda_core/tests/graph/test_graph_node_update.py b/cuda_core/tests/graph/test_graph_node_update.py index cfb05a0481b2..bf7c93f58d12 100644 --- a/cuda_core/tests/graph/test_graph_node_update.py +++ b/cuda_core/tests/graph/test_graph_node_update.py @@ -17,7 +17,7 @@ from cuda.core import Device, DeviceMemoryResource, EventOptions, LaunchConfig, LegacyPinnedMemoryResource from cuda.core._memory._synchronous_memory_resource import _SynchronousMemoryResource -from cuda.core._utils._weak_handles import weak_handle +from cuda.core._utils._testing import weak_handle from cuda.core._utils.cuda_utils import CUDAError, driver, handle_return from cuda.core._utils.version import driver_version from cuda.core.graph import ( 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 1e8c7c4c6e59..4b4f4c212f91 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 @@ -40,14 +40,22 @@ from cuda.bindings import driver from cuda.core import Buffer, Device, DeviceMemoryResource from cuda.core._memory._buffer import _live_owned_mempool_count -from cuda.core._rt import _set_ipc_pool_release_delay_for_testing +from cuda.core._utils._testing import ( + arm_pool_release_gate, + disarm_pool_release_gate, + install_driver_fn_wrappers, + open_pool_release_gate, + wait_pool_release_gate_entered, +) NBYTES = 64 THREADS = 4 ITERATIONS = 20 -# The owner's release sleeps this long in the race test, so the re-import overlaps it. -RELEASE_DELAY_US = 50_000 -RACE_ITERATIONS = 3 +# How long the race test holds the release after the re-import's driver call. +# A correct registry makes the re-import wait for the release, so the hold +# always runs out; it only bounds how fast a broken registry's re-import must +# finish to be caught. +RELEASE_GRACE_SEC = 0.25 REENTRY_ITERATIONS = 100 LOOKUP_RACE_SECONDS = 0.5 @@ -121,6 +129,9 @@ def _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor): # The buffer is freed on another thread, which a per-thread default stream # would report as a cross-thread free. stream = device.create_stream() + # Only a hang reaches a gate timeout; it ends before run_child's timeout, so + # that a hang fails here with a message. + gate_timeout = child_timeout_sec() / 4 # The stack closes in reverse order: the new buffer and resource, then the # stream after it has synchronized the pending frees. with contextlib.ExitStack() as stack: @@ -130,6 +141,7 @@ def _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor): # The buffer holds the last reference to the pool once its resource is # closed, so closing the buffer releases the pool. with contextlib.closing(import_pool_resource(mr_type, device, int(alloc_handle))) as mr: + pool = int(mr.handle) outstanding = stack.enter_context(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) del mr @@ -139,28 +151,39 @@ def _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor): def release(): barrier.wait() + # The gate holds this release after its last reference is gone and + # before it revokes access, while the re-import below runs. outstanding.close() def reimport(): Device().set_current() barrier.wait() - # Start once the release is under way, inside its delay. - time.sleep(RELEASE_DELAY_US / 4 / 1e6) + # Start once the release is held, past the point where it could be joined. + assert wait_pool_release_gate_entered(gate_timeout), "the release never reached its access revocation" # 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)) + try: + mr = import_pool_resource(mr_type, device, int(alloc_handle)) + finally: + # Only an import that did not wait for the release gets here first. + open_pool_release_gate() reimported.append(mr) reimported_buffers.append(Buffer.from_ipc_descriptor(mr, descriptor, stream=stream)) + arm_pool_release_gate(pool, gate_timeout, RELEASE_GRACE_SEC) try: run_in_threads([release, reimport], barrier=barrier) finally: + overlapped = disarm_pool_release_gate() # 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) + # Without the overlap the race was not exercised, and a pass would mean nothing. + assert overlapped, "the re-import did not run while the release was held; the gate timed out" + # The release has finished: its cleanup must have left the new import alone. # The final release revokes access one GPU at a time, so check every GPU the # pool grants access to, not only the default one. @@ -173,14 +196,10 @@ def reimport(): def child_reimport_races_last_release(mr_type, alloc_handle, descriptor): - with _child_device() as (device, _baseline): - _set_ipc_pool_release_delay_for_testing(RELEASE_DELAY_US) - try: - with assert_no_cuda_warning(): - for _ in range(RACE_ITERATIONS): - _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor) - finally: - _set_ipc_pool_release_delay_for_testing(0) + # A spawned child does not run conftest.py, which installs the wrappers. + install_driver_fn_wrappers() + with _child_device() as (device, _baseline), assert_no_cuda_warning(): + _race_reimport_with_last_release(mr_type, device, alloc_handle, descriptor) def child_register_reentered_by_gc(mr_type, alloc_handle): diff --git a/cuda_core/tests/test_error_handling.py b/cuda_core/tests/test_error_handling.py index bfbec2ed0cfe..666abc3cd8fb 100644 --- a/cuda_core/tests/test_error_handling.py +++ b/cuda_core/tests/test_error_handling.py @@ -8,9 +8,10 @@ context is raised (or reported) with an explanation rather than swallowed or turned into a process abort; and a secondary failure that occurs while an exception is being raised is attached to that exception as a note. Restoration -failures are injected with the handle layer's test hook, which leaves the target -context current exactly as a real ``cuCtxSetCurrent`` failure would, so every -test here restores the context stack itself. +failures are injected through a test wrapper around the C++ layer's +``cuCtxSetCurrent`` (see ``cuda.core._utils._testing``), which leaves the target +context current exactly as a real failure would, so every test here restores the +context stack itself. """ import ctypes @@ -29,11 +30,8 @@ LegacyPinnedMemoryResource, ) from cuda.core._memory._synchronous_memory_resource import _SynchronousMemoryResource -from cuda.core._rt import ( - _attach_rollback_failure_for_testing, - _set_context_restore_fault_for_testing, -) from cuda.core._stream import default_stream +from cuda.core._utils._testing import attach_rollback_failure_for_testing, set_context_restore_fault from cuda.core._utils.cuda_utils import CUDAError, driver, handle_return from cuda.core._utils.version import BUILD_CUDA_MAJOR, driver_version from cuda.core.graph import GraphDefinition @@ -62,11 +60,11 @@ def no_context_with_restore_fault(status=INVALID_CONTEXT): """ previous = handle_return(driver.cuCtxPopCurrent()) assert current_context_handle() == 0 - _set_context_restore_fault_for_testing(status) + set_context_restore_fault(status) try: yield finally: - _set_context_restore_fault_for_testing(0) + set_context_restore_fault(0) handle_return(driver.cuCtxSetCurrent(driver.CUcontext(0))) handle_return(driver.cuCtxPushCurrent(previous)) @@ -140,14 +138,14 @@ def test_failed_call_raises_its_own_error_with_the_restore_failure_attached(init @thread_unsafe_context_fault @pytest.mark.agent_authored(model="claude-fable-5-1") def test_unused_restore_fault_does_not_fire_without_a_context_switch(init_cuda): - """The hook only affects restorations; a call in the current context never restores.""" + """The fault only affects restorations; a call in the current context never restores.""" dev = init_cuda - _set_context_restore_fault_for_testing(INVALID_CONTEXT) + set_context_restore_fault(INVALID_CONTEXT) try: stream = dev.create_stream() stream.close() finally: - _set_context_restore_fault_for_testing(0) + set_context_restore_fault(0) @thread_unsafe_context_fault @@ -184,13 +182,13 @@ def test_independent_cleanup_failures_are_reported_separately(mempool_device): with warnings.catch_warnings(record=True) as records: warnings.simplefilter("default", CUDAWarning) for buf in buffers: - _set_context_restore_fault_for_testing(INVALID_CONTEXT) + set_context_restore_fault(INVALID_CONTEXT) buf.close() # The failed restoration left the device's context current; clear it # so the next release also has to switch and fail the same way. handle_return(driver.cuCtxSetCurrent(driver.CUcontext(0))) finally: - _set_context_restore_fault_for_testing(0) + set_context_restore_fault(0) handle_return(driver.cuCtxSetCurrent(driver.CUcontext(0))) handle_return(driver.cuCtxPushCurrent(previous)) messages = [str(record.message) for record in records if issubclass(record.category, CUDAWarning)] @@ -268,13 +266,13 @@ def test_memset_update_keeps_new_owners_alive_when_context_cannot_be_restored(de # Updating from another device's context switches to the node's context and # must switch back; make that restoration fail. other_dev.set_current() - _set_context_restore_fault_for_testing(INVALID_CONTEXT) + set_context_restore_fault(INVALID_CONTEXT) try: with pytest.raises(CUDAError) as excinfo: node.update(dst=replacement, value=0x22) assert "could not be restored" in error_text(excinfo.value) finally: - _set_context_restore_fault_for_testing(0) + set_context_restore_fault(0) node_dev.set_current() def as_bytes(buffer): @@ -304,9 +302,9 @@ def test_rollback_failure_is_attached_to_the_propagating_exception(): raise RuntimeError("primary failure") except RuntimeError: with assert_no_cuda_warning(): - _attach_rollback_failure_for_testing(INVALID_VALUE) + attach_rollback_failure_for_testing(INVALID_VALUE) with assert_no_cuda_warning(): - _attach_rollback_failure_for_testing(DEINITIALIZED) + attach_rollback_failure_for_testing(DEINITIALIZED) raise exc = excinfo.value assert str(exc) == "primary failure" @@ -314,4 +312,4 @@ def test_rollback_failure_is_attached_to_the_propagating_exception(): assert "cuTestOperation failed while testing: CUDA_ERROR_INVALID_VALUE" in exc.__notes__[0] # With no exception being handled there is nothing to attach to. with pytest.warns(CUDAWarning, match="cuTestOperation failed while testing"): - _attach_rollback_failure_for_testing(INVALID_VALUE) + attach_rollback_failure_for_testing(INVALID_VALUE)