From c87022d2aa9141800714a70e918e9213e7ad1fef Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 08:09:23 -0800 Subject: [PATCH 1/7] 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/7] 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/7] 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/7] 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/7] 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/7] 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 2ca321ec4a4f400fa0271eca41fd5f7e0cff81b0 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 30 Nov 2026 10:29:21 -0800 Subject: [PATCH 7/7] fix(cuda.core): retain each primary context once and never release it cuda.core again keeps each device's primary context alive for the rest of the process, as the CUDA runtime does and as cuda.core did before 0.6.0 (#1368). get_primary_context() pins one retaining box per device in a process-wide table that is never freed and is read without a lock, so no thread exit or handle release can drop it. The per-thread cache is gone. create_context_handle_ref() and get_current_context() also pin a primary context that another library made current: if the context is the calling thread's current context and its device's active primary context, it is retained once and pinned. The retain taken to compare addresses is given back for any other context, and an inactive primary context is never created. Device.set_current(ctx) resolves the previous context before it switches, while that context is still current. Context resolution now goes through one helper in C++ and one in Cython (Context_primary() / Context_get_primary_handle()), which Device.set_current() and both memory resources share, so failures are raised consistently. These lookups may take a mutex and report a failure, which acquires the GIL, so they must not run under a C++ lock. deviceptr_import_ipc() therefore resolves the deallocation stream before it takes the IPC pointer cache's mutex, and peeks at the cache first with a non-waiting find_live(), so a repeat import is returned without resolving a stream. Device.set_current(ctx) no longer returns a stale Context for the previous context: the driver reuses the address of a destroyed context, so it now compares the remembered Context's handle with the handle just resolved instead of comparing raw addresses. DESIGN.md and REGISTRY_DESIGN.md describe the primary-context policy and its lock rule. Tests cover concurrent set_current() leaving exactly one retain, lookups and set_current() of a primary context that another owner made current, a green-context lookup leaving no primary retain, and the stale-address case. Fixes #3533 Co-Authored-By: Claude Opus 5.5 --- cuda_core/cuda/core/_context.pxd | 4 + cuda_core/cuda/core/_context.pyx | 21 ++ cuda_core/cuda/core/_cpp/rt/DESIGN.md | 59 ++- .../cuda/core/_cpp/rt/REGISTRY_DESIGN.md | 8 +- cuda_core/cuda/core/_cpp/rt/api.hpp | 22 +- cuda_core/cuda/core/_cpp/rt/context.cpp | 346 +++++++++++++----- cuda_core/cuda/core/_cpp/rt/driver_api.hpp | 1 + cuda_core/cuda/core/_cpp/rt/internal.hpp | 10 + cuda_core/cuda/core/_cpp/rt/memory.cpp | 38 +- cuda_core/cuda/core/_device.pyx | 31 +- .../_memory/_synchronous_memory_resource.pyx | 12 +- .../core/_memory/_virtual_memory_resource.pyx | 9 +- cuda_core/cuda/core/_rt.pxd | 2 + cuda_core/cuda/core/_rt.pyx | 2 + cuda_core/docs/source/release/1.4.0-notes.rst | 33 +- cuda_core/tests/helpers/contexts.py | 7 + cuda_core/tests/test_context.py | 168 ++++----- cuda_core/tests/test_green_context.py | 135 ++++++- cuda_core/tests/test_rt_layout.py | 7 +- 19 files changed, 638 insertions(+), 277 deletions(-) diff --git a/cuda_core/cuda/core/_context.pxd b/cuda_core/cuda/core/_context.pxd index 3476fffb322c..1b917f7834cf 100644 --- a/cuda_core/cuda/core/_context.pxd +++ b/cuda_core/cuda/core/_context.pxd @@ -25,6 +25,10 @@ cdef class Context: cpdef close(self) +cdef int Context_get_primary_handle(int device_id, ContextHandle* h_context) except -1 +cdef Context Context_primary(int device_id) + + cdef inline int Context_check_open(Context self) except -1: if not self._h_context: raise RuntimeError("Context has been closed") diff --git a/cuda_core/cuda/core/_context.pyx b/cuda_core/cuda/core/_context.pyx index 725dd8eb7fdd..48525e866a63 100644 --- a/cuda_core/cuda/core/_context.pyx +++ b/cuda_core/cuda/core/_context.pyx @@ -18,6 +18,7 @@ from cuda.core._rt cimport ( create_context_handle_from_green_ctx, get_context_green_ctx, get_last_error, + get_primary_context, as_intptr, as_py, ) @@ -150,6 +151,26 @@ cdef class Context: return f"" +cdef int Context_get_primary_handle(int device_id, ContextHandle* h_context) except -1: + """Store the primary context of ``device_id`` in ``h_context``. + + cuda.core retains it on first use and never releases it. Raises if it + cannot be retained. + """ + h_context[0] = get_primary_context(device_id) + if not h_context[0]: + HANDLE_RETURN(get_last_error()) + raise RuntimeError(f"Failed to retain the primary context for device {device_id}") + return 0 + + +cdef Context Context_primary(int device_id): + """Return a :class:`Context` for the primary context of ``device_id``.""" + cdef ContextHandle h_context + Context_get_primary_handle(device_id, &h_context) + return Context._from_handle(Context, h_context, device_id) + + @dataclass cdef class ContextOptions: """Options for context creation. diff --git a/cuda_core/cuda/core/_cpp/rt/DESIGN.md b/cuda_core/cuda/core/_cpp/rt/DESIGN.md index 2341aab388a2..5b342a1fae9c 100644 --- a/cuda_core/cuda/core/_cpp/rt/DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/DESIGN.md @@ -233,7 +233,8 @@ Two rules follow: 1. Do not make a `DRIVER_CALL` while the caller holds a C++ lock, because the fill acquires the GIL. Resolve the table before the lock (`ensure_fn_table(FnTable::driver)`) and use the raw pointer inside it, - marked `// raw:` (see `deviceptr_import_ipc`). + marked `// raw:` (see `deviceptr_import_ipc`, and `pin_primary_context` + under the primary-context table's mutex). 2. If the Cython layer gates a driver function, gate it at the version cuda-bindings requests it at (the number in the table), not at the version the driver first shipped it. @@ -317,7 +318,61 @@ that must update shared state before user code can run does so in `cleanup_in_context`'s `after_cleanup` hook, which runs once the cleanup is done and before anything that may run user code; the IPC pointer deleter releases its registry entry there. The registries store `weak_ptr`s, -so erasing an entry under a registry lock never runs a deleter. +so erasing an entry under a registry lock never runs a deleter. Releasing a +handle can, though: `HandleRegistry::insert_or_get` therefore destroys a +displaced handle only after it has unlocked, and a caller drops a losing +candidate outside the lock (REGISTRY_DESIGN.md). + +Resolving a context handle can call the driver and report a failure, so +`create_context_handle_ref()`, `create_current_context_handle_ref()`, +`get_current_context()` and everything that calls them, such as +`make_deallocation_stream()` for a default-stream token, must not run while a +C++ lock is held (see "Primary contexts"). `deviceptr_import_ipc` +resolves its deallocation stream before it takes the IPC pointer cache's mutex +for this reason. + +### Primary contexts + +`cuda.core` retains each device's primary context at most once per process and +never releases it, as the CUDA runtime does. The driver destroys a primary +context when its last retain is released, so code outside `cuda.core` +(`cuDevicePrimaryCtxReset`, `cudaDeviceReset`) is the only way a primary context +that `cuda.core` has handed out can go away. Before #1368 `cuda.core` already +behaved this way; #1368 released the retain when the last handle dropped, which +#3533 showed to be wrong. + +- `get_primary_context()` pins one retaining `ContextBox` per device in a + process-wide table (`pin_primary_context()` in `context.cpp`). The table is + leaked on purpose and holds a strong reference, so the box's deleter never + runs and its retain is never given back. The table is read without a lock: + pinning publishes a new immutable snapshot under the table's mutex, and old + snapshots are leaked, so a reader never sees freed memory. There is no + per-thread cache, so a thread's exit has no effect on primary contexts. The + mutex and the snapshot pointer are constant-initialized globals, not + function-local statics, so no static-initialization guard is involved (see + "Static Initialization and Deadlock Hazards"). +- `create_context_handle_ref()`, `create_current_context_handle_ref()` and + `get_current_context()` pin a primary context that another library made + current: when `ctx` is the calling thread's current context and its device's + active primary context, it is retained and pinned. All three go through + `resolve_context_handle()`; the last two are for callers that already know + what is current, so it is not queried again. Only the current context is + examined, because its device is the only one that can be queried without + switching contexts. An inactive primary context is never retained, because + that would create it. When the active primary context turns out to be + another one, the retain taken to find out is given back. That release cannot + destroy a context, because it was active without that retain. +- A context that is not current at the time of the lookup, such as another + context's stream or a graph node's update context, gets a plain handle that + does not keep it alive. +- The retain runs with the GIL released, under the table's mutex, through the + raw `p_` pointers after `ensure_fn_table()` (see "The GIL is the outermost + lock"). Giving back a probe retain can report a failure through Python, so it + runs after the mutex is released. +- Cython code gets a primary context through `Context_get_primary_handle()` + (a `ContextHandle`) or `Context_primary()` (a `Context`) in `_context.pyx`, + not by calling `get_primary_context()` directly. Both drain + `get_last_error()` and raise on failure, so every caller fails the same way. ### Static Initialization and Deadlock Hazards diff --git a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md index 2a9aa8ebf751..951ee75d4759 100644 --- a/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md +++ b/cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md @@ -15,7 +15,8 @@ together to map a raw driver handle all the way back to the original Python object. Both use weak references so they do not prevent cleanup. Entries are removed either explicitly (via `destroy()` or a Box destructor) or implicitly when the weak reference -expires. +expires. The one exception is a primary context's Box, which a separate table +pins for the life of the process (see "Removing and replacing entries"). ## Level 1: Driver Handle -> Resource Handle (C++) @@ -50,8 +51,9 @@ 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. +one, and nothing replaces an owning one. A primary context's retaining Box is +pinned for the life of the process (`pin_primary_context()` in `context.cpp`), +so all threads share it and its retain is never released. ### Imports that wait for an in-flight release diff --git a/cuda_core/cuda/core/_cpp/rt/api.hpp b/cuda_core/cuda/core/_cpp/rt/api.hpp index 97355aea4a8d..de227e4b04c0 100644 --- a/cuda_core/cuda/core/_cpp/rt/api.hpp +++ b/cuda_core/cuda/core/_cpp/rt/api.hpp @@ -16,9 +16,19 @@ namespace cuda_core::rt { // Context handle functions // ============================================================================ -// Function to create a non-owning context handle (references existing context). +// Return a handle for an existing context: the registered handle if there is +// one. A primary context that is the calling thread's current context is +// retained and pinned for the life of the process (see get_primary_context). +// Any other context gets a handle that does not keep it alive. May call the +// driver and report a failure, which acquires the GIL: do not call it while +// holding a C++ lock. ContextHandle create_context_handle_ref(CUcontext ctx); +// As create_context_handle_ref, for a caller that knows that ctx is the calling +// thread's current context and that its device is `device`, so that neither is +// queried again. +ContextHandle create_current_context_handle_ref(CUcontext ctx, CUdevice device); + // Create a context handle for the CUcontext view of the provided green context. // The returned ContextHandle keeps the green context alive, but the CUcontext // view is non-owning and is not destroyed independently. @@ -35,12 +45,14 @@ GreenCtxHandle create_green_ctx_handle( // Create a non-owning green context handle. GreenCtxHandle create_green_ctx_handle_ref(CUgreenCtx ctx); -// Get handle to the primary context for a device (with thread-local caching) -// Returns empty handle on error (caller must check) +// Get handle to the primary context for a device. +// cuda.core retains each primary context at most once per process and never +// releases it. Returns empty handle on error (caller must check) ContextHandle get_primary_context(int device_id); -// Get handle to the current CUDA context -// Returns empty handle if no context is current (caller must check) +// Get handle to the current CUDA context, as create_context_handle_ref does; +// the same rules apply. Returns empty handle if no context is current (caller +// must check) ContextHandle get_current_context(); // Synchronize the provided context. Releases the GIL around the driver call. diff --git a/cuda_core/cuda/core/_cpp/rt/context.cpp b/cuda_core/cuda/core/_cpp/rt/context.cpp index d9f78ac044bd..25dcca4e2f7a 100644 --- a/cuda_core/cuda/core/_cpp/rt/context.cpp +++ b/cuda_core/cuda/core/_cpp/rt/context.cpp @@ -8,8 +8,10 @@ #include "driver_api.hpp" #include "error.hpp" #include "internal.hpp" +#include #include #include +#include #include #include @@ -119,7 +121,7 @@ namespace { struct ContextBox { CUcontext resource; GreenCtxHandle h_green_ctx; - bool retains_primary = false; // Owns one cuDevicePrimaryCtxRetain. + bool retains_primary = false; // Pinned primary context (see pin_primary_context). }; struct GreenCtxBox { @@ -136,7 +138,7 @@ 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 +// A box keeps its context alive if it is a pinned primary context or holds the // owning green-context handle. Reads only immutable box fields, so it is safe // under the registry's mutex. bool @@ -157,31 +159,245 @@ replace_if_upgrade(const ContextHandle &candidate) noexcept }; } -// Create a context handle reference, with optional green context as source. +// Box ctx in a new handle, which the caller registers. The deleter erases the +// box's registry entry if it is still the registered one. It releases nothing: +// a plain box owns nothing, a green box releases its context through +// h_green_ctx, and a pinned primary box is never deleted (its retain is +// deliberately never released). ContextHandle -create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx) +make_context_handle(CUcontext ctx, GreenCtxHandle h_green_ctx, bool retains_primary) { - if (!ctx) { - return {}; - } - if (auto h = context_registry.lookup(ctx)) { - // 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)}, + new ContextBox{ctx, std::move(h_green_ctx), retains_primary}, [](const ContextBox *b) { context_registry.unregister_handle(b->resource, &b->resource); delete b; } ); // clang-format on - ContextHandle candidate(box, &box->resource); + return ContextHandle(box, &box->resource); +} + +// ---------------------------------------------------------------------------- +// Primary contexts +// +// cuda.core retains each device's primary context at most once per process and +// never gives that retain back, as the CUDA runtime does. The driver destroys +// a primary context when its last retain is released, so a context that +// cuda.core has handed out can only be destroyed by code outside cuda.core +// (cuDevicePrimaryCtxReset, cudaDeviceReset). +// +// The retain is held by one box per device, pinned in a process-wide table +// that is never freed: no thread's exit and no handle's release can drop the +// box's last reference, so its deleter never runs. +// +// The table is read without a lock. It is published as immutable snapshots: +// pinning a context, under primary_context_mutex, publishes a copy of the +// current snapshot with one more entry. Snapshots and the handles they point +// to are leaked, so a reader never sees freed memory, and other threads may +// still use them while the process exits. At most one snapshot is published +// per device. +// ---------------------------------------------------------------------------- + +struct PinnedPrimaryContexts { + std::vector slots; // indexed by device ordinal +}; + +std::mutex primary_context_mutex; // serializes pinning +std::atomic pinned_primary_contexts{nullptr}; + +// Return the pinned primary context of device ordinal idx, or an empty handle. +ContextHandle +find_pinned_primary_context(size_t idx) noexcept +{ + const PinnedPrimaryContexts *pinned = pinned_primary_contexts.load(std::memory_order_acquire); + if (pinned && idx < pinned->slots.size() && pinned->slots[idx]) { + return *pinned->slots[idx]; + } + return {}; +} + +// Publish h as the pinned primary context of device ordinal idx. The caller +// holds primary_context_mutex, so no other snapshot is published meanwhile. +void +publish_pinned_primary_context(size_t idx, const ContextHandle &h) +{ + // The previous store was made under the same mutex, so a relaxed load sees it. + const PinnedPrimaryContexts *current = pinned_primary_contexts.load(std::memory_order_relaxed); + // Both allocations are leaked on purpose (see above). + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) + auto *next = new PinnedPrimaryContexts{current ? current->slots : std::vector{}}; + if (idx >= next->slots.size()) { + next->slots.resize(idx + 1, nullptr); + } + next->slots[idx] = new ContextHandle(h); // NOLINT(cppcoreguidelines-owning-memory) + pinned_primary_contexts.store(next, std::memory_order_release); +} + +// Return the pinned primary context of device_id, pinning it first if needed. +// +// With expected == nullptr, retain the device's primary context (creating it +// if it is not active) and pin it. On failure, return an empty handle and +// store the status in *status. +// +// With expected != nullptr, pin and return the primary context only if it is +// active and is `expected`; otherwise return an empty handle. A primary +// context that is not active is not retained, because that would create it. If +// the active primary context is another one, the retain taken to learn its +// address is given back: the context was active without it, so that release +// cannot destroy a context that its other owners still hold. +ContextHandle +pin_primary_context(int device_id, CUcontext expected, CUresult *status) +{ + *status = CUDA_SUCCESS; + const auto idx = static_cast(device_id); + auto pinned_result = [expected](ContextHandle pinned) -> ContextHandle { + if (expected && as_cu(pinned) != expected) { + return {}; + } + return pinned; + }; + if (ContextHandle pinned = find_pinned_primary_context(idx)) { + return pinned_result(std::move(pinned)); + } + + // The GIL is the outermost lock, and filling the table acquires it: do both + // before the mutex is taken. The raw p_ calls below rely on the fill. + GILReleaseGuard gil; + if (!ensure_fn_table(FnTable::driver)) { + report_unavailable_fn(FnTable::driver, "cuDevicePrimaryCtxRetain"); + *status = CUDA_ERROR_NOT_INITIALIZED; + return {}; + } + + ContextHandle h; + bool release_probe = false; + { + std::scoped_lock lock(primary_context_mutex); + // Another thread may have pinned it since the check above. + if (ContextHandle pinned = find_pinned_primary_context(idx)) { + return pinned_result(std::move(pinned)); + } + if (expected) { + unsigned int flags = 0; + int active = 0; + *status = p_cuDevicePrimaryCtxGetState(device_id, &flags, &active); // raw: under primary_context_mutex + if (*status != CUDA_SUCCESS || !active) { + return {}; + } + } + CUcontext ctx = nullptr; + *status = p_cuDevicePrimaryCtxRetain(&ctx, device_id); // raw: under primary_context_mutex + if (*status != CUDA_SUCCESS) { + return {}; + } + if (expected && ctx != expected) { + release_probe = true; + } + else { + h = make_context_handle(ctx, {}, true); + publish_pinned_primary_context(idx, h); + } + } + if (release_probe) { + // Reports through Python on failure, so it runs after the unlock. + pw_cuDevicePrimaryCtxRelease(device_id); + return {}; + } + // The driver has just returned this address as the device's primary + // context, so a live entry under it is a plain box or a stale one: replace + // it. Registering after the unlock keeps a displaced box's deleter out of + // primary_context_mutex. A lookup that misses the registry in between finds + // the box in the table (see resolve_context_handle). + context_registry.insert_or_get(as_cu(h), h, [](const ContextHandle &) noexcept { return true; }); + return h; +} + +// A lookup falls back to a handle that holds no retain, and its callers do not +// check for an error, so each failure while adopting a primary context is +// reported. +constexpr const char *adopt_failure_detail = "failed while looking up the current context"; + +// ctx is the calling thread's current context, on `device`. If it is that +// device's primary context, pin it and return the pinned handle; otherwise +// return an empty handle. +ContextHandle +adopt_primary_context(CUcontext ctx, CUdevice device) +{ + CUresult status = CUDA_SUCCESS; + ContextHandle h = pin_primary_context(static_cast(device), ctx, &status); + if (status != CUDA_SUCCESS) { + report_cuda_error("cuDevicePrimaryCtxRetain", status, adopt_failure_detail); + } + return h; +} + +// ctx is the calling thread's current context: query its device and adopt it. +ContextHandle +adopt_current_context(CUcontext ctx) +{ + GILReleaseGuard gil; + CUdevice device = 0; + CUresult status = DRIVER_CALL(cuCtxGetDevice, &device); + if (status != CUDA_SUCCESS) { + report_cuda_error("cuCtxGetDevice", status, adopt_failure_detail); + return {}; + } + return adopt_primary_context(ctx, device); +} + +// Adopt ctx if it is the calling thread's current context. Only the current +// context is examined, because its device can be queried without switching +// contexts, which a lookup must not do. +ContextHandle +adopt_if_current(CUcontext ctx) +{ + GILReleaseGuard gil; + CUcontext current = nullptr; + CUresult status = DRIVER_CALL(cuCtxGetCurrent, ¤t); + if (status != CUDA_SUCCESS) { + report_cuda_error("cuCtxGetCurrent", status, adopt_failure_detail); + return {}; + } + if (current != ctx) { + return {}; + } + return adopt_current_context(ctx); +} + +// Return the handle for ctx, with an optional owning green context as source. +// +// adopt() returns the pinned handle if ctx is a primary context that cuda.core +// has not retained yet, for example one made current by another library, and +// an empty handle otherwise. It runs only for a plain lookup (no h_green_ctx) +// that finds no owning entry, so callers that know what is current pass what +// they know instead of querying the driver again. +template +ContextHandle +resolve_context_handle(CUcontext ctx, GreenCtxHandle h_green_ctx, Adopt &&adopt) +{ + if (!ctx) { + return {}; + } + ContextHandle registered = context_registry.lookup(ctx); + // An owning entry for ctx is either this green context's own box or a + // pinned primary context. A green context cannot share a live primary + // context's CUcontext, so returning it never drops a needed green owner. + if (registered && owns_context(registered)) { + return registered; + } + if (!h_green_ctx) { + // Pin a primary context, so that the handle keeps it alive like every + // other primary-context handle. + if (ContextHandle h = adopt()) { + return h; + } + if (registered) { + return registered; + } + } + ContextHandle candidate = make_context_handle(ctx, std::move(h_green_ctx), false); // A losing candidate is dropped by the caller, outside the registry's lock; // its deleter's ownership-checked erase is then a no-op. return context_registry.insert_or_get(ctx, candidate, replace_if_upgrade(candidate)); @@ -191,7 +407,13 @@ create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx) ContextHandle create_context_handle_ref(CUcontext ctx) { - return create_context_handle_ref(ctx, {}); + return resolve_context_handle(ctx, {}, [ctx] { return adopt_if_current(ctx); }); +} + +ContextHandle +create_current_context_handle_ref(CUcontext ctx, CUdevice device) +{ + return resolve_context_handle(ctx, {}, [ctx, device] { return adopt_primary_context(ctx, device); }); } ContextHandle @@ -206,7 +428,7 @@ create_context_handle_from_green_ctx(const GreenCtxHandle &h_green_ctx) return {}; } - return create_context_handle_ref(ctx, h_green_ctx); + return resolve_context_handle(ctx, h_green_ctx, [] { return ContextHandle{}; }); } GreenCtxHandle @@ -255,89 +477,15 @@ 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. -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 (use_cache && idx < primary_context_cache.entries.size()) { - if (auto cached = primary_context_cache.entries[idx]) { - return cached; - } - } - - // Cache miss - acquire primary context from driver - GILReleaseGuard gil; - CUcontext ctx; - if (CUDA_SUCCESS != (err = DRIVER_CALL(cuDevicePrimaryCtxRetain, &ctx, device_id))) { - return {}; - } - - // clang-format off - auto box = std::shared_ptr( - new ContextBox{ctx, {}, true}, - [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); - } - delete b; - } - ); - // clang-format on - 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 (use_cache) { - if (idx >= primary_context_cache.entries.size()) { - primary_context_cache.entries.resize(idx + 1); - } - primary_context_cache.entries[idx] = h; + // The common case: the context is pinned already. Leave the thread's last + // error untouched, as any other lookup that succeeds does. + if (ContextHandle h = find_pinned_primary_context(static_cast(device_id))) { + return h; } - return h; + return pin_primary_context(device_id, nullptr, &err); } ContextHandle @@ -351,7 +499,7 @@ get_current_context() if (!ctx) { return {}; // No current context (not an error) } - return create_context_handle_ref(ctx); + return resolve_context_handle(ctx, {}, [ctx] { return adopt_current_context(ctx); }); } } // namespace cuda_core::rt diff --git a/cuda_core/cuda/core/_cpp/rt/driver_api.hpp b/cuda_core/cuda/core/_cpp/rt/driver_api.hpp index 1d13cd016485..1fa95ccf0137 100644 --- a/cuda_core/cuda/core/_cpp/rt/driver_api.hpp +++ b/cuda_core/cuda/core/_cpp/rt/driver_api.hpp @@ -58,6 +58,7 @@ namespace cuda_core::rt { X(cuGetErrorString, 6000) \ /* Context */ \ X(cuDevicePrimaryCtxRetain, 7000) \ + X(cuDevicePrimaryCtxGetState, 7000) \ X(cuDevicePrimaryCtxRelease, 11000) \ X(cuCtxGetCurrent, 4000) \ X(cuCtxSetCurrent, 4000) \ diff --git a/cuda_core/cuda/core/_cpp/rt/internal.hpp b/cuda_core/cuda/core/_cpp/rt/internal.hpp index b30b0ea4fab3..0bc0c5439059 100644 --- a/cuda_core/cuda/core/_cpp/rt/internal.hpp +++ b/cuda_core/cuda/core/_cpp/rt/internal.hpp @@ -342,6 +342,16 @@ class ReleasingHandleRegistry { return h; } + // Return the live handle registered under key, or an empty handle. Unlike + // get_or_create(), it never waits for a release in flight, so a caller that + // gets nothing goes on to get_or_create(). + Handle + find_live(const Key &key) + { + std::unique_lock lock(mutex_); + return find(lock, key).owner; + } + // Called by an owner's deleter after its last driver call on the resource: // erase key's entry if it belongs to the handle that pointed to resource, // and wake the importers waiting for it. diff --git a/cuda_core/cuda/core/_cpp/rt/memory.cpp b/cuda_core/cuda/core/_cpp/rt/memory.cpp index 395b60fd1079..12ae4305e819 100644 --- a/cuda_core/cuda/core/_cpp/rt/memory.cpp +++ b/cuda_core/cuda/core/_cpp/rt/memory.cpp @@ -497,12 +497,31 @@ deviceptr_import_ipc(const MemoryPoolHandle &h_pool, const void *export_data, co // on it while holding the GIL would deadlock with a holder that needs // the GIL back (#2840). GILReleaseGuard gil; + // A repeat import keeps the cached mapping's deallocation stream, so + // return it before one is resolved for this call: resolving may pin a + // primary context or report a failure for a stream that is never used. + if (DevicePtrHandle cached = ipc_ptr_cache.find_live(key)) { + return cached; + } // Allocate before taking the mutex: a failed allocation then cannot run // a deleter under it. The box owns nothing until it holds an import. auto box = std::shared_ptr(new DevicePtrBox{0, DeallocationStream{}}, DeleteIpcPtrBox{h_pool, key}); DevicePtrHandle h(box, &box->resource); + // Resolve the deallocation stream before the mutex is taken: for a + // default-stream token it looks up the current context, which may pin a + // primary context and report a failure (get_current_context). + // Only a fresh import uses it, so a failure is kept for that path. An + // import that was cached by a concurrent call since the lookup above + // still resolves it, and gets the cached mapping. May throw + // std::bad_alloc; nothing has been imported yet. + DeallocationStream ds; + const CUresult status_before = err; + const bool ds_ok = make_deallocation_stream(h_stream, ds); + const CUresult ds_status = err; + err = status_before; + // The factory runs under the cache's mutex, which makes lookup, import // and registration one step: two threads cannot import the same // descriptor twice. It therefore calls the driver through the raw p_ @@ -516,21 +535,16 @@ deviceptr_import_ipc(const MemoryPoolHandle &h_pool, const void *export_data, co (err = p_cuMemPoolImportPointer(&ptr, *h_pool, data))) { // raw: under the cache's mutex return {}; } - // Without a recorded deallocation stream the import is - // discarded before the mutex is released, or a concurrent - // import would share the mapping this free unmaps. - bool recorded = false; - try { - recorded = make_deallocation_stream(h_stream, box->deallocation); - } - catch (...) { - discarded = DiscardedIpcImport::discard(ptr, h_stream); - throw; - } - if (!recorded) { + // No deallocation stream could be recorded: discard the import + // before the mutex is released, or a concurrent import would + // share the mapping this free unmaps. + if (!ds_ok) { + err = ds_status; discarded = DiscardedIpcImport::discard(ptr, h_stream); return {}; } + // Moves two handles; no deleter runs under the mutex. + box->deallocation = std::move(ds); box->resource = ptr; return h; }); diff --git a/cuda_core/cuda/core/_device.pyx b/cuda_core/cuda/core/_device.pyx index 5ce22959e985..e1293b51fb29 100644 --- a/cuda_core/cuda/core/_device.pyx +++ b/cuda_core/cuda/core/_device.pyx @@ -12,7 +12,7 @@ from libcpp.vector cimport vector import threading -from cuda.core._context cimport Context, Context_check_open +from cuda.core._context cimport Context, Context_check_open, Context_primary from cuda.core._context import ContextOptions from cuda.core._device_resources cimport DeviceResources, SMResource, WorkqueueResource from cuda.core._event cimport Event as cyEvent @@ -21,10 +21,9 @@ from cuda.core._memory._buffer cimport Buffer, MemoryResource from cuda.core._rt cimport ( ContextHandle, GreenCtxHandle, - create_context_handle_ref, + create_current_context_handle_ref, create_green_ctx_handle, context_synchronize, - get_primary_context, get_last_error, as_cu, ) @@ -1292,6 +1291,7 @@ class Device: cdef cydriver.CUcontext prev_ctx, curr_ctx cdef cydriver.CUdevice prev_dev cdef Context prev_owned = None + cdef Context primary if ctx is not None: Context_check_open(ctx) @@ -1309,6 +1309,11 @@ class Device: HANDLE_RETURN(cydriver.cuCtxGetCurrent(&prev_ctx)) if prev_ctx != NULL: HANDLE_RETURN(cydriver.cuCtxGetDevice(&prev_dev)) + # Resolve the previous context while it is still current: + # only then is a primary context that cuda.core has not + # retained yet pinned, so that the returned Context keeps + # it alive. + h_context = create_current_context_handle_ref(prev_ctx, prev_dev) # cuCtxSetCurrent replaces the top of the thread's context stack # in one driver call (or binds ctx when nothing is current), so # a failure leaves the previous context current instead of @@ -1318,22 +1323,20 @@ class Device: self._has_inited = True self._context = ctx # Store owning context reference if prev_ctx != NULL: - if prev_owned is not None and as_cu(prev_owned._h_context) == prev_ctx: + # Reuse this device's Context object only if it holds the handle + # just resolved. Comparing CUcontext addresses is not enough: the + # driver reuses the address of a destroyed context, and a stale + # object for it would hide the live context's owning handle. + if prev_owned is not None and prev_owned._h_context.get() == h_context.get(): return prev_owned - return Context._from_handle( - Context, create_context_handle_ref(prev_ctx), prev_dev) + return Context._from_handle(Context, h_context, prev_dev) else: # use primary ctx - h_context = get_primary_context(self._device_id) - if h_context.get() == NULL: - HANDLE_RETURN(get_last_error()) - raise RuntimeError( - f"Failed to retain the primary context for device {self._device_id}" - ) + primary = Context_primary(self._device_id) with nogil: - HANDLE_RETURN(cydriver.cuCtxSetCurrent(as_cu(h_context))) + HANDLE_RETURN(cydriver.cuCtxSetCurrent(as_cu(primary._h_context))) self._has_inited = True - self._context = Context._from_handle(Context, h_context, self._device_id) # Store owning context + self._context = primary # Store owning context def create_context(self, options: ContextOptions | None = None) -> Context: """Create a new :obj:`~_context.Context` object. diff --git a/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx b/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx index e54387976646..9c6a207e0df9 100644 --- a/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_synchronous_memory_resource.pyx @@ -7,14 +7,11 @@ from __future__ import annotations from libc.stdint cimport uintptr_t from cuda.bindings cimport cydriver -from cuda.core._context cimport Context +from cuda.core._context cimport Context, Context_primary from cuda.core._memory._buffer cimport Buffer, MemoryResource from cuda.core._rt cimport ( - ContextHandle, create_context_bound_legacy_stream, deviceptr_alloc_raw, - get_last_error, - get_primary_context, ) from cuda.core._stream cimport Stream, Stream_accept, Stream_is_default_token from cuda.core._utils.cuda_utils cimport HANDLE_RETURN @@ -41,13 +38,8 @@ class _SynchronousMemoryResource(MemoryResource): self._context = context def _resolve_context(self) -> Context: - cdef ContextHandle h_context if self._context is None: - h_context = get_primary_context(self._device_id) - if not h_context: - HANDLE_RETURN(get_last_error()) - self._context = Context._from_handle( - Context, h_context, self._device_id) + self._context = Context_primary(self._device_id) return self._context def allocate( diff --git a/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx b/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx index db6bae19fb56..43b72e324a51 100644 --- a/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx +++ b/cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx @@ -10,6 +10,7 @@ from libcpp.vector cimport vector cimport cpython from cuda.bindings cimport cydriver +from cuda.core._context cimport Context_get_primary_handle from cuda.core._memory._buffer cimport ( Buffer, Buffer_check_open, @@ -40,7 +41,6 @@ from cuda.core._rt cimport ( deallocation_stream, deviceptr_create_vmm, get_last_error, - get_primary_context, import_mem_allocation_handle, mem_allocation_is_imported, mem_allocation_size, @@ -656,10 +656,9 @@ cdef class VirtualMemoryResource(MemoryResource): # Bind the legacy default-stream token to the device's primary # context so the free is ordered correctly no matter what is current # then, and so allocate() never depends on a current context. - # get_primary_context keeps its own cache; nothing is cached here. - h_ctx = get_primary_context(self.device.device_id) - if not h_ctx: - _raise_last_error() + # The primary context is pinned for the life of the process; + # nothing is cached here. + Context_get_primary_handle(self.device.device_id, &h_ctx) h = create_context_bound_legacy_stream(h_ctx) if not h: _raise_last_error() diff --git a/cuda_core/cuda/core/_rt.pxd b/cuda_core/cuda/core/_rt.pxd index b67c66db9b3d..2566c75f42f6 100644 --- a/cuda_core/cuda/core/_rt.pxd +++ b/cuda_core/cuda/core/_rt.pxd @@ -216,6 +216,8 @@ cdef void clear_last_error_detail() noexcept nogil # Context handles cdef ContextHandle create_context_handle_ref(cydriver.CUcontext ctx) except+ nogil +cdef ContextHandle create_current_context_handle_ref( + cydriver.CUcontext ctx, cydriver.CUdevice device) except+ nogil cdef ContextHandle create_context_handle_from_green_ctx(const GreenCtxHandle& h_green_ctx) except+ nogil cdef GreenCtxHandle get_context_green_ctx(const ContextHandle& h) noexcept nogil cdef GreenCtxHandle create_green_ctx_handle( diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index 6511643edb52..b8b9f892e5e2 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -71,6 +71,8 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": # Context handles ContextHandle create_context_handle_ref "cuda_core::rt::create_context_handle_ref" ( cydriver.CUcontext ctx) except+ nogil + ContextHandle create_current_context_handle_ref "cuda_core::rt::create_current_context_handle_ref" ( + cydriver.CUcontext ctx, cydriver.CUdevice device) except+ nogil ContextHandle create_context_handle_from_green_ctx "cuda_core::rt::create_context_handle_from_green_ctx" ( const GreenCtxHandle& h_green_ctx) except+ nogil GreenCtxHandle get_context_green_ctx "cuda_core::rt::get_context_green_ctx" ( diff --git a/cuda_core/docs/source/release/1.4.0-notes.rst b/cuda_core/docs/source/release/1.4.0-notes.rst index 4998ad503cc9..a590333782f9 100644 --- a/cuda_core/docs/source/release/1.4.0-notes.rst +++ b/cuda_core/docs/source/release/1.4.0-notes.rst @@ -60,19 +60,28 @@ Fixes and enhancements before. (`#3502 `__) -- A :class:`Context`, :class:`Stream` or :class:`Event` no longer fails with +- ``cuda.core`` again retains each device's primary context at most once per + process and never releases it, as the CUDA runtime does and as + ``cuda.core`` did before 0.6.0. Since 0.6.0 it released its retains when + the last object holding them was released, so the driver could destroy a + primary context that the application still used. In particular, a + :class:`Context`, :class:`Stream` or :class:`Event` could fail with ``CUDA_ERROR_CONTEXT_IS_DESTROYED`` after other threads that used the same - device exit. Each thread that called :meth:`Device.set_current` retained + device exited: each thread that called :meth:`Device.set_current` retained the primary context separately, and a thread's exit could leave later lookups, such as :meth:`Stream.from_handle` or recording an event on - :attr:`Device.default_stream`, with a :class:`Context` that held no - retain. 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. + :attr:`Device.default_stream`, with a :class:`Context` that held no retain. + (`#3533 `__) + +- A :class:`Context` that ``cuda.core`` resolves for the calling thread's + current context now also keeps a primary context alive that another + library made current, for example the context of + ``Stream.from_handle(...)`` for a default stream, or the previous context + returned by :meth:`Device.set_current`. A :class:`Context` resolved for a + context that is not current at the time, for example the context of + another context's stream or a graph node's update context, still holds no + retain if ``cuda.core`` has not retained that primary context, and stays + valid only as long as the context's owner keeps it alive. (`#3533 `__) - :meth:`Device.create_context` no longer returns a context with @@ -81,7 +90,3 @@ Fixes and enhancements :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/helpers/contexts.py b/cuda_core/tests/helpers/contexts.py index d1e73de926a3..625f561da294 100644 --- a/cuda_core/tests/helpers/contexts.py +++ b/cuda_core/tests/helpers/contexts.py @@ -12,6 +12,7 @@ "assert_no_cuda_warning", "current_context_handle", "no_current_context", + "primary_context_active", "use_context", ] @@ -36,6 +37,12 @@ def current_context_handle(): return int(handle_return(driver.cuCtxGetCurrent())) +def primary_context_active(device_id): + """Return whether the primary context of ``device_id`` is active (retained).""" + _, active = handle_return(driver.cuDevicePrimaryCtxGetState(device_id)) + return bool(active) + + def _assert_event_record_rejected_from_ambient_context(event): """Assert that recording ``event`` into a stream from the ambient context fails. diff --git a/cuda_core/tests/test_context.py b/cuda_core/tests/test_context.py index 0ade0d5fd909..4800fb3b1bc8 100644 --- a/cuda_core/tests/test_context.py +++ b/cuda_core/tests/test_context.py @@ -4,11 +4,11 @@ import gc import threading import time -from concurrent.futures import ThreadPoolExecutor import pytest -from helpers.child_processes import run_child -from helpers.contexts import assert_no_cuda_warning +from helpers.child_processes import child_timeout_sec, run_child +from helpers.contexts import assert_no_cuda_warning, primary_context_active +from helpers.misc import run_in_threads import cuda.core from cuda.bindings import driver @@ -101,123 +101,83 @@ def test_context_dict_key(init_cuda): # ============================================================================ -# Primary-context lifetime across threads (#3533) +# Primary-context lifetime (#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. +# Each test runs in a fresh child process, so nothing else holds a retain of the +# primary context: the pytest process does, through fixtures, which would hide +# a released or leaked retain. -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. +# Several threads retain the primary context concurrently, after which every +# thread exits and every Context is dropped. cuda.core keeps exactly one retain +# of the primary context for the rest of the process: the context stays active, +# and releasing one retain from outside cuda.core leaves no retain behind. This +# covers the cause of #3533: on releasing code, the primary context is inactive +# here. def _concurrent_primary_retains_child(device_id): num_threads = 8 barrier = threading.Barrier(num_threads) + contexts = [] - def worker(_): + 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))) - - held = contexts[0] + run_in_threads([worker] * num_threads, barrier=barrier, timeout=child_timeout_sec()) + assert len(contexts) == num_threads + assert len({int(ctx.handle) for ctx in contexts}) == 1 contexts.clear() gc.collect() - assert _primary_active(device_id), "primary context destroyed while a Context is held" + # Thread.join() can return before a thread's C++ thread_local + # destructors run, and they cannot be observed, so wait a fixed second. + # A release at thread exit would make the next check fail. + time.sleep(1.0) + assert primary_context_active(device_id), "cuda.core released its primary-context retain" - 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" + # This process has no other retain of the primary context, so one + # release must leave it inactive: cuda.core held exactly one retain. + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + assert not primary_context_active(device_id), "cuda.core holds more than one primary-context retain" -@pytest.mark.agent_authored(model="claude-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-fable-5-2") +def test_concurrent_set_current_keeps_one_primary_retain(init_cuda): + """Concurrent Device.set_current() calls take one primary-context retain, which cuda.core never releases.""" run_child(_concurrent_primary_retains_child, init_cuda.device_id) + + +# Another owner (here cuda.bindings, standing in for another library) retains the +# primary context and makes it current, and cuda.core has not retained it. An +# Event recorded on the legacy default stream and that stream's Context, both +# resolved for the current context, must keep it alive once that owner releases +# its retain. Both resolve through the same lookup; the first one pins the +# primary context, and the second finds it registered. +def _foreign_primary_context_child(device_id): + handle_return(driver.cuInit(0)) + with assert_no_cuda_warning(): + assert not primary_context_active(device_id) + primary = handle_return(driver.cuDevicePrimaryCtxRetain(device_id)) + handle_return(driver.cuCtxSetCurrent(primary)) + legacy = Stream.from_handle(int(driver.CU_STREAM_LEGACY)) + event = legacy.record() + ctx = legacy.context + handle_return(driver.cuCtxSetCurrent(None)) + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + + assert primary_context_active(device_id), ( + "primary context destroyed while a cuda.core object still refers to it" + ) + event.sync() + dev = Device(device_id) + dev.set_current(ctx) + dev.create_stream().sync() + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_lookup_retains_foreign_primary_context(init_cuda): + """A Context resolved for a primary context that another owner made current keeps it alive.""" + run_child(_foreign_primary_context_child, init_cuda.device_id) diff --git a/cuda_core/tests/test_green_context.py b/cuda_core/tests/test_green_context.py index dc9853527889..9ba6bdf4dcb1 100644 --- a/cuda_core/tests/test_green_context.py +++ b/cuda_core/tests/test_green_context.py @@ -4,10 +4,18 @@ import numpy as np import pytest -from helpers.contexts import assert_device_operations_use_bound_context, current_context_handle, use_context +from helpers.child_processes import run_child +from helpers.contexts import ( + assert_device_operations_use_bound_context, + assert_no_cuda_warning, + current_context_handle, + primary_context_active, + use_context, +) from cuda.core import ( ContextOptions, + Device, DeviceResources, LaunchConfig, LegacyPinnedMemoryResource, @@ -15,11 +23,11 @@ ProgramOptions, SMResource, SMResourceOptions, + Stream, WorkqueueResource, 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 +287,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 @@ -307,6 +319,117 @@ def test_green_context_replaces_stale_plain_entry(init_cuda, sm_resource): green.close() +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_set_current_returns_live_context_after_address_reuse(init_cuda, sm_resource): + """set_current() returns the live green context, not the Device's stale + Context for a destroyed context at the same CUcontext address.""" + dev = init_cuda + primary = dev.context + groups, _ = sm_resource.split(SMResourceOptions(count=None)) + opts = ContextOptions(resources=[groups[0]]) + res = handle_return(driver.cuDeviceGetDevResource(dev.device_id, driver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM)) + desc = handle_return(driver.cuDevResourceGenerateDesc([res], 1)) + flags = driver.CUgreenCtxCreate_flags.CU_GREEN_CTX_DEFAULT_STREAM + + # Make the Device remember a plain Context for a context that cuda.core did + # not create, destroy that context, and retry until the driver reuses its + # CUcontext address for a green context that cuda.core owns. + green = None + try: + for _ in range(20): + foreign = handle_return(driver.cuGreenCtxCreate(desc, dev.device_id, flags)) + try: + handle_return(driver.cuCtxSetCurrent(handle_return(driver.cuCtxFromGreenCtx(foreign)))) + stale = dev.set_current(primary) + dev.set_current(stale) # the Device now remembers stale + finally: + # Behind the Device's back, so that it keeps remembering stale. + handle_return(driver.cuCtxSetCurrent(primary.handle)) + handle_return(driver.cuGreenCtxDestroy(foreign)) + assert not stale.is_green + green = dev.create_context(opts) + if int(green.handle) == int(stale.handle): + break + green.close() + green = None + else: + pytest.skip("driver did not reuse the destroyed context's CUcontext address") + + handle_return(driver.cuCtxSetCurrent(green.handle)) + previous = dev.set_current(primary) + # Context equality compares raw CUcontext values, so compare identity + # and ownership instead. + assert previous is not stale + assert previous.is_green + finally: + # A skip or a failure above leaves the Device remembering stale, which + # the init_cuda teardown would then synchronize: rebind it. + dev.set_current(primary) + if green is not None: + green.close() + + +# The driver holds a retain of the primary context while any green context of +# the device exists. The tests below therefore check the primary context's state +# only after their green contexts are destroyed, and run in a fresh child +# process, because the pytest process already retains the primary context. + + +# Another owner (here cuda.bindings, standing in for another library) retains the +# primary context and makes it current, and cuda.core has not retained it. +# Device.set_current(green) then returns the previous context, which must keep +# the primary context alive once that owner releases its retain. +def _set_current_returns_foreign_primary_child(device_id): + handle_return(driver.cuInit(0)) + dev = Device(device_id) + with assert_no_cuda_warning(): + groups, _ = dev.resources.sm.split(SMResourceOptions(count=None)) + green = dev.create_context(ContextOptions(resources=[groups[0]])) + + primary = handle_return(driver.cuDevicePrimaryCtxRetain(device_id)) + handle_return(driver.cuCtxSetCurrent(primary)) + previous = dev.set_current(green) + assert not previous.is_green + assert int(previous.handle) == int(primary) + + dev.set_current(previous) + green.close() + handle_return(driver.cuDevicePrimaryCtxRelease(device_id)) + assert primary_context_active(device_id), "primary context destroyed while the previous Context is held" + dev.create_stream().sync() + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_set_current_previous_context_retains_foreign_primary(init_cuda, green_ctx): + """The previous Context returned by Device.set_current(green) keeps a foreign primary context alive.""" + # green_ctx skips the test where green contexts cannot be created. + run_child(_set_current_returns_foreign_primary_child, init_cuda.device_id) + + +# A plain lookup of a context that is current but is not a primary context must +# not keep a retain of the device's primary context. +def _lookup_green_does_not_retain_primary_child(device_id): + handle_return(driver.cuInit(0)) + with assert_no_cuda_warning(): + res = handle_return(driver.cuDeviceGetDevResource(device_id, driver.CUdevResourceType.CU_DEV_RESOURCE_TYPE_SM)) + desc = handle_return(driver.cuDevResourceGenerateDesc([res], 1)) + flags = driver.CUgreenCtxCreate_flags.CU_GREEN_CTX_DEFAULT_STREAM + foreign = handle_return(driver.cuGreenCtxCreate(desc, device_id, flags)) + handle_return(driver.cuCtxSetCurrent(handle_return(driver.cuCtxFromGreenCtx(foreign)))) + ctx = Stream.from_handle(int(driver.CU_STREAM_LEGACY)).context + assert not ctx.is_green + handle_return(driver.cuCtxSetCurrent(None)) + del ctx + handle_return(driver.cuGreenCtxDestroy(foreign)) + assert not primary_context_active(device_id), "a lookup of a green context kept a primary-context retain" + + +@pytest.mark.agent_authored(model="claude-fable-5-2") +def test_green_context_lookup_does_not_retain_primary(init_cuda, green_ctx): + """Looking up a current green context leaves no primary-context retain behind.""" + run_child(_lookup_green_does_not_retain_primary_child, init_cuda.device_id) + + # --------------------------------------------------------------------------- # SM resource query # --------------------------------------------------------------------------- diff --git a/cuda_core/tests/test_rt_layout.py b/cuda_core/tests/test_rt_layout.py index 29f6fc59da71..2a5d7861b122 100644 --- a/cuda_core/tests/test_rt_layout.py +++ b/cuda_core/tests/test_rt_layout.py @@ -138,8 +138,9 @@ def test_driver_function_table_matches_the_cuda_bindings_loader(): def test_driver_calls_go_through_the_table(): """Every driver call uses DRIVER_CALL or a pw_ wrapper, which resolves the table on first use and never dereferences null. The only raw p_ calls are - the table's own machinery and the sites under the IPC pointer cache's mutex. Those sites - resolve the table before the lock and carry the `// raw:` mark.""" + the table's own machinery and the sites under the IPC pointer cache's mutex + and the primary-context table's mutex. Those sites resolve the table before + the lock and carry the `// raw:` mark.""" machinery = {"driver_api.hpp", "driver_api.cpp", "py_driver_fns.cpp", "internal.hpp"} raw_call = re.compile(r"\bp_(cu|nv)\w+\b") # calls and null checks alike offenders = [] @@ -156,7 +157,7 @@ def test_driver_calls_go_through_the_table(): for number, line in enumerate(read(path).splitlines(), 1) if "// raw:" in line ] - assert {name.split(":")[0] for name in marked} == {"memory.cpp"}, marked + assert {name.split(":")[0] for name in marked} == {"context.cpp", "memory.cpp"}, marked @pytest.mark.agent_authored(model="claude-fable-5-1")