diff --git a/cuda_core/cuda/core/_cpp/rt/DESIGN.md b/cuda_core/cuda/core/_cpp/rt/DESIGN.md index 2341aab388a2..22e3b907c825 100644 --- a/cuda_core/cuda/core/_cpp/rt/DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/DESIGN.md @@ -432,6 +432,7 @@ exactly one of these; none is ever dropped. | Cython, inside an `except` block whose rollback failed | `attach_rollback_failure(op, status, detail)` | Adds a note to the exception being handled. Reports instead if nothing is being handled. | | C++, a deleter or deferred cleanup | A `pw_*` wrapper, or `report_cuda_error()` / `report_message()` | Emits `CUDAWarning`. Never raises. | | Cython or Python, a `__dealloc__` or destructor-path callback | `warnings.warn(msg, CUDAWarning, stacklevel=2)` | Same. | +| C++, a deleter that can run during native thread exit (a `thread_local` destructor) | Call the driver with `DRIVER_CALL`, and on failure hand a preallocated `DeferredCleanupItem` that reports to the deferred-cleanup queue | Warning hooks must not run during thread teardown: on Windows the loader lock is held, and a hook that starts a thread deadlocks. The report is delivered from the main thread. The primary context's deleter does this when `primary_context_cache_closed` is set. | | A CUDA user-object destructor callback | Nothing that needs the GIL. Hand the work to the deferred-cleanup queue with `Py_AddPendingCall` | CUDA forbids driver calls there, and acquiring the GIL there can deadlock with a GIL holder blocked in a driver call. GIL-free C API that only schedules work is fine. | ### `p_` versus `pw_` diff --git a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md index 8fb71e13a9f1..2a9aa8ebf751 100644 --- a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md @@ -33,6 +33,26 @@ 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. `get_primary_context()` therefore +shares one retaining Box per primary context across all threads. + ### 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/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index fd632991be7b..30175eced0cc 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -116,9 +116,29 @@ context_get_device(const ContextHandle &h_context, CUdevice *device) noexcept // ============================================================================ namespace { +// A release failure that could not be reported where it happened. The +// deferred-cleanup queue destroys it on Python's main thread, and its +// destructor reports the failure there. +struct DeferredCudaReport final : DeferredCleanupItem { + char operation[kOperationNameSize] = {}; + CUresult status = CUDA_SUCCESS; + + ~DeferredCudaReport() noexcept override + { + if (status != CUDA_SUCCESS) { + report_cuda_error(operation, status); + } + } +}; + struct ContextBox { CUcontext resource; GreenCtxHandle h_green_ctx; + bool retains_primary = false; // Owns one cuDevicePrimaryCtxRetain. + // Allocated with a retaining box, so that its deleter never allocates. The + // deleter hands it to the deferred-cleanup queue when it must not report + // a failed release itself. Mutable: the deleter sees a const box. + mutable std::unique_ptr deferred_release; }; struct GreenCtxBox { @@ -135,6 +155,27 @@ get_box(const ContextHandle &h) noexcept // See REGISTRY_DESIGN.md (Level 1: Driver Handle -> Resource Handle) HandleRegistry context_registry; +// A box keeps its context alive if it holds a primary-context retain or 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); + }; +} + // Create a context handle reference, with optional green context as source. ContextHandle create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx) @@ -143,20 +184,26 @@ create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx) return {}; } if (auto h = context_registry.lookup(ctx)) { - return h; + // An owning entry for ctx is either this green context's own box or a + // live primary context. A green context cannot share a live primary + // context's CUcontext, so returning it never drops a needed green owner. + if (!h_green_ctx || owns_context(h)) { + return h; + } } // clang-format off auto box = std::shared_ptr( new ContextBox{ctx, std::move(h_green_ctx)}, [](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 h; + ContextHandle candidate(box, &box->resource); + // 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 @@ -227,15 +274,44 @@ 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; +namespace { +// Set when the calling thread's primary-context cache is torn down. A plain +// bool needs no destructor, so it stays readable for the whole thread exit. +thread_local bool primary_context_cache_closed = false; + +// Thread-local cache of primary contexts indexed by device ID. A fast path in +// front of the registry: every thread caches the same process-wide box. +struct PrimaryContextCache { + std::vector entries; + + PrimaryContextCache() = default; + PrimaryContextCache(const PrimaryContextCache &) = delete; + PrimaryContextCache &operator=(const PrimaryContextCache &) = delete; + + // Releasing the last entry can run a CUDAWarning hook on this thread, and + // the hook may call get_primary_context(). Close the cache first and drop + // the entries from a local, so such a call bypasses the cache instead of + // reading one that is being destroyed. + ~PrimaryContextCache() + { + primary_context_cache_closed = true; + std::vector doomed; + doomed.swap(entries); + } +}; + +thread_local PrimaryContextCache primary_context_cache; +} // namespace ContextHandle get_primary_context(int device_id) { + const bool use_cache = !primary_context_cache_closed; + auto idx = static_cast(device_id); + // Check thread-local cache - if (static_cast(device_id) < primary_context_cache.size()) { - if (auto cached = primary_context_cache[device_id]) { + if (use_cache && idx < primary_context_cache.entries.size()) { + if (auto cached = primary_context_cache.entries[idx]) { return cached; } } @@ -249,28 +325,56 @@ get_primary_context(int device_id) // clang-format off auto box = std::shared_ptr( - new ContextBox{ctx, {}}, + new ContextBox{ctx, {}, true, std::make_unique()}, [device_id](const ContextBox *b) { - context_registry.unregister_handle(b->resource); + context_registry.unregister_handle(b->resource, &b->resource); // During interpreter shutdown, leave primary-context cleanup to - // process teardown. An unavailable table entry would need Python - // to report itself. + // process teardown. Reporting a failure needs Python too. if (Py_IsInitialized() && !py_is_finalizing()) { GILReleaseGuard gil; - DRIVER_CALL(cuDevicePrimaryCtxRelease, device_id); + if (!primary_context_cache_closed) { + pw_cuDevicePrimaryCtxRelease(device_id); + } + else { + // This thread's cache is being destroyed, so the thread is + // exiting. Native thread teardown must not run Python: a + // warning hook that starts a thread would wait for a + // thread that needs the loader lock this one holds on + // Windows. Report the failure from the main thread. + const CUresult status = DRIVER_CALL(cuDevicePrimaryCtxRelease, device_id); + if (status != CUDA_SUCCESS && status != CUDA_ERROR_DEINITIALIZED) { + DeferredCudaReport *report = b->deferred_release.release(); + report->status = status; + format_operation(report->operation, sizeof(report->operation), "cuDevicePrimaryCtxRelease", device_id); + enqueue_cleanup(static_cast(report)); + } + } } 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); + ContextHandle candidate(box, &box->resource); + // Keep one retaining box per primary context per process. If another + // thread's box is live, use it, and dropping our candidate releases the + // extra retain taken above; the live box still holds its own retain, so the + // driver's count never reaches zero. This runs with the GIL released and + // after insert_or_get has released the registry's lock, so the deleter may + // report through a pw_ wrapper. + ContextHandle h = context_registry.insert_or_get(ctx, candidate, replace_if_upgrade(candidate)); + + // Update the cache before dropping a losing candidate. Dropping it releases + // its extra retain, and a failure report can run a hook that calls + // get_primary_context() again; that call must find the cache entry instead + // of retaining and releasing once more. + if (use_cache) { + if (idx >= primary_context_cache.entries.size()) { + primary_context_cache.entries.resize(idx + 1); + } + primary_context_cache.entries[idx] = h; } - primary_context_cache[device_id] = h; + candidate.reset(); + box.reset(); return h; } 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..b30b0ea4fab3 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_); + 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_); - map_.erase(key); + 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; } 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/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index 1be489a39591..4998ad503cc9 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,29 @@ Fixes and enhancements later driver; with a CUDA 12 build or an older driver, imports behave as before. (`#3502 `__) + +- A :class:`Context`, :class:`Stream` or :class:`Event` no longer fails with + ``CUDA_ERROR_CONTEXT_IS_DESTROYED`` after other threads that used the same + device exit. 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. Once the last retaining thread exited, the driver destroyed the + primary context while the application still used it. All threads now + share one retain per primary context, which ``cuda.core`` releases when + the last object holding it is released. A :class:`Context` obtained for a + context that ``cuda.core`` had not retained at that time, for example one + made current by another library, still holds no retain 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 `__) + +- ``cuDevicePrimaryCtxRelease`` failures are now reported as a + :class:`CUDAWarning` instead of being ignored. + (`#3533 `__) diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index 53182520e242..73bba507cabe 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -1,10 +1,21 @@ # 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 warnings +from concurrent.futures import ThreadPoolExecutor + import pytest +from helpers.child_processes import child_timeout_sec, run_child +from helpers.contexts import assert_no_cuda_warning +from helpers.misc import run_in_threads import cuda.core -from cuda.core import Device +from cuda.bindings import driver +from cuda.core import CUDAWarning, Device, Stream +from cuda.core._utils.cuda_utils import handle_return def test_context_init_disabled(): @@ -89,3 +100,176 @@ def test_context_dict_key(init_cuda): ctx_cache = {context: "context_data"} assert ctx_cache[context] == "context_data" + + +# ============================================================================ +# Primary-context lifetime across threads (#3533) +# ============================================================================ + +# Thread A retains the primary context, then thread B retains it too and exits. +# Thread A then resolves a Context through the context registry (``lookup``), +# and the main thread uses that object (``use``) once both threads are gone. +# 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 the bug. +# +# Thread.join() can return before a thread's C++ thread_local destructors run, +# and they cannot be observed, so the child waits a fixed second after each +# join. With the fix, the test passes regardless of that timing. Without it, +# the test fails only if the destructors run within the wait, so a pass on +# unfixed code is not evidence that the bug is gone. + + +def _primary_active(device_id): + _, active = handle_return(driver.cuDevicePrimaryCtxGetState(device_id)) + return bool(active) + + +def _lookup_foreign_stream_context(dev): + return Stream.from_handle(int(driver.CU_STREAM_LEGACY)).context + + +def _use_context(dev, ctx): + dev.set_current(ctx) + dev.create_stream().sync() + + +def _lookup_default_stream_event(dev): + return dev.default_stream.record() + + +def _use_event(dev, event): + event.sync() + + +def _primary_context_across_threads_child(device_id, lookup, use): + def retain(): + Device(device_id).set_current() + + # A failed primary-context release is reported as a CUDAWarning, which a + # warning filter cannot turn into a failure here (see + # assert_no_cuda_warning), so the block asserts that none was issued. + with assert_no_cuda_warning(): + # Each executor runs its work on one thread, whose exit ends the ``with`` + # block, and result() re-raises any error from that thread. + with ThreadPoolExecutor(max_workers=1) as thread_a: + thread_a.submit(retain).result() + # B must retain the primary context after A: if B registered first + # and exited, A would register its own retain and hide the bug. + with ThreadPoolExecutor(max_workers=1) as thread_b: + thread_b.submit(retain).result() + time.sleep(1.0) + obj = thread_a.submit(lambda: lookup(Device(device_id))).result() + time.sleep(1.0) + + assert _primary_active(device_id), "primary context destroyed while a cuda.core object still refers to it" + use(Device(device_id), obj) + + +@pytest.mark.agent_authored(model="claude-opus-5-5") +@pytest.mark.parametrize( + ("lookup", "use"), + [ + pytest.param(_lookup_foreign_stream_context, _use_context, id="foreign-stream-context"), + pytest.param(_lookup_default_stream_event, _use_event, id="default-stream-event"), + ], +) +def test_primary_context_survives_thread_exit(init_cuda, lookup, use): + """A Context resolved through the registry keeps the primary context alive after other threads exit.""" + # The child asserts on the primary context's state and uses the object, so + # it exits non-zero (failing the test) if the context was destroyed. + run_child(_primary_context_across_threads_child, init_cuda.device_id, lookup, use) + + +# Several threads retain the primary context concurrently, so most of them lose +# the registration race in get_primary_context() and must release their extra +# retain. One Context must keep the context alive after every thread has exited, +# and dropping it must release the last retain: a leaked extra retain keeps the +# context active, and an extra release destroys it while the Context is held. +# The thread_local caches are destroyed after Thread.join() returns. They hold +# the same box as the Context, so they do not affect the first check, and the +# second check polls until they are gone. +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) + + # An extra release of the primary context fails and is reported as a + # CUDAWarning, so the block asserts that none was issued. + with assert_no_cuda_warning(): + run_in_threads([worker] * num_threads, barrier=barrier, timeout=child_timeout_sec()) + assert len(contexts) == num_threads + + held = contexts[0] + contexts.clear() + gc.collect() + assert _primary_active(device_id), "primary context destroyed while a Context is held" + + del held + gc.collect() + deadline = time.monotonic() + 5.0 + while _primary_active(device_id) and time.monotonic() < deadline: + time.sleep(0.05) + assert not _primary_active(device_id), "primary context still active after its last Context was dropped" + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_concurrent_set_current_keeps_primary_active_after_threads_exit(init_cuda): + """After concurrent Device.set_current() calls, a held Context keeps the primary context active, and + dropping the last one releases it.""" + run_child(_concurrent_primary_retains_child, init_cuda.device_id) + + +# The primary context's deleter runs on the thread that drops the last handle, +# and for the last thread to exit that is native thread teardown, where running +# a Python warning hook is unsafe (on Windows the loader lock is held). A failed +# release must then be reported later, from the main thread. The release fails +# here because the child releases cuda.core's only retain behind its back. +def _deferred_release_report_child(device_id): + main_thread = threading.get_ident() + timeout = child_timeout_sec() + retained = threading.Event() + released = threading.Event() + reports = [] + + def show(message, category, filename, lineno, file=None, line=None): + reports.append((threading.get_ident(), str(message))) + + def worker(): + Device(device_id).set_current() + retained.set() + assert released.wait(timeout) + + def release_behind_cuda_cores_back(): + assert retained.wait(timeout) + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + released.set() + + with warnings.catch_warnings(): + warnings.simplefilter("always", CUDAWarning) + warnings.showwarning = show + run_in_threads([worker, release_behind_cuda_cores_back], timeout=timeout) + # The worker's thread_local cache can be destroyed after its thread is + # joined, and the deferred report is delivered at a later bytecode + # boundary of the main thread. + deadline = time.monotonic() + 5.0 + while not any("cuDevicePrimaryCtxRelease" in message for _, message in reports): + assert time.monotonic() < deadline, f"no release report was delivered: {reports}" + time.sleep(0.05) + time.sleep(0.5) + + release_reports = [(thread, message) for thread, message in reports if "cuDevicePrimaryCtxRelease" in message] + assert len(release_reports) == 1, release_reports + assert release_reports[0][0] == main_thread, "the release failure was reported from a thread that was exiting" + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_failed_primary_release_at_thread_exit_is_reported_from_main_thread(init_cuda): + """A primary-context release that fails during thread exit is reported from the main thread.""" + run_child(_deferred_release_report_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..224dc6b96d43 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -256,6 +256,60 @@ 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() + + # --------------------------------------------------------------------------- # SM resource query # ---------------------------------------------------------------------------