From c87022d2aa9141800714a70e918e9213e7ad1fef Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 08:09:23 -0800 Subject: [PATCH 1/9] fix(cuda.core): keep one owning context handle per live context Each thread that missed its thread-local cache in get_primary_context() retained the primary context separately and overwrote the registry entry of the previous thread's box, and every context deleter erased the registry entry for its CUcontext unconditionally. When a thread exited, its box erased the entry of a still-live box, later lookups returned non-retaining handles, and the driver destroyed the primary context while cuda.core objects still referred to it. The same unconditional erase and overwrite let Device.create_context() drop its new green context in favor of a stale plain entry at a reused address. HandleRegistry now records the element address of each entry, erases an entry only for the handle that registered it, and gains insert_or_get(), which registers a candidate without displacing a live entry unless a policy says so. Contexts use it to keep one owning box per live context: a box that holds a primary-context retain or the owning green-context handle replaces a plain one, and nothing replaces an owning one. All threads now share one retaining primary-context box per device. Stream, event and graph registries use the ownership-checked erase as well. The primary-context deleter now reports cuDevicePrimaryCtxRelease failures through a pw_ wrapper instead of discarding the status. Part of #3533 Co-Authored-By: Claude Opus 5.5 --- .../cuda/core/_cpp/rt/REGISTRY_DESIGN.md | 17 ++++ cuda_core/cuda/core/_cpp/rt/context.cpp | 62 ++++++++++--- cuda_core/cuda/core/_cpp/rt/event.cpp | 4 +- cuda_core/cuda/core/_cpp/rt/graph.cpp | 7 +- cuda_core/cuda/core/_cpp/rt/internal.hpp | 55 +++++++++-- cuda_core/cuda/core/_cpp/rt/stream.cpp | 4 +- cuda_core/docs/source/release/1.4.0-notes.rst | 24 +++++ cuda_core/tests/test_context.py | 91 +++++++++++++++++++ cuda_core/tests/test_green_context.py | 44 +++++++++ 9 files changed, 281 insertions(+), 27 deletions(-) diff --git a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md index 8fb71e13a9f1..298af8cfaf61 100644 --- a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md @@ -33,6 +33,23 @@ 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. `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..f93ceb1d7fd1 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -119,6 +119,7 @@ namespace { struct ContextBox { CUcontext resource; GreenCtxHandle h_green_ctx; + bool retains_primary = false; // Owns one cuDevicePrimaryCtxRetain. }; struct GreenCtxBox { @@ -135,6 +136,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 +165,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,7 +255,8 @@ create_green_ctx_handle_ref(CUgreenCtx green_ctx) return GreenCtxHandle(box, &box->resource); } -// Thread-local cache of primary contexts indexed by device ID +// 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. static thread_local std::vector primary_context_cache; ContextHandle @@ -249,22 +278,29 @@ get_primary_context(int device_id) // clang-format off auto box = std::shared_ptr( - new ContextBox{ctx, {}}, + new ContextBox{ctx, {}, true}, [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); + pw_cuDevicePrimaryCtxRelease(device_id); } delete b; } ); // clang-format on - auto h = ContextHandle(box, &box->resource); - context_registry.register_handle(ctx, h); + 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)); + candidate.reset(); + box.reset(); // Update cache if (static_cast(device_id) >= primary_context_cache.size()) { 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..60bf792a0195 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,68 @@ 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) { std::scoped_lock lock(mutex_); - map_.erase(key); + auto [it, inserted] = map_.try_emplace(key); + if (!inserted) { + if (Handle existing = it->second.handle.lock()) { + if (!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 +256,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 +264,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..31c35a521345 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,27 @@ 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 is released when the last + ``cuda.core`` object that refers to it is released. A context that + ``cuda.core`` did not retain, for example one made current by another + library, stays valid only as long as that library 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 a context that ``cuda.core`` saw earlier, for example as 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..ed900d695cd0 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -2,6 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 import pytest +from cuda_python_test_helpers.subprocess_runner import run_python_snippet +from helpers.child_processes import child_timeout_sec import cuda.core from cuda.core import Device @@ -89,3 +91,92 @@ 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 and waits until thread B has retained +# it too and exited. Thread A then resolves a Context through the context +# registry (``{lookup}``), and the main thread uses that object (``{use}``) once +# both threads are gone. The child process starts clean, 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. +_PRIMARY_CONTEXT_ACROSS_THREADS = """ +import threading +import time +import warnings + +from cuda.bindings import driver +from cuda.core import CUDAWarning, Device, Stream + +warnings.simplefilter("error", CUDAWarning) +out = [] +errors = [] +b_exited = threading.Event() + + +def thread_a(): + try: + dev = Device({device_id}) + dev.set_current() + b_exited.wait() + out.append({lookup}) + except BaseException as exc: + errors.append(exc) + + +def thread_b(): + try: + Device({device_id}).set_current() + except BaseException as exc: + errors.append(exc) + + +a = threading.Thread(target=thread_a) +a.start() +b = threading.Thread(target=thread_b) +b.start() +b.join() +time.sleep(1.0) +b_exited.set() +a.join() +time.sleep(1.0) +if errors: + raise errors[0] + +err, _, active = driver.cuDevicePrimaryCtxGetState({device_id}) +assert err == driver.CUresult.CUDA_SUCCESS, err +assert active, "primary context destroyed while a cuda.core object still refers to it" +obj = out[0] +{use} +""" + + +@pytest.mark.agent_authored(model="claude-opus-5-5") +@pytest.mark.parametrize( + ("lookup", "use"), + [ + pytest.param( + "Stream.from_handle(int(driver.CU_STREAM_LEGACY)).context", + "Device({device_id}).set_current(obj)\nDevice({device_id}).create_stream().sync()", + id="foreign-stream-context", + ), + pytest.param("dev.default_stream.record()", "obj.sync()", 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.""" + device_id = init_cuda.device_id + code = _PRIMARY_CONTEXT_ACROSS_THREADS.format( + device_id=device_id, lookup=lookup, use=use.format(device_id=device_id) + ) + result = run_python_snippet(code, timeout=child_timeout_sec()) + assert "CONTEXT_IS_DESTROYED" not in result.stderr diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index f95037077012..c47f545119e6 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -256,6 +256,50 @@ 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)) + 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) + handle_return(driver.cuGreenCtxDestroy(foreign)) + assert not stale.is_green + try: + green = dev.create_context(opts) + except CUDAError as exc: + pytest.skip(str(exc)) + 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. + try: + assert green.is_green + stream = green.create_stream() + stream.sync() + stream.close() + finally: + green.close() + + # --------------------------------------------------------------------------- # SM resource query # --------------------------------------------------------------------------- From e461e0886be8cc7d1b5d393cd41b99654c0f31da Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 10:57:43 -0800 Subject: [PATCH 2/9] fix(cuda.core): release a displaced registry handle after the unlock insert_or_get() destroyed a displaced live handle at the end of its inner scope, while the registry mutex was still held. If another thread had dropped its own copy in the meantime, that handle was the last reference, and its deleter took the same mutex and deadlocked. Declare the handle before the lock so that it is destroyed after the unlock. Add a test in which several threads call Device.set_current() concurrently in a fresh process. It covers the losing-candidate path in get_primary_context(): one held Context keeps the primary context active, and dropping it leaves the context inactive. Co-Authored-By: Claude Opus 5.5 --- cuda_core/cuda/core/_cpp/rt/internal.hpp | 12 ++-- cuda_core/tests/test_context.py | 70 ++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 4 deletions(-) diff --git a/cuda_core/cuda/core/_cpp/rt/internal.hpp b/cuda_core/cuda/core/_cpp/rt/internal.hpp index 60bf792a0195..b30b0ea4fab3 100644 --- a/cuda_core/cuda/core/_cpp/rt/internal.hpp +++ b/cuda_core/cuda/core/_cpp/rt/internal.hpp @@ -222,13 +222,17 @@ class HandleRegistry { 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) { - if (Handle existing = it->second.handle.lock()) { - if (!replace(existing)) { - return existing; - } + existing = it->second.handle.lock(); + if (existing && !replace(existing)) { + return existing; } } it->second = Entry{candidate, candidate.get()}; diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index ed900d695cd0..01daa7ab5fa6 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -180,3 +180,73 @@ def test_primary_context_survives_thread_exit(init_cuda, lookup, use): ) result = run_python_snippet(code, timeout=child_timeout_sec()) assert "CONTEXT_IS_DESTROYED" not in result.stderr + + +# 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, so the child +# waits a fixed second before checking (see _PRIMARY_CONTEXT_ACROSS_THREADS). +_CONCURRENT_PRIMARY_RETAINS = """ +import gc +import threading +import time +import warnings + +from cuda.bindings import driver +from cuda.core import CUDAWarning, Device + +warnings.simplefilter("error", CUDAWarning) +NUM_THREADS = 8 +barrier = threading.Barrier(NUM_THREADS) +contexts = [] +errors = [] + + +def worker(): + try: + dev = Device({device_id}) + barrier.wait() + dev.set_current() + contexts.append(dev.context) + except BaseException as exc: + errors.append(exc) + + +def primary_active(): + err, _, active = driver.cuDevicePrimaryCtxGetState({device_id}) + assert err == driver.CUresult.CUDA_SUCCESS, err + return bool(active) + + +threads = [threading.Thread(target=worker) for _ in range(NUM_THREADS)] +for t in threads: + t.start() +for t in threads: + t.join() +time.sleep(1.0) +if errors: + raise errors[0] +assert len(contexts) == NUM_THREADS + +held = contexts[0] +contexts.clear() +gc.collect() +assert primary_active(), "primary context destroyed while a Context is held" + +del held +gc.collect() +deadline = time.monotonic() + 5.0 +while primary_active() and time.monotonic() < deadline: + time.sleep(0.05) +assert not primary_active(), "primary context still active after its last Context was dropped" +""" + + +@pytest.mark.agent_authored(model="claude-opus-5-5") +def test_concurrent_set_current_shares_one_primary_retain(init_cuda): + """Concurrent Device.set_current() calls leave exactly one primary-context retain, held by the Context.""" + code = _CONCURRENT_PRIMARY_RETAINS.format(device_id=init_cuda.device_id) + run_python_snippet(code, timeout=child_timeout_sec()) From c6cb7a3b98bb3ff3a3043810f8c021f51967f5b9 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 13:07:35 -0800 Subject: [PATCH 3/9] docs,test(cuda.core): tighten #3533 release notes and tests Release notes: say that only the retaining handle keeps the primary context alive, and that the green-context bug needs a live Context for the earlier context. Tests: drop the stderr-text assertion, let create_context errors propagate instead of skipping, and destroy the foreign green context and close the stream on failure. Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/docs/source/release/1.4.0-notes.rst | 12 ++++++---- cuda_core/tests/test_context.py | 5 ++-- cuda_core/tests/test_green_context.py | 23 ++++++++++--------- 3 files changed, 22 insertions(+), 18 deletions(-) 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 31c35a521345..4998ad503cc9 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -68,15 +68,17 @@ Fixes and enhancements :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 is released when the last - ``cuda.core`` object that refers to it is released. A context that - ``cuda.core`` did not retain, for example one made current by another - library, stays valid only as long as that library keeps it alive. + 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 a context that ``cuda.core`` saw earlier, for example as 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/test_context.py b/cuda_core/tests/test_context.py index 01daa7ab5fa6..bfe22dfaea9e 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -178,8 +178,9 @@ def test_primary_context_survives_thread_exit(init_cuda, lookup, use): code = _PRIMARY_CONTEXT_ACROSS_THREADS.format( device_id=device_id, lookup=lookup, use=use.format(device_id=device_id) ) - result = run_python_snippet(code, timeout=child_timeout_sec()) - assert "CONTEXT_IS_DESTROYED" not in result.stderr + # 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_python_snippet(code, timeout=child_timeout_sec()) # Several threads retain the primary context concurrently, so most of them lose diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index c47f545119e6..2ac021ce5e65 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -273,16 +273,15 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): # the next green context. Retry until the address is reused. for _ in range(20): foreign = handle_return(driver.cuGreenCtxCreate(desc, dev.device_id, flags)) - 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) - handle_return(driver.cuGreenCtxDestroy(foreign)) - assert not stale.is_green try: - green = dev.create_context(opts) - except CUDAError as exc: - pytest.skip(str(exc)) + 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) + finally: + 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() @@ -294,8 +293,10 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): try: assert green.is_green stream = green.create_stream() - stream.sync() - stream.close() + try: + stream.sync() + finally: + stream.close() finally: green.close() From 1251b13d07c01a334fea558d1278f4b238c01741 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 13:15:15 -0800 Subject: [PATCH 4/9] test,docs(cuda.core): tighten #3533 test cleanup and registry notes test_green_context_replaces_stale_plain_entry: if set_current() fails after the foreign green context was made current, make the primary context current again before destroying the foreign one, and let the original error propagate instead of a rollback failure from handle_return. test_concurrent_set_current_shares_one_primary_retain: drop the fixed one-second wait. The held Context keeps the primary context active either way, and the release check already polls with a deadline. REGISTRY_DESIGN.md: state that insert_or_get releases a displaced live handle only after the unlock. Co-Authored-By: Claude Opus 5.5 --- cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md | 5 ++++- cuda_core/tests/test_context.py | 6 +++--- cuda_core/tests/test_green_context.py | 9 +++++++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md index 298af8cfaf61..2a9aa8ebf751 100644 --- a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md @@ -44,7 +44,10 @@ 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. `context_registry` uses +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 diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index bfe22dfaea9e..1889e8e7e833 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -188,8 +188,9 @@ def test_primary_context_survives_thread_exit(init_cuda, lookup, use): # 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, so the child -# waits a fixed second before checking (see _PRIMARY_CONTEXT_ACROSS_THREADS). +# 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. _CONCURRENT_PRIMARY_RETAINS = """ import gc import threading @@ -227,7 +228,6 @@ def primary_active(): t.start() for t in threads: t.join() -time.sleep(1.0) if errors: raise errors[0] assert len(contexts) == NUM_THREADS diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index 2ac021ce5e65..e5501d9acce4 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -278,8 +278,13 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): # 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) - finally: - handle_return(driver.cuGreenCtxDestroy(foreign)) + except BaseException: + # Do not leave the foreign context current once it is destroyed, and + # let the original error propagate: rollback statuses are ignored. + driver.cuCtxSetCurrent(primary.handle) + driver.cuGreenCtxDestroy(foreign) + raise + handle_return(driver.cuGreenCtxDestroy(foreign)) assert not stale.is_green green = dev.create_context(opts) if int(green.handle) == int(stale.handle): From 409940a26e5bf91da0f46d071d24b8c339621765 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 14:23:21 -0800 Subject: [PATCH 5/9] fix,test(cuda.core): close the primary cache during thread exit; tighten #3533 tests context.cpp: the thread-local primary-context cache is now a struct whose destructor sets a plain thread_local flag before dropping its entries from a local. A CUDAWarning hook that runs while the last entry is released and calls Device.set_current() then bypasses the cache instead of reading one that is being destroyed. test_primary_context_survives_thread_exit: start thread B only after thread A has retained the primary context, so the test cannot pass because B registered first. test_green_context_replaces_stale_plain_entry: check liveness with green.resources.sm, which works on driver 12.4, instead of a stream, which needs 12.5. Both thread tests now run module-level child functions through run_child and use ThreadPoolExecutor, which propagates thread errors through result(). Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/cuda/core/_cpp/rt/context.cpp | 42 ++++- cuda_core/tests/test_context.py | 194 ++++++++++-------------- cuda_core/tests/test_green_context.py | 10 +- 3 files changed, 120 insertions(+), 126 deletions(-) diff --git a/cuda_core/cuda/core/_cpp/rt/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index f93ceb1d7fd1..d9f78ac044bd 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -255,16 +255,44 @@ create_green_ctx_handle_ref(CUgreenCtx green_ctx) return GreenCtxHandle(box, &box->resource); } +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. -static thread_local std::vector primary_context_cache; +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; } } @@ -303,10 +331,12 @@ get_primary_context(int device_id) box.reset(); // Update cache - if (static_cast(device_id) >= primary_context_cache.size()) { - primary_context_cache.resize(device_id + 1); + 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; return h; } diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index 1889e8e7e833..a18f854cbd44 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -1,12 +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 warnings +from concurrent.futures import ThreadPoolExecutor + import pytest -from cuda_python_test_helpers.subprocess_runner import run_python_snippet -from helpers.child_processes import child_timeout_sec +from helpers.child_processes import run_child 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(): @@ -97,90 +104,77 @@ def test_context_dict_key(init_cuda): # Primary-context lifetime across threads (#3533) # ============================================================================ -# Thread A retains the primary context and waits until thread B has retained -# it too and exited. Thread A then resolves a Context through the context -# registry (``{lookup}``), and the main thread uses that object (``{use}``) once -# both threads are gone. The child process starts clean, so nothing else holds -# a retain of the primary context: the pytest process does, through fixtures, -# which would hide the bug. +# 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. -_PRIMARY_CONTEXT_ACROSS_THREADS = """ -import threading -import time -import warnings -from cuda.bindings import driver -from cuda.core import CUDAWarning, Device, Stream -warnings.simplefilter("error", CUDAWarning) -out = [] -errors = [] -b_exited = threading.Event() +def _primary_active(device_id): + _, active = handle_return(driver.cuDevicePrimaryCtxGetState(device_id)) + return bool(active) -def thread_a(): - try: - dev = Device({device_id}) - dev.set_current() - b_exited.wait() - out.append({lookup}) - except BaseException as exc: - errors.append(exc) - - -def thread_b(): - try: - Device({device_id}).set_current() - except BaseException as exc: - errors.append(exc) - - -a = threading.Thread(target=thread_a) -a.start() -b = threading.Thread(target=thread_b) -b.start() -b.join() -time.sleep(1.0) -b_exited.set() -a.join() -time.sleep(1.0) -if errors: - raise errors[0] - -err, _, active = driver.cuDevicePrimaryCtxGetState({device_id}) -assert err == driver.CUresult.CUDA_SUCCESS, err -assert active, "primary context destroyed while a cuda.core object still refers to it" -obj = out[0] -{use} -""" +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): + warnings.simplefilter("error", CUDAWarning) + + def retain(): + Device(device_id).set_current() + + # 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( - "Stream.from_handle(int(driver.CU_STREAM_LEGACY)).context", - "Device({device_id}).set_current(obj)\nDevice({device_id}).create_stream().sync()", - id="foreign-stream-context", - ), - pytest.param("dev.default_stream.record()", "obj.sync()", id="default-stream-event"), + 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.""" - device_id = init_cuda.device_id - code = _PRIMARY_CONTEXT_ACROSS_THREADS.format( - device_id=device_id, lookup=lookup, use=use.format(device_id=device_id) - ) # 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_python_snippet(code, timeout=child_timeout_sec()) + 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 @@ -191,63 +185,35 @@ def test_primary_context_survives_thread_exit(init_cuda, lookup, use): # 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. -_CONCURRENT_PRIMARY_RETAINS = """ -import gc -import threading -import time -import warnings - -from cuda.bindings import driver -from cuda.core import CUDAWarning, Device - -warnings.simplefilter("error", CUDAWarning) -NUM_THREADS = 8 -barrier = threading.Barrier(NUM_THREADS) -contexts = [] -errors = [] - +def _concurrent_primary_retains_child(device_id): + warnings.simplefilter("error", CUDAWarning) + num_threads = 8 + barrier = threading.Barrier(num_threads) -def worker(): - try: - dev = Device({device_id}) + def worker(_): + dev = Device(device_id) barrier.wait() dev.set_current() - contexts.append(dev.context) - except BaseException as exc: - errors.append(exc) - - -def primary_active(): - err, _, active = driver.cuDevicePrimaryCtxGetState({device_id}) - assert err == driver.CUresult.CUDA_SUCCESS, err - return bool(active) - + return dev.context -threads = [threading.Thread(target=worker) for _ in range(NUM_THREADS)] -for t in threads: - t.start() -for t in threads: - t.join() -if errors: - raise errors[0] -assert len(contexts) == NUM_THREADS + # The workers block on the barrier, so each runs on its own thread. + with ThreadPoolExecutor(max_workers=num_threads) as pool: + contexts = list(pool.map(worker, range(num_threads))) -held = contexts[0] -contexts.clear() -gc.collect() -assert primary_active(), "primary context destroyed while a Context is held" + 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() and time.monotonic() < deadline: - time.sleep(0.05) -assert not primary_active(), "primary context still active after its last Context was dropped" -""" + 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-opus-5-5") def test_concurrent_set_current_shares_one_primary_retain(init_cuda): """Concurrent Device.set_current() calls leave exactly one primary-context retain, held by the Context.""" - code = _CONCURRENT_PRIMARY_RETAINS.format(device_id=init_cuda.device_id) - run_python_snippet(code, timeout=child_timeout_sec()) + run_child(_concurrent_primary_retains_child, init_cuda.device_id) diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index e5501d9acce4..145fb75608f4 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -294,14 +294,12 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): 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. + # 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 - stream = green.create_stream() - try: - stream.sync() - finally: - stream.close() + assert green.resources.sm.sm_count == groups[0].sm_count finally: green.close() From e8a92effde7145c96703fb1ef81e397e025e48a6 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 14:34:53 -0800 Subject: [PATCH 6/9] test(cuda.core): assert no CUDAWarning in #3533 children; attach rollback failures The thread-exit and concurrent-retain children used simplefilter("error", CUDAWarning), but a promoted warning from a deleter reaches sys.unraisablehook, so the child still exited 0. Run both bodies inside assert_no_cuda_warning(), which records warnings and fails on a CUDAWarning. test_green_context_replaces_stale_plain_entry: keep both rollback calls and attach each failed status to the original exception instead of discarding it. Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/tests/test_context.py | 68 ++++++++++++++------------- cuda_core/tests/test_green_context.py | 11 +++-- 2 files changed, 43 insertions(+), 36 deletions(-) diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index a18f854cbd44..0ade0d5fd909 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -4,15 +4,15 @@ import gc import threading import time -import warnings from concurrent.futures import ThreadPoolExecutor import pytest from helpers.child_processes import run_child +from helpers.contexts import assert_no_cuda_warning import cuda.core from cuda.bindings import driver -from cuda.core import CUDAWarning, Device, Stream +from cuda.core import Device, Stream from cuda.core._utils.cuda_utils import handle_return @@ -141,25 +141,27 @@ def _use_event(dev, event): def _primary_context_across_threads_child(device_id, lookup, use): - warnings.simplefilter("error", CUDAWarning) - def retain(): Device(device_id).set_current() - # 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() + # 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) - 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) + 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") @@ -186,7 +188,6 @@ def test_primary_context_survives_thread_exit(init_cuda, lookup, use): # 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): - warnings.simplefilter("error", CUDAWarning) num_threads = 8 barrier = threading.Barrier(num_threads) @@ -196,21 +197,24 @@ def worker(_): dev.set_current() return dev.context - # The workers block on the barrier, so each runs on its own thread. - with ThreadPoolExecutor(max_workers=num_threads) as pool: - contexts = list(pool.map(worker, range(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" + # 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(): + # The workers block on the barrier, so each runs on its own thread. + with ThreadPoolExecutor(max_workers=num_threads) as pool: + contexts = list(pool.map(worker, range(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-opus-5-5") diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index 145fb75608f4..dc9853527889 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -19,6 +19,7 @@ WorkqueueResourceOptions, launch, ) +from cuda.core._rt import _attach_rollback_failure_for_testing from cuda.core._utils.cuda_utils import CUDAError, driver, handle_return from cuda.core._utils.version import BUILD_CUDA_MAJOR, driver_version from cuda.core.graph import GraphDefinition @@ -279,10 +280,12 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): # plain, non-owning Context for it and registers it. stale = dev.set_current(primary) except BaseException: - # Do not leave the foreign context current once it is destroyed, and - # let the original error propagate: rollback statuses are ignored. - driver.cuCtxSetCurrent(primary.handle) - driver.cuGreenCtxDestroy(foreign) + # 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 attached to it. + for (err,) in (driver.cuCtxSetCurrent(primary.handle), driver.cuGreenCtxDestroy(foreign)): + if err != driver.CUresult.CUDA_SUCCESS: + _attach_rollback_failure_for_testing(int(err)) raise handle_return(driver.cuGreenCtxDestroy(foreign)) assert not stale.is_green From 4781acea3effbdda50cfc50f26c0c5cf24feb46e Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 30 Nov 2026 13:43:03 -0800 Subject: [PATCH 7/9] fix(cuda.core): cache the primary context before dropping a losing candidate get_primary_context() dropped its candidate box before it stored the winning handle in the thread-local cache. When another thread's box won, dropping the candidate releases the extra retain, and a failure there is reported through a warning hook. A hook that called Device.set_current() found the cache still empty and repeated the retain-and-release path, so the callback reentered. Store the handle in the cache first, so a reentrant call finds it. Found by rwgk's review of #3538, using a mocked driver whose release fails. A test needs a losing candidate, which two threads racing the first retain produce only by chance, so none is added. Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/cuda/core/_cpp/rt/context.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/cuda_core/cuda/core/_cpp/rt/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index d9f78ac044bd..fb1ec3cd532d 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -327,16 +327,19 @@ get_primary_context(int device_id) // 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)); - candidate.reset(); - box.reset(); - // Update cache + // 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; } + candidate.reset(); + box.reset(); return h; } From f63e1c2faca2bd3a10775c02dba5224723ed9583 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 30 Nov 2026 13:45:36 -0800 Subject: [PATCH 8/9] fix(cuda.core): report a failed primary release at thread exit from the main thread The primary context's deleter reports a failed cuDevicePrimaryCtxRelease through a pw_ wrapper, which runs Python warning hooks on the calling thread. When the last thread that cached the context exits, the deleter runs from the thread_local cache's destructor, in native thread teardown. On Windows the loader lock is held there, so a hook that starts a thread waits for a thread that cannot start. Python state is torn down at that point on every platform. When the thread's cache is closed, the deleter now calls the driver without reporting and, on failure, hands a report to the deferred-cleanup queue, which delivers it from the main thread. The report is preallocated with the box, so the deleter does not allocate. It is dropped during interpreter finalization, like other deleter work. The test makes the release fail by releasing cuda.core's only retain from the child, then lets the last thread exit. On the previous code the one CUDAWarning arrives from the exiting thread. Found by rwgk's review of #3538, from source inspection. Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/cuda/core/_cpp/rt/DESIGN.md | 1 + cuda_core/cuda/core/_cpp/rt/context.cpp | 39 +++++++++++++++++- cuda_core/tests/test_context.py | 55 ++++++++++++++++++++++++- 3 files changed, 91 insertions(+), 4 deletions(-) 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/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index fb1ec3cd532d..30175eced0cc 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -116,10 +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 { @@ -306,14 +325,30 @@ get_primary_context(int device_id) // clang-format off auto box = std::shared_ptr( - new ContextBox{ctx, {}, true}, + new ContextBox{ctx, {}, true, std::make_unique()}, [device_id](const ContextBox *b) { context_registry.unregister_handle(b->resource, &b->resource); // During interpreter shutdown, leave primary-context cleanup to // process teardown. Reporting a failure needs Python too. if (Py_IsInitialized() && !py_is_finalizing()) { GILReleaseGuard gil; - pw_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; } diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index 0ade0d5fd909..535628c8e515 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -4,15 +4,17 @@ import gc import threading import time +import warnings from concurrent.futures import ThreadPoolExecutor import pytest -from helpers.child_processes import run_child +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.bindings import driver -from cuda.core import Device, Stream +from cuda.core import CUDAWarning, Device, Stream from cuda.core._utils.cuda_utils import handle_return @@ -221,3 +223,52 @@ def worker(_): def test_concurrent_set_current_shares_one_primary_retain(init_cuda): """Concurrent Device.set_current() calls leave exactly one primary-context retain, held by the Context.""" 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) From abca5205f18bb69c4a9286d632a3e56b11cde3ed Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 30 Nov 2026 13:46:13 -0800 Subject: [PATCH 9/9] test(cuda.core): name the concurrent set_current test for what it checks test_concurrent_set_current_shares_one_primary_retain claimed to count retains, but it drops seven of its eight Contexts before the first check, so it only checks cleanup: a held Context keeps the primary context active, and dropping the last one releases it. main passes that too. Rename it to match, and leave the lifetime guarantee to test_primary_context_survives_thread_exit. Start the workers with run_in_threads instead of a ThreadPoolExecutor, so a failing worker aborts the barrier and its error is re-raised instead of the other workers blocking until the child times out. In test_green_context_replaces_stale_plain_entry, note rollback failures on the propagating exception with add_note() instead of the private _attach_rollback_failure_for_testing hook, which exists to test the C++ attach_rollback_failure() itself. Found by rwgk's review of #3538. Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/tests/test_context.py | 17 +++++++++-------- cuda_core/tests/test_green_context.py | 13 ++++++++----- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index 535628c8e515..73bba507cabe 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -192,19 +192,19 @@ def test_primary_context_survives_thread_exit(init_cuda, lookup, use): def _concurrent_primary_retains_child(device_id): num_threads = 8 barrier = threading.Barrier(num_threads) + contexts = [] - def worker(_): + def worker(): dev = Device(device_id) barrier.wait() dev.set_current() - return dev.context + 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(): - # The workers block on the barrier, so each runs on its own thread. - with ThreadPoolExecutor(max_workers=num_threads) as pool: - contexts = list(pool.map(worker, range(num_threads))) + run_in_threads([worker] * num_threads, barrier=barrier, timeout=child_timeout_sec()) + assert len(contexts) == num_threads held = contexts[0] contexts.clear() @@ -219,9 +219,10 @@ def worker(_): assert not _primary_active(device_id), "primary context still active after its last Context was dropped" -@pytest.mark.agent_authored(model="claude-opus-5-5") -def test_concurrent_set_current_shares_one_primary_retain(init_cuda): - """Concurrent Device.set_current() calls leave exactly one primary-context retain, held by the Context.""" +@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) diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index dc9853527889..224dc6b96d43 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -19,7 +19,6 @@ WorkqueueResourceOptions, launch, ) -from cuda.core._rt import _attach_rollback_failure_for_testing from cuda.core._utils.cuda_utils import CUDAError, driver, handle_return from cuda.core._utils.version import BUILD_CUDA_MAJOR, driver_version from cuda.core.graph import GraphDefinition @@ -279,13 +278,17 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): # 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: + 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 attached to it. - for (err,) in (driver.cuCtxSetCurrent(primary.handle), driver.cuGreenCtxDestroy(foreign)): + # 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: - _attach_rollback_failure_for_testing(int(err)) + exc.add_note(f"rollback: {name} failed with {err.name}") raise handle_return(driver.cuGreenCtxDestroy(foreign)) assert not stale.is_green