diff --git a/cuda_core/cuda/core/_context.pxd b/cuda_core/cuda/core/_context.pxd index 3476fffb322c..1b917f7834cf 100644 --- a/cuda_core/cuda/core/_context.pxd +++ b/cuda_core/cuda/core/_context.pxd @@ -25,6 +25,10 @@ cdef class Context: cpdef close(self) +cdef int Context_get_primary_handle(int device_id, ContextHandle* h_context) except -1 +cdef Context Context_primary(int device_id) + + cdef inline int Context_check_open(Context self) except -1: if not self._h_context: raise RuntimeError("Context has been closed") diff --git a/cuda_core/cuda/core/_context.pyx b/cuda_core/cuda/core/_context.pyx index 725dd8eb7fdd..48525e866a63 100644 --- a/cuda_core/cuda/core/_context.pyx +++ b/cuda_core/cuda/core/_context.pyx @@ -18,6 +18,7 @@ from cuda.core._rt cimport ( create_context_handle_from_green_ctx, get_context_green_ctx, get_last_error, + get_primary_context, as_intptr, as_py, ) @@ -150,6 +151,26 @@ cdef class Context: return f"" +cdef int Context_get_primary_handle(int device_id, ContextHandle* h_context) except -1: + """Store the primary context of ``device_id`` in ``h_context``. + + cuda.core retains it on first use and never releases it. Raises if it + cannot be retained. + """ + h_context[0] = get_primary_context(device_id) + if not h_context[0]: + HANDLE_RETURN(get_last_error()) + raise RuntimeError(f"Failed to retain the primary context for device {device_id}") + return 0 + + +cdef Context Context_primary(int device_id): + """Return a :class:`Context` for the primary context of ``device_id``.""" + cdef ContextHandle h_context + Context_get_primary_handle(device_id, &h_context) + return Context._from_handle(Context, h_context, device_id) + + @dataclass cdef class ContextOptions: """Options for context creation. diff --git a/cuda_core/cuda/core/_cpp/rt/DESIGN.md b/cuda_core/cuda/core/_cpp/rt/DESIGN.md index 2341aab388a2..5b342a1fae9c 100644 --- a/cuda_core/cuda/core/_cpp/rt/DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/DESIGN.md @@ -233,7 +233,8 @@ Two rules follow: 1. Do not make a `DRIVER_CALL` while the caller holds a C++ lock, because the fill acquires the GIL. Resolve the table before the lock (`ensure_fn_table(FnTable::driver)`) and use the raw pointer inside it, - marked `// raw:` (see `deviceptr_import_ipc`). + marked `// raw:` (see `deviceptr_import_ipc`, and `pin_primary_context` + under the primary-context table's mutex). 2. If the Cython layer gates a driver function, gate it at the version cuda-bindings requests it at (the number in the table), not at the version the driver first shipped it. @@ -317,7 +318,61 @@ that must update shared state before user code can run does so in `cleanup_in_context`'s `after_cleanup` hook, which runs once the cleanup is done and before anything that may run user code; the IPC pointer deleter releases its registry entry there. The registries store `weak_ptr`s, -so erasing an entry under a registry lock never runs a deleter. +so erasing an entry under a registry lock never runs a deleter. Releasing a +handle can, though: `HandleRegistry::insert_or_get` therefore destroys a +displaced handle only after it has unlocked, and a caller drops a losing +candidate outside the lock (REGISTRY_DESIGN.md). + +Resolving a context handle can call the driver and report a failure, so +`create_context_handle_ref()`, `create_current_context_handle_ref()`, +`get_current_context()` and everything that calls them, such as +`make_deallocation_stream()` for a default-stream token, must not run while a +C++ lock is held (see "Primary contexts"). `deviceptr_import_ipc` +resolves its deallocation stream before it takes the IPC pointer cache's mutex +for this reason. + +### Primary contexts + +`cuda.core` retains each device's primary context at most once per process and +never releases it, as the CUDA runtime does. The driver destroys a primary +context when its last retain is released, so code outside `cuda.core` +(`cuDevicePrimaryCtxReset`, `cudaDeviceReset`) is the only way a primary context +that `cuda.core` has handed out can go away. Before #1368 `cuda.core` already +behaved this way; #1368 released the retain when the last handle dropped, which +#3533 showed to be wrong. + +- `get_primary_context()` pins one retaining `ContextBox` per device in a + process-wide table (`pin_primary_context()` in `context.cpp`). The table is + leaked on purpose and holds a strong reference, so the box's deleter never + runs and its retain is never given back. The table is read without a lock: + pinning publishes a new immutable snapshot under the table's mutex, and old + snapshots are leaked, so a reader never sees freed memory. There is no + per-thread cache, so a thread's exit has no effect on primary contexts. The + mutex and the snapshot pointer are constant-initialized globals, not + function-local statics, so no static-initialization guard is involved (see + "Static Initialization and Deadlock Hazards"). +- `create_context_handle_ref()`, `create_current_context_handle_ref()` and + `get_current_context()` pin a primary context that another library made + current: when `ctx` is the calling thread's current context and its device's + active primary context, it is retained and pinned. All three go through + `resolve_context_handle()`; the last two are for callers that already know + what is current, so it is not queried again. Only the current context is + examined, because its device is the only one that can be queried without + switching contexts. An inactive primary context is never retained, because + that would create it. When the active primary context turns out to be + another one, the retain taken to find out is given back. That release cannot + destroy a context, because it was active without that retain. +- A context that is not current at the time of the lookup, such as another + context's stream or a graph node's update context, gets a plain handle that + does not keep it alive. +- The retain runs with the GIL released, under the table's mutex, through the + raw `p_` pointers after `ensure_fn_table()` (see "The GIL is the outermost + lock"). Giving back a probe retain can report a failure through Python, so it + runs after the mutex is released. +- Cython code gets a primary context through `Context_get_primary_handle()` + (a `ContextHandle`) or `Context_primary()` (a `Context`) in `_context.pyx`, + not by calling `get_primary_context()` directly. Both drain + `get_last_error()` and raise on failure, so every caller fails the same way. ### Static Initialization and Deadlock Hazards diff --git a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md index 8fb71e13a9f1..951ee75d4759 100644 --- a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md @@ -15,7 +15,8 @@ together to map a raw driver handle all the way back to the original Python object. Both use weak references so they do not prevent cleanup. Entries are removed either explicitly (via `destroy()` or a Box destructor) or implicitly when the weak reference -expires. +expires. The one exception is a primary context's Box, which a separate table +pins for the life of the process (see "Removing and replacing entries"). ## Level 1: Driver Handle -> Resource Handle (C++) @@ -33,6 +34,27 @@ Instances: `context_registry`, `stream_registry`, `event_registry`, `kernel_registry`, and, per `GraphBox`, one registry for its direct child graphs and one for its nodes. +### Removing and replacing entries + +More than one Box can exist for one raw handle, for example a plain `_ref` +Box and an owning one. An entry therefore records the address of the +element its handle points to, and `unregister_handle(key, resource)` erases +the entry only if `resource` matches. A Box destructor thus never erases the +entry of another, still-live Box registered under the same key. + +`insert_or_get(key, candidate, replace)` registers a new Box without blindly +overwriting a live entry; `replace(existing)` decides. Build the candidate +before the call and drop a losing candidate after it, never under the +registry's lock, because its deleter takes that lock. For the same reason, +`insert_or_get` releases a displaced live handle only after the unlock: another +thread may have dropped its own copy, leaving the last reference to that Box +inside the call. `context_registry` uses +this to keep one owning Box per live context (#3533): a Box that holds a +primary-context retain or the owning green-context handle replaces a plain +one, and nothing replaces an owning one. A primary context's retaining Box is +pinned for the life of the process (`pin_primary_context()` in `context.cpp`), +so all threads share it and its retain is never released. + ### Imports that wait for an in-flight release IPC imports use `ReleasingHandleRegistry`, a variant whose entry outlives its diff --git a/cuda_core/cuda/core/_cpp/rt/api.hpp b/cuda_core/cuda/core/_cpp/rt/api.hpp index 97355aea4a8d..de227e4b04c0 100644 --- a/cuda_core/cuda/core/_cpp/rt/api.hpp +++ b/cuda_core/cuda/core/_cpp/rt/api.hpp @@ -16,9 +16,19 @@ namespace cuda_core::rt { // Context handle functions // ============================================================================ -// Function to create a non-owning context handle (references existing context). +// Return a handle for an existing context: the registered handle if there is +// one. A primary context that is the calling thread's current context is +// retained and pinned for the life of the process (see get_primary_context). +// Any other context gets a handle that does not keep it alive. May call the +// driver and report a failure, which acquires the GIL: do not call it while +// holding a C++ lock. ContextHandle create_context_handle_ref(CUcontext ctx); +// As create_context_handle_ref, for a caller that knows that ctx is the calling +// thread's current context and that its device is `device`, so that neither is +// queried again. +ContextHandle create_current_context_handle_ref(CUcontext ctx, CUdevice device); + // Create a context handle for the CUcontext view of the provided green context. // The returned ContextHandle keeps the green context alive, but the CUcontext // view is non-owning and is not destroyed independently. @@ -35,12 +45,14 @@ GreenCtxHandle create_green_ctx_handle( // Create a non-owning green context handle. GreenCtxHandle create_green_ctx_handle_ref(CUgreenCtx ctx); -// Get handle to the primary context for a device (with thread-local caching) -// Returns empty handle on error (caller must check) +// Get handle to the primary context for a device. +// cuda.core retains each primary context at most once per process and never +// releases it. Returns empty handle on error (caller must check) ContextHandle get_primary_context(int device_id); -// Get handle to the current CUDA context -// Returns empty handle if no context is current (caller must check) +// Get handle to the current CUDA context, as create_context_handle_ref does; +// the same rules apply. Returns empty handle if no context is current (caller +// must check) ContextHandle get_current_context(); // Synchronize the provided context. Releases the GIL around the driver call. diff --git a/cuda_core/cuda/core/_cpp/rt/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index fd632991be7b..25dcca4e2f7a 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -8,8 +8,10 @@ #include "driver_api.hpp" #include "error.hpp" #include "internal.hpp" +#include #include #include +#include #include #include @@ -119,6 +121,7 @@ namespace { struct ContextBox { CUcontext resource; GreenCtxHandle h_green_ctx; + bool retains_primary = false; // Pinned primary context (see pin_primary_context). }; struct GreenCtxBox { @@ -135,35 +138,282 @@ get_box(const ContextHandle &h) noexcept // See REGISTRY_DESIGN.md (Level 1: Driver Handle -> Resource Handle) HandleRegistry context_registry; -// Create a context handle reference, with optional green context as source. +// A box keeps its context alive if it is a pinned primary context or holds the +// owning green-context handle. Reads only immutable box fields, so it is safe +// under the registry's mutex. +bool +owns_context(const ContextHandle &h) noexcept +{ + const ContextBox *b = get_box(h); + return b->retains_primary || b->h_green_ctx; +} + +// Registry replacement policy for contexts: an owning candidate replaces a +// non-owning entry, and nothing replaces an owning entry. This keeps one +// owning box per live context, and a lookup never trades it for a plain one. +auto +replace_if_upgrade(const ContextHandle &candidate) noexcept +{ + return [owning = owns_context(candidate)](const ContextHandle &existing) noexcept { + return owning && !owns_context(existing); + }; +} + +// Box ctx in a new handle, which the caller registers. The deleter erases the +// box's registry entry if it is still the registered one. It releases nothing: +// a plain box owns nothing, a green box releases its context through +// h_green_ctx, and a pinned primary box is never deleted (its retain is +// deliberately never released). ContextHandle -create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx) +make_context_handle(CUcontext ctx, GreenCtxHandle h_green_ctx, bool retains_primary) { - if (!ctx) { - return {}; - } - if (auto h = context_registry.lookup(ctx)) { - return h; - } // clang-format off auto box = std::shared_ptr( - new ContextBox{ctx, std::move(h_green_ctx)}, + new ContextBox{ctx, std::move(h_green_ctx), retains_primary}, [](const ContextBox *b) { - context_registry.unregister_handle(b->resource); + context_registry.unregister_handle(b->resource, &b->resource); delete b; } ); // clang-format on - ContextHandle h(box, &box->resource); - context_registry.register_handle(ctx, h); + return ContextHandle(box, &box->resource); +} + +// ---------------------------------------------------------------------------- +// Primary contexts +// +// cuda.core retains each device's primary context at most once per process and +// never gives that retain back, as the CUDA runtime does. The driver destroys +// a primary context when its last retain is released, so a context that +// cuda.core has handed out can only be destroyed by code outside cuda.core +// (cuDevicePrimaryCtxReset, cudaDeviceReset). +// +// The retain is held by one box per device, pinned in a process-wide table +// that is never freed: no thread's exit and no handle's release can drop the +// box's last reference, so its deleter never runs. +// +// The table is read without a lock. It is published as immutable snapshots: +// pinning a context, under primary_context_mutex, publishes a copy of the +// current snapshot with one more entry. Snapshots and the handles they point +// to are leaked, so a reader never sees freed memory, and other threads may +// still use them while the process exits. At most one snapshot is published +// per device. +// ---------------------------------------------------------------------------- + +struct PinnedPrimaryContexts { + std::vector slots; // indexed by device ordinal +}; + +std::mutex primary_context_mutex; // serializes pinning +std::atomic pinned_primary_contexts{nullptr}; + +// Return the pinned primary context of device ordinal idx, or an empty handle. +ContextHandle +find_pinned_primary_context(size_t idx) noexcept +{ + const PinnedPrimaryContexts *pinned = pinned_primary_contexts.load(std::memory_order_acquire); + if (pinned && idx < pinned->slots.size() && pinned->slots[idx]) { + return *pinned->slots[idx]; + } + return {}; +} + +// Publish h as the pinned primary context of device ordinal idx. The caller +// holds primary_context_mutex, so no other snapshot is published meanwhile. +void +publish_pinned_primary_context(size_t idx, const ContextHandle &h) +{ + // The previous store was made under the same mutex, so a relaxed load sees it. + const PinnedPrimaryContexts *current = pinned_primary_contexts.load(std::memory_order_relaxed); + // Both allocations are leaked on purpose (see above). + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) + auto *next = new PinnedPrimaryContexts{current ? current->slots : std::vector{}}; + if (idx >= next->slots.size()) { + next->slots.resize(idx + 1, nullptr); + } + next->slots[idx] = new ContextHandle(h); // NOLINT(cppcoreguidelines-owning-memory) + pinned_primary_contexts.store(next, std::memory_order_release); +} + +// Return the pinned primary context of device_id, pinning it first if needed. +// +// With expected == nullptr, retain the device's primary context (creating it +// if it is not active) and pin it. On failure, return an empty handle and +// store the status in *status. +// +// With expected != nullptr, pin and return the primary context only if it is +// active and is `expected`; otherwise return an empty handle. A primary +// context that is not active is not retained, because that would create it. If +// the active primary context is another one, the retain taken to learn its +// address is given back: the context was active without it, so that release +// cannot destroy a context that its other owners still hold. +ContextHandle +pin_primary_context(int device_id, CUcontext expected, CUresult *status) +{ + *status = CUDA_SUCCESS; + const auto idx = static_cast(device_id); + auto pinned_result = [expected](ContextHandle pinned) -> ContextHandle { + if (expected && as_cu(pinned) != expected) { + return {}; + } + return pinned; + }; + if (ContextHandle pinned = find_pinned_primary_context(idx)) { + return pinned_result(std::move(pinned)); + } + + // The GIL is the outermost lock, and filling the table acquires it: do both + // before the mutex is taken. The raw p_ calls below rely on the fill. + GILReleaseGuard gil; + if (!ensure_fn_table(FnTable::driver)) { + report_unavailable_fn(FnTable::driver, "cuDevicePrimaryCtxRetain"); + *status = CUDA_ERROR_NOT_INITIALIZED; + return {}; + } + + ContextHandle h; + bool release_probe = false; + { + std::scoped_lock lock(primary_context_mutex); + // Another thread may have pinned it since the check above. + if (ContextHandle pinned = find_pinned_primary_context(idx)) { + return pinned_result(std::move(pinned)); + } + if (expected) { + unsigned int flags = 0; + int active = 0; + *status = p_cuDevicePrimaryCtxGetState(device_id, &flags, &active); // raw: under primary_context_mutex + if (*status != CUDA_SUCCESS || !active) { + return {}; + } + } + CUcontext ctx = nullptr; + *status = p_cuDevicePrimaryCtxRetain(&ctx, device_id); // raw: under primary_context_mutex + if (*status != CUDA_SUCCESS) { + return {}; + } + if (expected && ctx != expected) { + release_probe = true; + } + else { + h = make_context_handle(ctx, {}, true); + publish_pinned_primary_context(idx, h); + } + } + if (release_probe) { + // Reports through Python on failure, so it runs after the unlock. + pw_cuDevicePrimaryCtxRelease(device_id); + return {}; + } + // The driver has just returned this address as the device's primary + // context, so a live entry under it is a plain box or a stale one: replace + // it. Registering after the unlock keeps a displaced box's deleter out of + // primary_context_mutex. A lookup that misses the registry in between finds + // the box in the table (see resolve_context_handle). + context_registry.insert_or_get(as_cu(h), h, [](const ContextHandle &) noexcept { return true; }); return h; } + +// A lookup falls back to a handle that holds no retain, and its callers do not +// check for an error, so each failure while adopting a primary context is +// reported. +constexpr const char *adopt_failure_detail = "failed while looking up the current context"; + +// ctx is the calling thread's current context, on `device`. If it is that +// device's primary context, pin it and return the pinned handle; otherwise +// return an empty handle. +ContextHandle +adopt_primary_context(CUcontext ctx, CUdevice device) +{ + CUresult status = CUDA_SUCCESS; + ContextHandle h = pin_primary_context(static_cast(device), ctx, &status); + if (status != CUDA_SUCCESS) { + report_cuda_error("cuDevicePrimaryCtxRetain", status, adopt_failure_detail); + } + return h; +} + +// ctx is the calling thread's current context: query its device and adopt it. +ContextHandle +adopt_current_context(CUcontext ctx) +{ + GILReleaseGuard gil; + CUdevice device = 0; + CUresult status = DRIVER_CALL(cuCtxGetDevice, &device); + if (status != CUDA_SUCCESS) { + report_cuda_error("cuCtxGetDevice", status, adopt_failure_detail); + return {}; + } + return adopt_primary_context(ctx, device); +} + +// Adopt ctx if it is the calling thread's current context. Only the current +// context is examined, because its device can be queried without switching +// contexts, which a lookup must not do. +ContextHandle +adopt_if_current(CUcontext ctx) +{ + GILReleaseGuard gil; + CUcontext current = nullptr; + CUresult status = DRIVER_CALL(cuCtxGetCurrent, ¤t); + if (status != CUDA_SUCCESS) { + report_cuda_error("cuCtxGetCurrent", status, adopt_failure_detail); + return {}; + } + if (current != ctx) { + return {}; + } + return adopt_current_context(ctx); +} + +// Return the handle for ctx, with an optional owning green context as source. +// +// adopt() returns the pinned handle if ctx is a primary context that cuda.core +// has not retained yet, for example one made current by another library, and +// an empty handle otherwise. It runs only for a plain lookup (no h_green_ctx) +// that finds no owning entry, so callers that know what is current pass what +// they know instead of querying the driver again. +template +ContextHandle +resolve_context_handle(CUcontext ctx, GreenCtxHandle h_green_ctx, Adopt &&adopt) +{ + if (!ctx) { + return {}; + } + ContextHandle registered = context_registry.lookup(ctx); + // An owning entry for ctx is either this green context's own box or a + // pinned primary context. A green context cannot share a live primary + // context's CUcontext, so returning it never drops a needed green owner. + if (registered && owns_context(registered)) { + return registered; + } + if (!h_green_ctx) { + // Pin a primary context, so that the handle keeps it alive like every + // other primary-context handle. + if (ContextHandle h = adopt()) { + return h; + } + if (registered) { + return registered; + } + } + ContextHandle candidate = make_context_handle(ctx, std::move(h_green_ctx), false); + // A losing candidate is dropped by the caller, outside the registry's lock; + // its deleter's ownership-checked erase is then a no-op. + return context_registry.insert_or_get(ctx, candidate, replace_if_upgrade(candidate)); +} } // namespace ContextHandle create_context_handle_ref(CUcontext ctx) { - return create_context_handle_ref(ctx, {}); + return resolve_context_handle(ctx, {}, [ctx] { return adopt_if_current(ctx); }); +} + +ContextHandle +create_current_context_handle_ref(CUcontext ctx, CUdevice device) +{ + return resolve_context_handle(ctx, {}, [ctx, device] { return adopt_primary_context(ctx, device); }); } ContextHandle @@ -178,7 +428,7 @@ create_context_handle_from_green_ctx(const GreenCtxHandle &h_green_ctx) return {}; } - return create_context_handle_ref(ctx, h_green_ctx); + return resolve_context_handle(ctx, h_green_ctx, [] { return ContextHandle{}; }); } GreenCtxHandle @@ -227,51 +477,15 @@ create_green_ctx_handle_ref(CUgreenCtx green_ctx) return GreenCtxHandle(box, &box->resource); } -// Thread-local cache of primary contexts indexed by device ID -static thread_local std::vector primary_context_cache; - ContextHandle get_primary_context(int device_id) { - // Check thread-local cache - if (static_cast(device_id) < primary_context_cache.size()) { - if (auto cached = primary_context_cache[device_id]) { - return cached; - } - } - - // Cache miss - acquire primary context from driver - GILReleaseGuard gil; - CUcontext ctx; - if (CUDA_SUCCESS != (err = DRIVER_CALL(cuDevicePrimaryCtxRetain, &ctx, device_id))) { - return {}; - } - - // clang-format off - auto box = std::shared_ptr( - new ContextBox{ctx, {}}, - [device_id](const ContextBox *b) { - context_registry.unregister_handle(b->resource); - // During interpreter shutdown, leave primary-context cleanup to - // process teardown. An unavailable table entry would need Python - // to report itself. - if (Py_IsInitialized() && !py_is_finalizing()) { - GILReleaseGuard gil; - DRIVER_CALL(cuDevicePrimaryCtxRelease, device_id); - } - delete b; - } - ); - // clang-format on - auto h = ContextHandle(box, &box->resource); - context_registry.register_handle(ctx, h); - - // Update cache - if (static_cast(device_id) >= primary_context_cache.size()) { - primary_context_cache.resize(device_id + 1); + // The common case: the context is pinned already. Leave the thread's last + // error untouched, as any other lookup that succeeds does. + if (ContextHandle h = find_pinned_primary_context(static_cast(device_id))) { + return h; } - primary_context_cache[device_id] = h; - return h; + return pin_primary_context(device_id, nullptr, &err); } ContextHandle @@ -285,7 +499,7 @@ get_current_context() if (!ctx) { return {}; // No current context (not an error) } - return create_context_handle_ref(ctx); + return resolve_context_handle(ctx, {}, [ctx] { return adopt_current_context(ctx); }); } } // namespace cuda_core::rt diff --git a/cuda_core/cuda/core/_cpp/rt/driver_api.hpp b/cuda_core/cuda/core/_cpp/rt/driver_api.hpp index 1d13cd016485..1fa95ccf0137 100644 --- a/cuda_core/cuda/core/_cpp/rt/driver_api.hpp +++ b/cuda_core/cuda/core/_cpp/rt/driver_api.hpp @@ -58,6 +58,7 @@ namespace cuda_core::rt { X(cuGetErrorString, 6000) \ /* Context */ \ X(cuDevicePrimaryCtxRetain, 7000) \ + X(cuDevicePrimaryCtxGetState, 7000) \ X(cuDevicePrimaryCtxRelease, 11000) \ X(cuCtxGetCurrent, 4000) \ X(cuCtxSetCurrent, 4000) \ diff --git a/cuda_core/cuda/core/_cpp/rt/event.cpp b/cuda_core/cuda/core/_cpp/rt/event.cpp index dde3a97049a1..01ac5b265b7a 100644 --- a/cuda_core/cuda/core/_cpp/rt/event.cpp +++ b/cuda_core/cuda/core/_cpp/rt/event.cpp @@ -98,7 +98,7 @@ create_event_handle( auto box = std::shared_ptr( new EventBox{event, timing_enabled, is_blocking_sync, ipc_enabled, device_id, h_ctx}, [](const EventBox *b) { - event_registry.unregister_handle(b->resource); + event_registry.unregister_handle(b->resource, &b->resource); GILReleaseGuard gil; pw_cuEventDestroy(b->resource); delete b; @@ -154,7 +154,7 @@ create_event_handle_ipc(const CUipcEventHandle &ipc_handle, bool is_blocking_syn auto box = std::shared_ptr( new EventBox{event, false, is_blocking_sync, true, -1, {}}, [](const EventBox *b) { - event_registry.unregister_handle(b->resource); + event_registry.unregister_handle(b->resource, &b->resource); GILReleaseGuard gil; pw_cuEventDestroy(b->resource); delete b; diff --git a/cuda_core/cuda/core/_cpp/rt/graph.cpp b/cuda_core/cuda/core/_cpp/rt/graph.cpp index 2495774c97f4..eedaaa09256d 100644 --- a/cuda_core/cuda/core/_cpp/rt/graph.cpp +++ b/cuda_core/cuda/core/_cpp/rt/graph.cpp @@ -686,13 +686,14 @@ static void retire_graph(GraphHierarchy &hierarchy, std::list::iterator graph) noexcept { for (auto &entry : graph->node_handles.drain()) { - if (GraphNodeHandle h_node = entry.second.lock()) { + if (GraphNodeHandle h_node = entry.second.handle.lock()) { get_box(h_node)->resource = nullptr; } } if (graph->resource) { if (graph->parent) { - graph->parent->children.unregister_handle({graph->resource, graph->owner_node}); + // Child graph handles alias &child.resource (create_child_graph_handle). + graph->parent->children.unregister_handle({graph->resource, graph->owner_node}, &graph->resource); } graph->resource = nullptr; } @@ -779,7 +780,7 @@ invalidate_graph_node(const GraphNodeHandle &h) noexcept return; } GraphBox *graph = get_box(node_box->h_graph); - graph->node_handles.unregister_handle(node); + graph->node_handles.unregister_handle(node, &node_box->resource); node_box->resource = nullptr; } diff --git a/cuda_core/cuda/core/_cpp/rt/internal.hpp b/cuda_core/cuda/core/_cpp/rt/internal.hpp index 2a0d9d7d9c64..0bc0c5439059 100644 --- a/cuda_core/cuda/core/_cpp/rt/internal.hpp +++ b/cuda_core/cuda/core/_cpp/rt/internal.hpp @@ -142,6 +142,7 @@ const WarnOnFailure pw_cuMipmappedArrayDestroy{"cuMip const WarnOnFailure pw_cuTexObjectDestroy{"cuTexObjectDestroy"}; const WarnOnFailure pw_cuSurfObjectDestroy{"cuSurfObjectDestroy"}; const WarnOnFailure pw_cuGreenCtxDestroy{"cuGreenCtxDestroy"}; +const WarnOnFailure pw_cuDevicePrimaryCtxRelease{"cuDevicePrimaryCtxRelease"}; const WarnOnFailure pw_cuMemPoolDestroy{"cuMemPoolDestroy"}; const WarnOnFailure pw_cuMemFreeHost{"cuMemFreeHost"}; const WarnOnFailure pw_cuMemRelease{"cuMemRelease"}; @@ -179,28 +180,72 @@ void enqueue_cleanup(void *item) noexcept; template > class HandleRegistry { public: - using MapType = std::unordered_map, Hash>; + using Element = typename Handle::element_type; + + // An entry keeps the element pointer next to the weak_ptr: a deleter's own + // weak_ptr has already expired, so ownership is checked by address. + struct Entry { + std::weak_ptr handle; + const Element *resource = nullptr; + }; + using MapType = std::unordered_map; void register_handle(const Key &key, const Handle &h) { std::scoped_lock lock(mutex_); - map_[key] = h; + map_[key] = Entry{h, h.get()}; } + // Erase key's entry only if it was registered by the handle that pointed + // to resource, so a dying handle cannot erase the entry of a live handle + // registered under the same key. A deleter erases before freeing its box, + // so no other handle can share the address while the entry is compared. void - unregister_handle(const Key &key) noexcept + unregister_handle(const Key &key, const Element *resource) noexcept { std::scoped_lock lock(mutex_); - map_.erase(key); + auto it = map_.find(key); + if (it != map_.end() && it->second.resource == resource) { + map_.erase(it); + } } + + // Register candidate under key unless a live entry should be kept, and + // return the handle to use: the live entry, or candidate. replace(existing) + // decides whether candidate displaces a live entry; an expired entry is + // always displaced. replace runs under the registry's mutex, so it must + // not call the driver or acquire the GIL. Build candidate before calling + // and drop a losing candidate afterwards, never under the mutex: a deleter + // that takes this mutex would deadlock. + template + Handle + insert_or_get(const Key &key, const Handle &candidate, Replace &&replace) + { + // Declared before the lock so that it is destroyed after the unlock. + // A displaced handle may hold the last reference to its box: another + // thread can drop its own copy while we hold this one. Its deleter + // takes this mutex, so releasing it under the lock would deadlock. + Handle existing; + std::scoped_lock lock(mutex_); + auto [it, inserted] = map_.try_emplace(key); + if (!inserted) { + existing = it->second.handle.lock(); + if (existing && !replace(existing)) { + return existing; + } + } + it->second = Entry{candidate, candidate.get()}; + return candidate; + } + Handle lookup(const Key &key) { std::scoped_lock lock(mutex_); auto it = map_.find(key); if (it != map_.end()) { - if (auto h = it->second.lock()) { + if (auto h = it->second.handle.lock()) { return h; } map_.erase(it); @@ -215,7 +260,7 @@ class HandleRegistry { std::scoped_lock lock(mutex_); auto it = map_.find(key); if (it != map_.end()) { - if (Handle h = it->second.lock()) { + if (Handle h = it->second.handle.lock()) { return h; } map_.erase(it); @@ -223,7 +268,7 @@ class HandleRegistry { Handle h = create(); if (h) { - map_[key] = h; + map_[key] = Entry{h, h.get()}; } return h; } @@ -297,6 +342,16 @@ class ReleasingHandleRegistry { return h; } + // Return the live handle registered under key, or an empty handle. Unlike + // get_or_create(), it never waits for a release in flight, so a caller that + // gets nothing goes on to get_or_create(). + Handle + find_live(const Key &key) + { + std::unique_lock lock(mutex_); + return find(lock, key).owner; + } + // Called by an owner's deleter after its last driver call on the resource: // erase key's entry if it belongs to the handle that pointed to resource, // and wake the importers waiting for it. diff --git a/cuda_core/cuda/core/_cpp/rt/memory.cpp b/cuda_core/cuda/core/_cpp/rt/memory.cpp index 395b60fd1079..12ae4305e819 100644 --- a/cuda_core/cuda/core/_cpp/rt/memory.cpp +++ b/cuda_core/cuda/core/_cpp/rt/memory.cpp @@ -497,12 +497,31 @@ deviceptr_import_ipc(const MemoryPoolHandle &h_pool, const void *export_data, co // on it while holding the GIL would deadlock with a holder that needs // the GIL back (#2840). GILReleaseGuard gil; + // A repeat import keeps the cached mapping's deallocation stream, so + // return it before one is resolved for this call: resolving may pin a + // primary context or report a failure for a stream that is never used. + if (DevicePtrHandle cached = ipc_ptr_cache.find_live(key)) { + return cached; + } // Allocate before taking the mutex: a failed allocation then cannot run // a deleter under it. The box owns nothing until it holds an import. auto box = std::shared_ptr(new DevicePtrBox{0, DeallocationStream{}}, DeleteIpcPtrBox{h_pool, key}); DevicePtrHandle h(box, &box->resource); + // Resolve the deallocation stream before the mutex is taken: for a + // default-stream token it looks up the current context, which may pin a + // primary context and report a failure (get_current_context). + // Only a fresh import uses it, so a failure is kept for that path. An + // import that was cached by a concurrent call since the lookup above + // still resolves it, and gets the cached mapping. May throw + // std::bad_alloc; nothing has been imported yet. + DeallocationStream ds; + const CUresult status_before = err; + const bool ds_ok = make_deallocation_stream(h_stream, ds); + const CUresult ds_status = err; + err = status_before; + // The factory runs under the cache's mutex, which makes lookup, import // and registration one step: two threads cannot import the same // descriptor twice. It therefore calls the driver through the raw p_ @@ -516,21 +535,16 @@ deviceptr_import_ipc(const MemoryPoolHandle &h_pool, const void *export_data, co (err = p_cuMemPoolImportPointer(&ptr, *h_pool, data))) { // raw: under the cache's mutex return {}; } - // Without a recorded deallocation stream the import is - // discarded before the mutex is released, or a concurrent - // import would share the mapping this free unmaps. - bool recorded = false; - try { - recorded = make_deallocation_stream(h_stream, box->deallocation); - } - catch (...) { - discarded = DiscardedIpcImport::discard(ptr, h_stream); - throw; - } - if (!recorded) { + // No deallocation stream could be recorded: discard the import + // before the mutex is released, or a concurrent import would + // share the mapping this free unmaps. + if (!ds_ok) { + err = ds_status; discarded = DiscardedIpcImport::discard(ptr, h_stream); return {}; } + // Moves two handles; no deleter runs under the mutex. + box->deallocation = std::move(ds); box->resource = ptr; return h; }); diff --git a/cuda_core/cuda/core/_cpp/rt/stream.cpp b/cuda_core/cuda/core/_cpp/rt/stream.cpp index b406857c54ab..c48ef7ac6159 100644 --- a/cuda_core/cuda/core/_cpp/rt/stream.cpp +++ b/cuda_core/cuda/core/_cpp/rt/stream.cpp @@ -95,7 +95,7 @@ create_stream_handle(const ContextHandle &h_ctx, unsigned int flags, int priorit auto box = std::shared_ptr( new StreamBox{stream, h_ctx}, [](const StreamBox *b) { - stream_registry.unregister_handle(b->resource); + stream_registry.unregister_handle(b->resource, &b->resource); GILReleaseGuard gil; pw_cuStreamDestroy(b->resource); delete b; @@ -117,7 +117,7 @@ create_stream_handle_ref(CUstream stream) auto box = std::shared_ptr( new StreamBox{stream, {}}, [](const StreamBox *b) { - stream_registry.unregister_handle(b->resource); + stream_registry.unregister_handle(b->resource, &b->resource); delete b; } ); diff --git a/cuda_core/cuda/core/_device.pyx b/cuda_core/cuda/core/_device.pyx index 5ce22959e985..e1293b51fb29 100644 --- a/cuda_core/cuda/core/_device.pyx +++ b/cuda_core/cuda/core/_device.pyx @@ -12,7 +12,7 @@ from libcpp.vector cimport vector import threading -from cuda.core._context cimport Context, Context_check_open +from cuda.core._context cimport Context, Context_check_open, Context_primary from cuda.core._context import ContextOptions from cuda.core._device_resources cimport DeviceResources, SMResource, WorkqueueResource from cuda.core._event cimport Event as cyEvent @@ -21,10 +21,9 @@ from cuda.core._memory._buffer cimport Buffer, MemoryResource from cuda.core._rt cimport ( ContextHandle, GreenCtxHandle, - create_context_handle_ref, + create_current_context_handle_ref, create_green_ctx_handle, context_synchronize, - get_primary_context, get_last_error, as_cu, ) @@ -1292,6 +1291,7 @@ class Device: cdef cydriver.CUcontext prev_ctx, curr_ctx cdef cydriver.CUdevice prev_dev cdef Context prev_owned = None + cdef Context primary if ctx is not None: Context_check_open(ctx) @@ -1309,6 +1309,11 @@ class Device: HANDLE_RETURN(cydriver.cuCtxGetCurrent(&prev_ctx)) if prev_ctx != NULL: HANDLE_RETURN(cydriver.cuCtxGetDevice(&prev_dev)) + # Resolve the previous context while it is still current: + # only then is a primary context that cuda.core has not + # retained yet pinned, so that the returned Context keeps + # it alive. + h_context = create_current_context_handle_ref(prev_ctx, prev_dev) # cuCtxSetCurrent replaces the top of the thread's context stack # in one driver call (or binds ctx when nothing is current), so # a failure leaves the previous context current instead of @@ -1318,22 +1323,20 @@ class Device: self._has_inited = True self._context = ctx # Store owning context reference if prev_ctx != NULL: - if prev_owned is not None and as_cu(prev_owned._h_context) == prev_ctx: + # Reuse this device's Context object only if it holds the handle + # just resolved. Comparing CUcontext addresses is not enough: the + # driver reuses the address of a destroyed context, and a stale + # object for it would hide the live context's owning handle. + if prev_owned is not None and prev_owned._h_context.get() == h_context.get(): return prev_owned - return Context._from_handle( - Context, create_context_handle_ref(prev_ctx), prev_dev) + return Context._from_handle(Context, h_context, prev_dev) else: # use primary ctx - h_context = get_primary_context(self._device_id) - if h_context.get() == NULL: - HANDLE_RETURN(get_last_error()) - raise RuntimeError( - f"Failed to retain the primary context for device {self._device_id}" - ) + primary = Context_primary(self._device_id) with nogil: - HANDLE_RETURN(cydriver.cuCtxSetCurrent(as_cu(h_context))) + HANDLE_RETURN(cydriver.cuCtxSetCurrent(as_cu(primary._h_context))) self._has_inited = True - self._context = Context._from_handle(Context, h_context, self._device_id) # Store owning context + self._context = primary # Store owning context def create_context(self, options: ContextOptions | None = None) -> Context: """Create a new :obj:`~_context.Context` object. diff --git a/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx b/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx index e54387976646..9c6a207e0df9 100644 --- a/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx @@ -7,14 +7,11 @@ from __future__ import annotations from libc.stdint cimport uintptr_t from cuda.bindings cimport cydriver -from cuda.core._context cimport Context +from cuda.core._context cimport Context, Context_primary from cuda.core._memory._buffer cimport Buffer, MemoryResource from cuda.core._rt cimport ( - ContextHandle, create_context_bound_legacy_stream, deviceptr_alloc_raw, - get_last_error, - get_primary_context, ) from cuda.core._stream cimport Stream, Stream_accept, Stream_is_default_token from cuda.core._utils.cuda_utils cimport HANDLE_RETURN @@ -41,13 +38,8 @@ class _SynchronousMemoryResource(MemoryResource): self._context = context def _resolve_context(self) -> Context: - cdef ContextHandle h_context if self._context is None: - h_context = get_primary_context(self._device_id) - if not h_context: - HANDLE_RETURN(get_last_error()) - self._context = Context._from_handle( - Context, h_context, self._device_id) + self._context = Context_primary(self._device_id) return self._context def allocate( diff --git a/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx b/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx index db6bae19fb56..43b72e324a51 100644 --- a/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx @@ -10,6 +10,7 @@ from libcpp.vector cimport vector cimport cpython from cuda.bindings cimport cydriver +from cuda.core._context cimport Context_get_primary_handle from cuda.core._memory._buffer cimport ( Buffer, Buffer_check_open, @@ -40,7 +41,6 @@ from cuda.core._rt cimport ( deallocation_stream, deviceptr_create_vmm, get_last_error, - get_primary_context, import_mem_allocation_handle, mem_allocation_is_imported, mem_allocation_size, @@ -656,10 +656,9 @@ cdef class VirtualMemoryResource(MemoryResource): # Bind the legacy default-stream token to the device's primary # context so the free is ordered correctly no matter what is current # then, and so allocate() never depends on a current context. - # get_primary_context keeps its own cache; nothing is cached here. - h_ctx = get_primary_context(self.device.device_id) - if not h_ctx: - _raise_last_error() + # The primary context is pinned for the life of the process; + # nothing is cached here. + Context_get_primary_handle(self.device.device_id, &h_ctx) h = create_context_bound_legacy_stream(h_ctx) if not h: _raise_last_error() diff --git a/cuda_core/cuda/core/_rt.pxd b/cuda_core/cuda/core/_rt.pxd index b67c66db9b3d..2566c75f42f6 100644 --- a/cuda_core/cuda/core/_rt.pxd +++ b/cuda_core/cuda/core/_rt.pxd @@ -216,6 +216,8 @@ cdef void clear_last_error_detail() noexcept nogil # Context handles cdef ContextHandle create_context_handle_ref(cydriver.CUcontext ctx) except+ nogil +cdef ContextHandle create_current_context_handle_ref( + cydriver.CUcontext ctx, cydriver.CUdevice device) except+ nogil cdef ContextHandle create_context_handle_from_green_ctx(const GreenCtxHandle& h_green_ctx) except+ nogil cdef GreenCtxHandle get_context_green_ctx(const ContextHandle& h) noexcept nogil cdef GreenCtxHandle create_green_ctx_handle( diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index 6511643edb52..b8b9f892e5e2 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -71,6 +71,8 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": # Context handles ContextHandle create_context_handle_ref "cuda_core::rt::create_context_handle_ref" ( cydriver.CUcontext ctx) except+ nogil + ContextHandle create_current_context_handle_ref "cuda_core::rt::create_current_context_handle_ref" ( + cydriver.CUcontext ctx, cydriver.CUdevice device) except+ nogil ContextHandle create_context_handle_from_green_ctx "cuda_core::rt::create_context_handle_from_green_ctx" ( const GreenCtxHandle& h_green_ctx) except+ nogil GreenCtxHandle get_context_green_ctx "cuda_core::rt::get_context_green_ctx" ( diff --git a/cuda_core/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index 1be489a39591..a590333782f9 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -59,3 +59,34 @@ Fixes and enhancements later driver; with a CUDA 12 build or an older driver, imports behave as before. (`#3502 `__) + +- ``cuda.core`` again retains each device's primary context at most once per + process and never releases it, as the CUDA runtime does and as + ``cuda.core`` did before 0.6.0. Since 0.6.0 it released its retains when + the last object holding them was released, so the driver could destroy a + primary context that the application still used. In particular, a + :class:`Context`, :class:`Stream` or :class:`Event` could fail with + ``CUDA_ERROR_CONTEXT_IS_DESTROYED`` after other threads that used the same + device exited: each thread that called :meth:`Device.set_current` retained + the primary context separately, and a thread's exit could leave later + lookups, such as :meth:`Stream.from_handle` or recording an event on + :attr:`Device.default_stream`, with a :class:`Context` that held no retain. + (`#3533 `__) + +- A :class:`Context` that ``cuda.core`` resolves for the calling thread's + current context now also keeps a primary context alive that another + library made current, for example the context of + ``Stream.from_handle(...)`` for a default stream, or the previous context + returned by :meth:`Device.set_current`. A :class:`Context` resolved for a + context that is not current at the time, for example the context of + another context's stream or a graph node's update context, still holds no + retain if ``cuda.core`` has not retained that primary context, and stays + valid only as long as the context's owner keeps it alive. + (`#3533 `__) + +- :meth:`Device.create_context` no longer returns a context with + ``is_green == False`` that is already destroyed when the driver reuses the + address of an earlier context for which the application still holds a + :class:`Context` that ``cuda.core`` did not create, for example the + previous context returned by :meth:`Device.set_current`. + (`#3533 `__) diff --git a/cuda_core/tests/helpers/contexts.py b/cuda_core/tests/helpers/contexts.py index d1e73de926a3..625f561da294 100644 --- a/cuda_core/tests/helpers/contexts.py +++ b/cuda_core/tests/helpers/contexts.py @@ -12,6 +12,7 @@ "assert_no_cuda_warning", "current_context_handle", "no_current_context", + "primary_context_active", "use_context", ] @@ -36,6 +37,12 @@ def current_context_handle(): return int(handle_return(driver.cuCtxGetCurrent())) +def primary_context_active(device_id): + """Return whether the primary context of ``device_id`` is active (retained).""" + _, active = handle_return(driver.cuDevicePrimaryCtxGetState(device_id)) + return bool(active) + + def _assert_event_record_rejected_from_ambient_context(event): """Assert that recording ``event`` into a stream from the ambient context fails. diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index 53182520e242..4800fb3b1bc8 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -1,10 +1,19 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import gc +import threading +import time + import pytest +from helpers.child_processes import child_timeout_sec, run_child +from helpers.contexts import assert_no_cuda_warning, primary_context_active +from helpers.misc import run_in_threads import cuda.core -from cuda.core import Device +from cuda.bindings import driver +from cuda.core import Device, Stream +from cuda.core._utils.cuda_utils import handle_return def test_context_init_disabled(): @@ -89,3 +98,86 @@ def test_context_dict_key(init_cuda): ctx_cache = {context: "context_data"} assert ctx_cache[context] == "context_data" + + +# ============================================================================ +# Primary-context lifetime (#3533) +# ============================================================================ + +# Each test runs in a fresh child process, so nothing else holds a retain of the +# primary context: the pytest process does, through fixtures, which would hide +# a released or leaked retain. + + +# Several threads retain the primary context concurrently, after which every +# thread exits and every Context is dropped. cuda.core keeps exactly one retain +# of the primary context for the rest of the process: the context stays active, +# and releasing one retain from outside cuda.core leaves no retain behind. This +# covers the cause of #3533: on releasing code, the primary context is inactive +# here. +def _concurrent_primary_retains_child(device_id): + num_threads = 8 + barrier = threading.Barrier(num_threads) + contexts = [] + + def worker(): + dev = Device(device_id) + barrier.wait() + dev.set_current() + contexts.append(dev.context) + + with assert_no_cuda_warning(): + run_in_threads([worker] * num_threads, barrier=barrier, timeout=child_timeout_sec()) + assert len(contexts) == num_threads + assert len({int(ctx.handle) for ctx in contexts}) == 1 + contexts.clear() + gc.collect() + # Thread.join() can return before a thread's C++ thread_local + # destructors run, and they cannot be observed, so wait a fixed second. + # A release at thread exit would make the next check fail. + time.sleep(1.0) + assert primary_context_active(device_id), "cuda.core released its primary-context retain" + + # This process has no other retain of the primary context, so one + # release must leave it inactive: cuda.core held exactly one retain. + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + assert not primary_context_active(device_id), "cuda.core holds more than one primary-context retain" + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_concurrent_set_current_keeps_one_primary_retain(init_cuda): + """Concurrent Device.set_current() calls take one primary-context retain, which cuda.core never releases.""" + run_child(_concurrent_primary_retains_child, init_cuda.device_id) + + +# Another owner (here cuda.bindings, standing in for another library) retains the +# primary context and makes it current, and cuda.core has not retained it. An +# Event recorded on the legacy default stream and that stream's Context, both +# resolved for the current context, must keep it alive once that owner releases +# its retain. Both resolve through the same lookup; the first one pins the +# primary context, and the second finds it registered. +def _foreign_primary_context_child(device_id): + handle_return(driver.cuInit(0)) + with assert_no_cuda_warning(): + assert not primary_context_active(device_id) + primary = handle_return(driver.cuDevicePrimaryCtxRetain(device_id)) + handle_return(driver.cuCtxSetCurrent(primary)) + legacy = Stream.from_handle(int(driver.CU_STREAM_LEGACY)) + event = legacy.record() + ctx = legacy.context + handle_return(driver.cuCtxSetCurrent(None)) + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + + assert primary_context_active(device_id), ( + "primary context destroyed while a cuda.core object still refers to it" + ) + event.sync() + dev = Device(device_id) + dev.set_current(ctx) + dev.create_stream().sync() + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_lookup_retains_foreign_primary_context(init_cuda): + """A Context resolved for a primary context that another owner made current keeps it alive.""" + run_child(_foreign_primary_context_child, init_cuda.device_id) diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index f95037077012..9ba6bdf4dcb1 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -4,10 +4,18 @@ import numpy as np import pytest -from helpers.contexts import assert_device_operations_use_bound_context, current_context_handle, use_context +from helpers.child_processes import run_child +from helpers.contexts import ( + assert_device_operations_use_bound_context, + assert_no_cuda_warning, + current_context_handle, + primary_context_active, + use_context, +) from cuda.core import ( ContextOptions, + Device, DeviceResources, LaunchConfig, LegacyPinnedMemoryResource, @@ -15,6 +23,7 @@ ProgramOptions, SMResource, SMResourceOptions, + Stream, WorkqueueResource, WorkqueueResourceOptions, launch, @@ -256,6 +265,171 @@ def test_set_current_rejects_closed_context(init_cuda, sm_resource): init_cuda.set_current(ctx) +@pytest.mark.agent_authored(model="claude-opus-5-5") +def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): + """create_context() keeps its green context alive when a plain Context for + a destroyed context at the same CUcontext address is still registered (#3533).""" + dev = init_cuda + primary = dev.context + groups, _ = sm_resource.split(SMResourceOptions(count=None)) + opts = ContextOptions(resources=[groups[0]]) + res = handle_return(driver.cuDeviceGetDevResource(dev.device_id, driver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM)) + desc = handle_return(driver.cuDevResourceGenerateDesc([res], 1)) + flags = driver.CUgreenCtxCreate_flags.CU_GREEN_CTX_DEFAULT_STREAM + + # The stale plain entry must belong to a context that cuda.core did not + # create, then destroyed, and whose CUcontext address the driver reuses for + # the next green context. Retry until the address is reused. + for _ in range(20): + foreign = handle_return(driver.cuGreenCtxCreate(desc, dev.device_id, flags)) + try: + handle_return(driver.cuCtxSetCurrent(handle_return(driver.cuCtxFromGreenCtx(foreign)))) + # cuda.core did not create this context, so set_current() returns a + # plain, non-owning Context for it and registers it. + stale = dev.set_current(primary) + except BaseException as exc: + # Do not leave the foreign context current once it is destroyed. Run + # both rollback calls, and let the original error propagate with each + # rollback failure noted on it. + rollback = ( + ("cuCtxSetCurrent", driver.cuCtxSetCurrent(primary.handle)), + ("cuGreenCtxDestroy", driver.cuGreenCtxDestroy(foreign)), + ) + for name, (err,) in rollback: + if err != driver.CUresult.CUDA_SUCCESS: + exc.add_note(f"rollback: {name} failed with {err.name}") + raise + handle_return(driver.cuGreenCtxDestroy(foreign)) + assert not stale.is_green + green = dev.create_context(opts) + if int(green.handle) == int(stale.handle): + break + green.close() + else: + pytest.skip("driver did not reuse the destroyed context's CUcontext address") + + # Do not compare green with stale: Context equality compares raw CUcontext + # values, so they are equal with or without the fix. Query the SM resource + # to show the context is alive: unlike a stream, that works on driver 12.4, + # which the sm_resource fixture admits. + try: + assert green.is_green + assert green.resources.sm.sm_count == groups[0].sm_count + finally: + green.close() + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_set_current_returns_live_context_after_address_reuse(init_cuda, sm_resource): + """set_current() returns the live green context, not the Device's stale + Context for a destroyed context at the same CUcontext address.""" + dev = init_cuda + primary = dev.context + groups, _ = sm_resource.split(SMResourceOptions(count=None)) + opts = ContextOptions(resources=[groups[0]]) + res = handle_return(driver.cuDeviceGetDevResource(dev.device_id, driver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM)) + desc = handle_return(driver.cuDevResourceGenerateDesc([res], 1)) + flags = driver.CUgreenCtxCreate_flags.CU_GREEN_CTX_DEFAULT_STREAM + + # Make the Device remember a plain Context for a context that cuda.core did + # not create, destroy that context, and retry until the driver reuses its + # CUcontext address for a green context that cuda.core owns. + green = None + try: + for _ in range(20): + foreign = handle_return(driver.cuGreenCtxCreate(desc, dev.device_id, flags)) + try: + handle_return(driver.cuCtxSetCurrent(handle_return(driver.cuCtxFromGreenCtx(foreign)))) + stale = dev.set_current(primary) + dev.set_current(stale) # the Device now remembers stale + finally: + # Behind the Device's back, so that it keeps remembering stale. + handle_return(driver.cuCtxSetCurrent(primary.handle)) + handle_return(driver.cuGreenCtxDestroy(foreign)) + assert not stale.is_green + green = dev.create_context(opts) + if int(green.handle) == int(stale.handle): + break + green.close() + green = None + else: + pytest.skip("driver did not reuse the destroyed context's CUcontext address") + + handle_return(driver.cuCtxSetCurrent(green.handle)) + previous = dev.set_current(primary) + # Context equality compares raw CUcontext values, so compare identity + # and ownership instead. + assert previous is not stale + assert previous.is_green + finally: + # A skip or a failure above leaves the Device remembering stale, which + # the init_cuda teardown would then synchronize: rebind it. + dev.set_current(primary) + if green is not None: + green.close() + + +# The driver holds a retain of the primary context while any green context of +# the device exists. The tests below therefore check the primary context's state +# only after their green contexts are destroyed, and run in a fresh child +# process, because the pytest process already retains the primary context. + + +# Another owner (here cuda.bindings, standing in for another library) retains the +# primary context and makes it current, and cuda.core has not retained it. +# Device.set_current(green) then returns the previous context, which must keep +# the primary context alive once that owner releases its retain. +def _set_current_returns_foreign_primary_child(device_id): + handle_return(driver.cuInit(0)) + dev = Device(device_id) + with assert_no_cuda_warning(): + groups, _ = dev.resources.sm.split(SMResourceOptions(count=None)) + green = dev.create_context(ContextOptions(resources=[groups[0]])) + + primary = handle_return(driver.cuDevicePrimaryCtxRetain(device_id)) + handle_return(driver.cuCtxSetCurrent(primary)) + previous = dev.set_current(green) + assert not previous.is_green + assert int(previous.handle) == int(primary) + + dev.set_current(previous) + green.close() + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + assert primary_context_active(device_id), "primary context destroyed while the previous Context is held" + dev.create_stream().sync() + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_set_current_previous_context_retains_foreign_primary(init_cuda, green_ctx): + """The previous Context returned by Device.set_current(green) keeps a foreign primary context alive.""" + # green_ctx skips the test where green contexts cannot be created. + run_child(_set_current_returns_foreign_primary_child, init_cuda.device_id) + + +# A plain lookup of a context that is current but is not a primary context must +# not keep a retain of the device's primary context. +def _lookup_green_does_not_retain_primary_child(device_id): + handle_return(driver.cuInit(0)) + with assert_no_cuda_warning(): + res = handle_return(driver.cuDeviceGetDevResource(device_id, driver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM)) + desc = handle_return(driver.cuDevResourceGenerateDesc([res], 1)) + flags = driver.CUgreenCtxCreate_flags.CU_GREEN_CTX_DEFAULT_STREAM + foreign = handle_return(driver.cuGreenCtxCreate(desc, device_id, flags)) + handle_return(driver.cuCtxSetCurrent(handle_return(driver.cuCtxFromGreenCtx(foreign)))) + ctx = Stream.from_handle(int(driver.CU_STREAM_LEGACY)).context + assert not ctx.is_green + handle_return(driver.cuCtxSetCurrent(None)) + del ctx + handle_return(driver.cuGreenCtxDestroy(foreign)) + assert not primary_context_active(device_id), "a lookup of a green context kept a primary-context retain" + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_green_context_lookup_does_not_retain_primary(init_cuda, green_ctx): + """Looking up a current green context leaves no primary-context retain behind.""" + run_child(_lookup_green_does_not_retain_primary_child, init_cuda.device_id) + + # --------------------------------------------------------------------------- # SM resource query # --------------------------------------------------------------------------- diff --git a/cuda_core/tests/test_rt_layout.py b/cuda_core/tests/test_rt_layout.py index 29f6fc59da71..2a5d7861b122 100644 --- a/cuda_core/tests/test_rt_layout.py +++ b/cuda_core/tests/test_rt_layout.py @@ -138,8 +138,9 @@ def test_driver_function_table_matches_the_cuda_bindings_loader(): def test_driver_calls_go_through_the_table(): """Every driver call uses DRIVER_CALL or a pw_ wrapper, which resolves the table on first use and never dereferences null. The only raw p_ calls are - the table's own machinery and the sites under the IPC pointer cache's mutex. Those sites - resolve the table before the lock and carry the `// raw:` mark.""" + the table's own machinery and the sites under the IPC pointer cache's mutex + and the primary-context table's mutex. Those sites resolve the table before + the lock and carry the `// raw:` mark.""" machinery = {"driver_api.hpp", "driver_api.cpp", "py_driver_fns.cpp", "internal.hpp"} raw_call = re.compile(r"\bp_(cu|nv)\w+\b") # calls and null checks alike offenders = [] @@ -156,7 +157,7 @@ def test_driver_calls_go_through_the_table(): for number, line in enumerate(read(path).splitlines(), 1) if "// raw:" in line ] - assert {name.split(":")[0] for name in marked} == {"memory.cpp"}, marked + assert {name.split(":")[0] for name in marked} == {"context.cpp", "memory.cpp"}, marked @pytest.mark.agent_authored(model="claude-fable-5-1")