From 8a7dbac168a3e9a3b555ec75a4ca1c02a13d6c48 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 13:57:37 -0800 Subject: [PATCH 1/7] refactor(cuda.core): move the rollback-failure test wrapper into a test-only module The Python wrapper that tests call to exercise attach_rollback_failure() lived in _rt.pyx, together with an extern alias that existed only for it. Move it to the test-only module that already provides weak handles, and rename that module from _utils/_weak_handles to _utils/_testing now that it holds more than weak handles. The wrapper cimports attach_rollback_failure from _rt.pxd, so _rt keeps no test code for it. --- cuda_core/cuda/core/_rt.pyi | 7 ----- cuda_core/cuda/core/_rt.pyx | 15 ---------- .../{_weak_handles.pyi => _testing.pyi} | 26 +++++++++++----- .../{_weak_handles.pyx => _testing.pyx} | 30 ++++++++++++++----- .../graph/test_graph_definition_lifetime.py | 8 ++--- .../tests/graph/test_graph_node_update.py | 2 +- cuda_core/tests/test_error_handling.py | 12 ++++---- 7 files changed, 52 insertions(+), 48 deletions(-) rename cuda_core/cuda/core/_utils/{_weak_handles.pyi => _testing.pyi} (68%) rename cuda_core/cuda/core/_utils/{_weak_handles.pyx => _testing.pyx} (79%) diff --git a/cuda_core/cuda/core/_rt.pyi b/cuda_core/cuda/core/_rt.pyi index ad50dd4bd1e9..0a50337a2ae8 100644 --- a/cuda_core/cuda/core/_rt.pyi +++ b/cuda_core/cuda/core/_rt.pyi @@ -64,10 +64,3 @@ def _set_ipc_pool_release_delay_for_testing(microseconds: int): 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..a5503632b591 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -57,10 +57,6 @@ 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 @@ -367,14 +363,3 @@ def _set_ipc_pool_release_delay_for_testing(unsigned int microseconds): 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/_weak_handles.pyi b/cuda_core/cuda/core/_utils/_testing.pyi similarity index 68% rename from cuda_core/cuda/core/_utils/_weak_handles.pyi rename to cuda_core/cuda/core/_utils/_testing.pyi index 737e4a9ef6c2..c210f5bae907 100644 --- a/cuda_core/cuda/core/_utils/_weak_handles.pyi +++ b/cuda_core/cuda/core/_utils/_testing.pyi @@ -1,13 +1,18 @@ -# This file was generated by stubgen-pyx v0.2.23 from cuda_core/cuda/core/_utils/_weak_handles.pyx +# This file was generated by stubgen-pyx v0.2.23 from cuda_core/cuda/core/_utils/_testing.pyx -"""Test-only weak handles for resource-handle lifetime checks. +"""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 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). +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 @@ -52,3 +57,10 @@ def weak_handle(obj): 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``. + """ diff --git a/cuda_core/cuda/core/_utils/_weak_handles.pyx b/cuda_core/cuda/core/_utils/_testing.pyx similarity index 79% rename from cuda_core/cuda/core/_utils/_weak_handles.pyx rename to cuda_core/cuda/core/_utils/_testing.pyx index c0c456ed7286..a9e35df254e2 100644 --- a/cuda_core/cuda/core/_utils/_weak_handles.pyx +++ b/cuda_core/cuda/core/_utils/_testing.pyx @@ -1,14 +1,19 @@ # 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. +"""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 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). +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 @@ -22,9 +27,10 @@ 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.bindings cimport cydriver from cuda.core._memory._buffer cimport Buffer from cuda.core.graph._graph_definition cimport GraphDefinition -from cuda.core._rt cimport OpaqueHandle +from cuda.core._rt cimport OpaqueHandle, attach_rollback_failure # Cython cannot spell ``weak_ptr[const void]`` inline (the ``const void`` @@ -115,3 +121,13 @@ def weak_handle(obj): f"weak_handle() does not support {type(obj).__name__!r}; " "supported types: Buffer, GraphDefinition" ) + + +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") 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/test_error_handling.py b/cuda_core/tests/test_error_handling.py index bfbec2ed0cfe..629198c5ada1 100644 --- a/cuda_core/tests/test_error_handling.py +++ b/cuda_core/tests/test_error_handling.py @@ -29,11 +29,9 @@ 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._rt import _set_context_restore_fault_for_testing from cuda.core._stream import default_stream +from cuda.core._utils._testing import attach_rollback_failure_for_testing 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 @@ -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) From 99baf89e0bf5e6a87d7e281debc54626a97dc037 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 14:01:56 -0800 Subject: [PATCH 2/7] test(cuda.core): delay the race test's pool release from test code, not a production hook The re-import race test made an imported pool's owner sleep before it revoked access through set_ipc_pool_release_delay_for_testing(), a global delay read by the production deleter. Remove that hook from memory.cpp, api.hpp and _rt. The test now delays the same step from the test-only _utils/_testing module. The C++ layer calls the driver through a function table that it fills once per process from cuda.bindings' _inspect_function_pointers(). The race test's spawned child replaces that function before its first driver call, so that the table's cuMemPoolSetAccess entry is a C++ wrapper that sleeps when armed and then calls the driver. The C++ layer calls cuMemPoolSetAccess only for the revoke before a pool is destroyed, the point where the hook slept. Arming the delay raises if the table was filled without the wrapper. Disabling the release wait in ReleasingHandleRegistry makes the test fail for both pinned and device pools with the delay armed, and pass without it. --- cuda_core/cuda/core/_cpp/rt/api.hpp | 5 - cuda_core/cuda/core/_cpp/rt/memory.cpp | 14 --- cuda_core/cuda/core/_rt.pyi | 7 -- cuda_core/cuda/core/_rt.pyx | 12 --- cuda_core/cuda/core/_utils/_testing.pyi | 29 ++++++ cuda_core/cuda/core/_utils/_testing.pyx | 97 +++++++++++++++++++ .../test_ipc_pool_duplicate_import.py | 10 +- 7 files changed, 132 insertions(+), 42 deletions(-) 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/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 0a50337a2ae8..bce560bed4a2 100644 --- a/cuda_core/cuda/core/_rt.pyi +++ b/cuda_core/cuda/core/_rt.pyi @@ -57,10 +57,3 @@ def _set_context_restore_fault_for_testing(status: int): 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. - """ diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index a5503632b591..5be3dc3a6166 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -190,8 +190,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 @@ -353,13 +351,3 @@ def _set_context_restore_fault_for_testing(int status): ``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) diff --git a/cuda_core/cuda/core/_utils/_testing.pyi b/cuda_core/cuda/core/_utils/_testing.pyi index c210f5bae907..eb96291454c1 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyi +++ b/cuda_core/cuda/core/_utils/_testing.pyi @@ -24,10 +24,25 @@ 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, for example at the start of a spawned +child. The setters raise if the table was filled without the wrappers, so a +test cannot silently run unarmed. """ from _typeshed import Incomplete from typing_extensions import TypeAlias +_inspect_without_wrappers = None +_wrappers_installed = False OpaqueWeakHandle: TypeAlias = Incomplete class WeakHandle: @@ -64,3 +79,17 @@ def attach_rollback_failure_for_testing(status: int): 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 set_mempool_set_access_delay(microseconds: int): + """Make every ``cuMemPoolSetAccess`` call from the C++ layer sleep first. + + The C++ layer calls ``cuMemPoolSetAccess`` only to revoke access just + before it destroys a pool (or an imported pool's imports), so the delay + holds a pool's release in that state. 0 disables the delay. + """ diff --git a/cuda_core/cuda/core/_utils/_testing.pyx b/cuda_core/cuda/core/_utils/_testing.pyx index a9e35df254e2..81fcf5c5b06c 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyx +++ b/cuda_core/cuda/core/_utils/_testing.pyx @@ -25,13 +25,30 @@ 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, for example at the start of a spawned +child. The setters raise if the table was filled without the wrappers, so a +test cannot silently run unarmed. """ +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 +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 @@ -131,3 +148,83 @@ def attach_rollback_failure_for_testing(int status): 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 + namespace cuda_core_testing { + using MemPoolSetAccessFn = CUresult(CUDAAPI *)(CUmemoryPool, const CUmemAccessDesc *, size_t); + static std::atomic real_mempool_set_access{nullptr}; + static std::atomic mempool_set_access_delay_us{0}; + + static CUresult CUDAAPI delayed_mempool_set_access( + CUmemoryPool pool, const CUmemAccessDesc *map, size_t count) { + if (unsigned int delay = mempool_set_access_delay_us.load()) { + std::this_thread::sleep_for(std::chrono::microseconds(delay)); + } + 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(&delayed_mempool_set_access); + } + static void set_mempool_set_access_delay(unsigned int microseconds) { + mempool_set_access_delay_us.store(microseconds); + } + } // namespace cuda_core_testing + """ + intptr_t _wrap_mempool_set_access "cuda_core_testing::wrap_mempool_set_access" (intptr_t real) noexcept + void _set_mempool_set_access_delay "cuda_core_testing::set_mempool_set_access_delay" ( + unsigned int microseconds) noexcept nogil + + +_inspect_without_wrappers = None +_wrappers_installed = False + + +def _inspect_with_wrappers(): + global _wrappers_installed + pointers = dict(_inspect_without_wrappers()) + pointers["__cuMemPoolSetAccess"] = _wrap_mempool_set_access(pointers["__cuMemPoolSetAccess"]) + _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 filled its driver function table without the test wrappers; " + "call install_driver_fn_wrappers() before cuda.core's first driver call in this process" + ) + return 0 + + +def set_mempool_set_access_delay(unsigned int microseconds): + """Make every ``cuMemPoolSetAccess`` call from the C++ layer sleep first. + + The C++ layer calls ``cuMemPoolSetAccess`` only to revoke access just + before it destroys a pool (or an imported pool's imports), so the delay + holds a pool's release in that state. 0 disables the delay. + """ + if microseconds: + _require_driver_fn_wrappers() + _set_mempool_set_access_delay(microseconds) diff --git a/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py b/cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py index 1dd339a692d2..2550d3c9c6ed 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 @@ -37,12 +37,13 @@ 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 install_driver_fn_wrappers, set_mempool_set_access_delay NBYTES = 64 THREADS = 4 ITERATIONS = 20 -# The owner's release sleeps this long in the race test, so the re-import overlaps it. +# The owner's release sleeps this long before it revokes access in the race test, +# so the re-import overlaps it. RELEASE_DELAY_US = 50_000 RACE_ITERATIONS = 3 REENTRY_ITERATIONS = 20 @@ -166,14 +167,15 @@ def reimport(): def child_reimport_races_last_release(mr_type, alloc_handle, descriptor): + install_driver_fn_wrappers() with _child_device() as (device, _baseline): - _set_ipc_pool_release_delay_for_testing(RELEASE_DELAY_US) + set_mempool_set_access_delay(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) + set_mempool_set_access_delay(0) def child_register_reentered_by_gc(mr_type, alloc_handle): From 61a376f601a36000fe8601f7574390fbcf224734 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 14:05:33 -0800 Subject: [PATCH 3/7] test(cuda.core): inject context restoration faults from test code, not a production hook restore_context() checked a thread-local fault that tests set through set_context_restore_fault_for_testing(). Remove that hook from context.cpp, error.hpp and _rt. The test-only _utils/_testing module now wraps the driver function table's cuCtxSetCurrent entry, the same way it wraps cuMemPoolSetAccess for the IPC race test. set_context_restore_fault(status) records the context that is current on the calling thread, and the wrapper fails the next switch back to it on that thread without switching, which leaves the operation's context current as a real failure would. enter_context() never switches to the context that is already current, so only the restoration fails. conftest.py installs the wrappers before any test makes a driver call. When disarmed, the wrappers only check a thread-local or an atomic before calling the driver. --- cuda_core/AGENTS.md | 2 +- cuda_core/cuda/core/_cpp/rt/DESIGN.md | 3 +- cuda_core/cuda/core/_cpp/rt/context.cpp | 18 ---------- cuda_core/cuda/core/_cpp/rt/error.hpp | 5 --- cuda_core/cuda/core/_rt.pyi | 8 ----- cuda_core/cuda/core/_rt.pyx | 12 ------- cuda_core/cuda/core/_utils/_testing.pyi | 14 ++++++-- cuda_core/cuda/core/_utils/_testing.pyx | 48 +++++++++++++++++++++++-- cuda_core/tests/conftest.py | 4 +++ cuda_core/tests/test_error_handling.py | 28 +++++++-------- 10 files changed, 79 insertions(+), 63 deletions(-) diff --git a/cuda_core/AGENTS.md b/cuda_core/AGENTS.md index 863785d22281..301c869369ac 100644 --- a/cuda_core/AGENTS.md +++ b/cuda_core/AGENTS.md @@ -282,7 +282,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/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/_rt.pyi b/cuda_core/cuda/core/_rt.pyi index bce560bed4a2..e119da114e0d 100644 --- a/cuda_core/cuda/core/_rt.pyi +++ b/cuda_core/cuda/core/_rt.pyi @@ -49,11 +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. - """ diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index 5be3dc3a6166..51e37acdb01f 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -60,8 +60,6 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": 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" ( @@ -341,13 +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) diff --git a/cuda_core/cuda/core/_utils/_testing.pyi b/cuda_core/cuda/core/_utils/_testing.pyi index eb96291454c1..3dfdb0f3c2da 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyi +++ b/cuda_core/cuda/core/_utils/_testing.pyi @@ -34,8 +34,8 @@ fills once per process, on its first driver call, from :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, for example at the start of a spawned -child. The setters raise if the table was filled without the wrappers, so a +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 if the table was filled without the wrappers, so a test cannot silently run unarmed. """ from _typeshed import Incomplete @@ -93,3 +93,13 @@ def set_mempool_set_access_delay(microseconds: int): before it destroys a pool (or an imported pool's imports), so the delay holds a pool's release in that state. 0 disables the delay. """ +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 index 81fcf5c5b06c..e2983ff76c7e 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyx +++ b/cuda_core/cuda/core/_utils/_testing.pyx @@ -35,8 +35,8 @@ fills once per process, on its first driver call, from :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, for example at the start of a spawned -child. The setters raise if the table was filled without the wrappers, so a +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 if the table was filled without the wrappers, so a test cannot silently run unarmed. """ @@ -46,6 +46,7 @@ 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 @@ -160,6 +161,28 @@ cdef extern from *: #include #include namespace cuda_core_testing { + 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; + } + using MemPoolSetAccessFn = CUresult(CUDAAPI *)(CUmemoryPool, const CUmemAccessDesc *, size_t); static std::atomic real_mempool_set_access{nullptr}; static std::atomic mempool_set_access_delay_us{0}; @@ -180,6 +203,9 @@ cdef extern from *: } } // namespace cuda_core_testing """ + intptr_t _wrap_ctx_set_current "cuda_core_testing::wrap_ctx_set_current" (intptr_t real) noexcept + void _set_ctx_set_current_fault "cuda_core_testing::set_ctx_set_current_fault" ( + cydriver.CUresult status, cydriver.CUcontext target) noexcept nogil intptr_t _wrap_mempool_set_access "cuda_core_testing::wrap_mempool_set_access" (intptr_t real) noexcept void _set_mempool_set_access_delay "cuda_core_testing::set_mempool_set_access_delay" ( unsigned int microseconds) noexcept nogil @@ -192,6 +218,7 @@ _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"]) _wrappers_installed = True return pointers @@ -228,3 +255,20 @@ def set_mempool_set_access_delay(unsigned int microseconds): if microseconds: _require_driver_fn_wrappers() _set_mempool_set_access_delay(microseconds) + + +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/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/test_error_handling.py b/cuda_core/tests/test_error_handling.py index 629198c5ada1..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,9 +30,8 @@ LegacyPinnedMemoryResource, ) from cuda.core._memory._synchronous_memory_resource import _SynchronousMemoryResource -from cuda.core._rt import _set_context_restore_fault_for_testing from cuda.core._stream import default_stream -from cuda.core._utils._testing import attach_rollback_failure_for_testing +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 @@ -60,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)) @@ -138,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 @@ -182,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)] @@ -266,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): From 32ce52a6b44ef6fcd175466a5dee42e68787cd13 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 14:19:50 -0800 Subject: [PATCH 4/7] docs(cuda.core): keep test hooks out of production code Add a tests/AGENTS.md section that lists the test-only patterns production modules must not contain and the alternatives to use instead, in order of preference: the public API, objects the code under test calls back into, the test-only _utils/_testing module, and its driver function wrappers. --- cuda_core/tests/AGENTS.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/cuda_core/tests/AGENTS.md b/cuda_core/tests/AGENTS.md index 9598ddc6e731..b855110eddb2 100644 --- a/cuda_core/tests/AGENTS.md +++ b/cuda_core/tests/AGENTS.md @@ -142,6 +142,44 @@ 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 `set_mempool_set_access_delay`. 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. + +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 From 2ed05d7572c63295f17732da3589121ab90d696e Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 14:21:52 -0800 Subject: [PATCH 5/7] docs(cuda.core): point production-code guidance at the test-hook rules Agents editing production code follow cuda_core/AGENTS.md, not tests/AGENTS.md, so add an editing-guidance bullet that forbids test-only hooks and points to the alternatives in tests/AGENTS.md. --- cuda_core/AGENTS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cuda_core/AGENTS.md b/cuda_core/AGENTS.md index 301c869369ac..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 From 0959243a81ed18229193237ef83ea8abd73926ae Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 14:49:18 -0800 Subject: [PATCH 6/7] test(cuda.core): gate the race test's pool release instead of delaying it The race test held the owner's release with a fixed 50 ms sleep and started the re-import 12.5 ms in. If the release thread stalled past that offset, the re-import joined the still-live owner and the test passed without exercising the race. Replace the delay with a gate built from two driver function wrappers in cuda.core._utils._testing: - The first cuMemPoolSetAccess on the target pool after arming (the release's access revocation, after its last reference is gone) blocks. - A new wrapper on cuMemPoolImportFromShareableHandle signals when an import returns that pool while the release is held, which proves the overlap. - The release then stays held until the test opens the gate after the import has finished, or a grace period passes. A correct registry makes the import wait for the release, so the grace period always ends the hold; a broken one lets the import finish first, so the revocation lands after the access grant and the test sees the damage. The re-import waits for the release to be held instead of sleeping, and the test asserts the overlap, so a pass always means the race was exercised. With the registry's release wait disabled, the test now fails for both device and pinned pools; without the grace phase, the pinned case passed. Also: - Name both causes in the error raised when a wrapper is armed before the table holds the wrappers, and document arming after the first driver call. - Use one C++ namespace for the module's inline blocks, explain why the real driver pointers are atomic and why the rollback wrapper keeps its _for_testing suffix, and rewrap the module docstring. - Describe the gate pattern and the revert-the-fix check in tests/AGENTS.md. Co-Authored-By: Claude Opus 5.5 --- cuda_core/cuda/core/_utils/_testing.pyi | 36 +++- cuda_core/cuda/core/_utils/_testing.pyx | 189 +++++++++++++++--- cuda_core/tests/AGENTS.md | 8 +- .../test_ipc_pool_duplicate_import.py | 55 +++-- 4 files changed, 238 insertions(+), 50 deletions(-) diff --git a/cuda_core/cuda/core/_utils/_testing.pyi b/cuda_core/cuda/core/_utils/_testing.pyi index 3dfdb0f3c2da..c028c8438ed9 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyi +++ b/cuda_core/cuda/core/_utils/_testing.pyi @@ -35,8 +35,10 @@ fills once per process, on its first driver call, from 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 if the table was filled without the wrappers, so a -test cannot silently run unarmed. +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 @@ -86,12 +88,34 @@ def install_driver_fn_wrappers(): Call before ``cuda.core`` makes its first driver call; see the module docstring. Calling it again has no effect. """ -def set_mempool_set_access_delay(microseconds: int): - """Make every ``cuMemPoolSetAccess`` call from the C++ layer sleep first. +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), so the delay - holds a pool's release in that state. 0 disables the delay. + 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. diff --git a/cuda_core/cuda/core/_utils/_testing.pyx b/cuda_core/cuda/core/_utils/_testing.pyx index e2983ff76c7e..3749398cfa39 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyx +++ b/cuda_core/cuda/core/_utils/_testing.pyx @@ -36,8 +36,10 @@ fills once per process, on its first driver call, from 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 if the table was filled without the wrappers, so a -test cannot silently run unarmed. +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 @@ -141,6 +143,8 @@ def weak_handle(obj): ) +# 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. @@ -157,10 +161,13 @@ cdef extern from *: """ #include #include + #include #include - #include + #include #include - namespace cuda_core_testing { + 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; @@ -183,32 +190,126 @@ cdef extern from *: 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; + 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 std::atomic mempool_set_access_delay_us{0}; - static CUresult CUDAAPI delayed_mempool_set_access( + static CUresult CUDAAPI gated_mempool_set_access( CUmemoryPool pool, const CUmemAccessDesc *map, size_t count) { - if (unsigned int delay = mempool_set_access_delay_us.load()) { - std::this_thread::sleep_for(std::chrono::microseconds(delay)); + 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.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; }); + } + } } 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(&delayed_mempool_set_access); + 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.entered && !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.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 void set_mempool_set_access_delay(unsigned int microseconds) { - mempool_set_access_delay_us.store(microseconds); + 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_testing + } // namespace cuda_core_test """ - intptr_t _wrap_ctx_set_current "cuda_core_testing::wrap_ctx_set_current" (intptr_t real) noexcept - void _set_ctx_set_current_fault "cuda_core_testing::set_ctx_set_current_fault" ( + 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_testing::wrap_mempool_set_access" (intptr_t real) noexcept - void _set_mempool_set_access_delay "cuda_core_testing::set_mempool_set_access_delay" ( - unsigned int microseconds) 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 @@ -220,6 +321,8 @@ def _inspect_with_wrappers(): 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 @@ -239,22 +342,56 @@ def install_driver_fn_wrappers(): cdef int _require_driver_fn_wrappers() except -1: if not _wrappers_installed: raise RuntimeError( - "cuda.core filled its driver function table without the test wrappers; " - "call install_driver_fn_wrappers() before cuda.core's first driver call in this process" + "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 set_mempool_set_access_delay(unsigned int microseconds): - """Make every ``cuMemPoolSetAccess`` call from the C++ layer sleep first. +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), so the delay - holds a pool's release in that state. 0 disables the delay. + 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. """ - if microseconds: - _require_driver_fn_wrappers() - _set_mempool_set_access_delay(microseconds) + _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): diff --git a/cuda_core/tests/AGENTS.md b/cuda_core/tests/AGENTS.md index b855110eddb2..460f127412d4 100644 --- a/cuda_core/tests/AGENTS.md +++ b/cuda_core/tests/AGENTS.md @@ -167,13 +167,19 @@ To make a hard-to-reach path testable, use the first option that works: 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 `set_mempool_set_access_delay`. Write the + `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 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 2550d3c9c6ed..f1cfd9d707b8 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 @@ -17,7 +17,6 @@ import gc import multiprocessing as mp import threading -import time import uuid import helpers @@ -37,16 +36,28 @@ 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._utils._testing import install_driver_fn_wrappers, set_mempool_set_access_delay +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 before it revokes access 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 = 20 +# 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 # these tests spawn new processes and files which fails for very many threads; # child processes and IPC fixtures are shared across workers (#2784); cap at two threads @@ -118,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: @@ -127,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 @@ -136,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. (mr,) = reimported (buffer,) = reimported_buffers @@ -167,15 +193,10 @@ def reimport(): def child_reimport_races_last_release(mr_type, alloc_handle, descriptor): + # A spawned child does not run conftest.py, which installs the wrappers. install_driver_fn_wrappers() - with _child_device() as (device, _baseline): - set_mempool_set_access_delay(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_mempool_set_access_delay(0) + 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): From 43437421913b37457cc9ff98fed2ccf0c7e95651 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Tue, 24 Nov 2026 15:01:48 -0800 Subject: [PATCH 7/7] test(cuda.core): count only imports made while the pool release is held After the pool release gate timed out, its "entered" flag stayed set, so a later import still marked the release as overlapped and the race test's overlap check could pass without an overlap. Track whether the release is still blocked in a separate "held" flag, cleared under the mutex when the release proceeds, and require it before an import counts. Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/cuda/core/_utils/_testing.pyx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cuda_core/cuda/core/_utils/_testing.pyx b/cuda_core/cuda/core/_utils/_testing.pyx index 3749398cfa39..fbe35d71da08 100644 --- a/cuda_core/cuda/core/_utils/_testing.pyx +++ b/cuda_core/cuda/core/_utils/_testing.pyx @@ -201,7 +201,8 @@ cdef extern from *: CUmemoryPool pool = nullptr; std::chrono::duration timeout{0}; std::chrono::duration grace{0}; - bool entered = false; + 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; @@ -225,11 +226,14 @@ cdef extern from *: 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); @@ -249,7 +253,7 @@ cdef extern from *: PoolReleaseGate &gate = pool_release_gate(); std::lock_guard lock(gate.mutex); // Only an import made while the release is held counts. - if (gate.entered && !gate.disarmed && *pool == gate.pool) { + if (gate.held && !gate.disarmed && *pool == gate.pool) { gate.imported = true; gate.changed.notify_all(); } @@ -268,6 +272,7 @@ cdef extern from *: 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;