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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion cuda_core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down
3 changes: 2 additions & 1 deletion cuda_core/cuda/core/_cpp/rt/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 0 additions & 5 deletions cuda_core/cuda/core/_cpp/rt/api.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 0 additions & 18 deletions cuda_core/cuda/core/_cpp/rt/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
Expand Down
5 changes: 0 additions & 5 deletions cuda_core/cuda/core/_cpp/rt/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 0 additions & 14 deletions cuda_core/cuda/core/_cpp/rt/memory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,11 @@
#include "error.hpp"
#include "internal.hpp"
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <thread>
#include <utility>
#ifndef _WIN32
#include <unistd.h>
Expand All @@ -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<long long> g_live_owned_mempools{0};

// See set_ipc_pool_release_delay_for_testing.
std::atomic<unsigned int> 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
Expand Down Expand Up @@ -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;
Expand Down
22 changes: 0 additions & 22 deletions cuda_core/cuda/core/_rt.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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``.
"""
39 changes: 0 additions & 39 deletions cuda_core/cuda/core/_rt.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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" (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(<cydriver.CUresult>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", <cydriver.CUresult>status, b"failed while testing")
129 changes: 129 additions & 0 deletions cuda_core/cuda/core/_utils/_testing.pyi
Original file line number Diff line number Diff line change
@@ -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_<type>`` 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.
"""
Loading
Loading