You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(cuda.core): make the primary-context cache process-wide - #3693
get_primary_context kept a thread_local cache. Every thread retained the primary context and registered its own box under the same CUcontext key in context_registry. Boxes overwrote each other's entries and a dying box erased another box's entry, so an Event or Context could end up referring to a primary context the driver then destroyed (CUDA_ERROR_CONTEXT_IS_DESTROYED).
Separately, create_context_handle_ref registered a plain, non-owning box for any context cuda.core did not create. That entry could outlive its context. When the driver reused the address for a new green context, Device.create_context() got the stale plain box back, dropped the only owner of the new green context, and returned a destroyed Context with is_green == False.
One owning handle per device in a process-wide cache, filled lazily on first use (no CUDA work at import).
Primary contexts are no longer registered in context_registry. create_context_handle_ref checks the cache first, then the registry.
Plain context handles are created fresh and never registered, so context_registry holds green contexts only. A plain box carries no metadata and Context compares raw CUcontext values, so sharing it gained nothing. With only owning boxes registered, an entry is erased before its context can be destroyed, so no ownership-checked erase or replacement policy is needed.
The cache holds its retain until process exit (behavior change: a primary context used only by worker threads is no longer released when those threads exit).
Free-threading: the cache is read and written only under a mutex held for vector access alone. The driver call runs with no lock held, and a thread that loses the publish race releases its extra retain outside the lock.
Not covered, unchanged by this PR: a Context for a primary context that only another library retained holds no retain and stays valid only as long as that library keeps it alive.
Release notes for both fixes and the behavior change are in cuda_core/docs/source/release/1.4.0-notes.rst.
In-process tests for the cache publication race and for the current-context path resolving to the primary Context.
test_green_context.py::test_create_context_at_reused_address_is_green, adapted from fix(cuda.core): keep one owning context handle per live context #3538: a green context created and destroyed through cuda.bindings leaves a plain Context, and the test retries until the driver reuses that address for create_context(). It fails without the registry change (is_green is False).
Full cuda_core suite run locally: 4366 passed, 357 skipped. Not yet run on a free-threaded interpreter.
get_primary_context kept a thread_local cache, so every thread retained
the primary context and registered its own box under the same CUcontext
key in context_registry. Boxes overwrote each other's entries, and a
dying box erased another box's entry, which could leave an Event or
Context referring to a primary context the driver then destroyed.
Keep one owning handle per device in a process-wide cache that is filled
lazily on first use. Primary contexts no longer go in context_registry;
create_context_handle_ref checks the cache first. The retain is held
until process exit. The driver call runs with no lock held.
Fixes the primary-context part of NVIDIA#3533.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.
No actionable comments were generated in the recent review.
Summary
Summary by CodeRabbit
Bug Fixes
Primary CUDA contexts are shared across threads and retained until process exit, so they remain available after the thread that obtained them exits.
Contexts obtained through device operations, streams, and events resolve consistently to the same primary context.
Device.create_context no longer returns a stale context when the driver reuses an address previously associated with a destroyed context.
Contexts not retained by cuda.core remain dependent on the library that retains them.
Documentation
Clarified primary-context caching and lifetime behavior.
The runtime now shares one retained primary-context handle per device across threads for the process lifetime. Context resolution checks the cache before the green-context registry and leaves plain, non-owning handles unregistered. Tests cover context use after thread exit and green-context address reuse.
Changes: Primary context cache and resolution
Layer / File(s)
Summary
Process-wide cache and context resolution cuda_core/cuda/core/_cpp/rt/context.cpp, cuda_core/cuda/core/_cpp/rt/api.hpp, cuda_core/cuda/core/_cpp/rt/internal.hpp, cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md, cuda_core/docs/source/release/1.4.0-notes.rst
The runtime caches retained primary-context handles per device and checks the cache before the green-context registry. Contexts without a green-context owner receive plain, unregistered handles. The API comment, design document, and release notes describe the cache and context-lifetime behavior.
Thread lifetime and handle reuse coverage cuda_core/tests/test_context.py, cuda_core/tests/test_device.py, cuda_core/tests/test_green_context.py, cuda_core/docs/source/release/1.4.0-notes.rst
Tests cover context equality across threads, context use after worker threads exit, and green-context creation after driver address reuse.
Assessment against linked issues
Objective
Addressed
Explanation
Keep a primary context alive while cuda.core context references use it, including after retaining threads exit [#3533]
✅
Possibly related issues
NVIDIA/cuda-python#1389 — The PR adds a mutex-protected process-wide primary-context cache, but the issue concerns thread safety of module-level state more broadly.
Change: Bug fix · Severity of issue fixed: High
Merge Risk: Minimal · up to 12f6c
The primary-context cache now shares one retained context per device across threads. It fixes stale contexts after worker threads exit and the reused-address green-context mix-up. Failed context releases are still reported through the existing warning path. No remaining merge-blocking concern was found.
Security architecture risk: Moderate · up to d08a3
The shared retain fixes premature context destruction when workers exit. The tradeoff is that memory operations can now keep a device’s primary context active until the process exits, even when an allocation returns no buffer. Applications that relied on releasing their last owner and recycling a worker must now recycle the process to clear CUDA Core’s retain.
Retained concerns
Minor · reliability · observed: A nonempty device-backed VirtualMemoryResource allocation or IPC import using a default stream can pin the primary context solely to order deallocation; allocation also does so when the stream is omitted. A synchronous memory resource without an explicit context can publish the retain before rejecting a stream or failing an allocation. At the merge base, dropping all owners and ending the retaining worker could allow last-release cleanup. At head, closing the buffer, dropping the resource, and replacing the worker cannot clear CUDA Core’s cache retain.
Trivial · reliability · inferred: The merge base could reuse an unchecked handle on a worker with a populated slot, but a new worker attempted a driver retain. At head all workers reuse the populated slot, and a failed Device.set_current does not invalidate it. If an out-of-band reset leaves the cached handle unusable, replacing the worker no longer provides a fresh retain attempt. The driver’s post-reset handle validity and whether a fresh retain would recover were not established.
observed — The lifetime change is scoped to each populated device slot in the calling process. All threads using that slot share its owner; an IPC import that populates the slot does so in the importing process, not the exporting process.
Trust Boundaries and Controls
observed — The IPC descriptor carries peer-supplied data, but the importing caller supplies the memory resource and stream. The VMM path checks that the resource is IPC-enabled and validates handle type and device location before reaching deallocation binding. The new effect occurs after those checks: an accepted, nonempty device-backed import with a default stream can establish a process-lifetime retain for the importer’s resource device.
Dependencies
inferred — CUDA Core assumes that a cached driver handle remains usable for later callers. It does not revalidate that handle after an out-of-band reset, and the reviewed source does not establish what the driver guarantees in that state.
Data and control flow
observed — On a miss, the driver retain runs outside the mutex. A failed retain publishes nothing. Publication keeps the first successful owner for the device; a losing publisher attempts to release its extra retain outside the mutex.
Resilience and Maintainability Implications
observed — No returned buffer does not necessarily mean no persistent state change. A rejected synchronous allocation can leave the same cached owner as a successful allocation followed by buffer closure. The failed driver retain itself does not populate the cache; the difference is whether publication preceded the later failure.
inferred — An external reset and an uninterrupted run leave the same CUDA Core cache entry. Replacing a worker cannot force revalidation or a fresh retain, even if the old handle fails when made current. Restarting the process clears the cache; whether reset alone leaves CUDA Core usable is not established.
Rollout and rollback
observed — At the merge base, callers could end the retaining worker and drop outstanding owners to allow last-release cleanup, provided no other driver retain remained. At head the cache owns the retain independently of those callers. An operator who needs to clear CUDA Core’s retain must terminate the owning process, not just replace a worker.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Reviewing files that changed from the base of the PR and between d08a31a and 12f6cb3.
Files selected for processing: 1
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Files skipped from review as they are similar to previous changes: 1
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.
Device-backed VirtualMemoryResource allocation with an omitted or default stream can pin the device’s primary context for the rest of the process, even though the caller only requested memory. At the merge base, once the worker exited and the last handle and driver retain were released, CUDA could reset the context automatically. At the head, closing the buffer and stopping the worker no longer drops cuda.core’s cache retain. Applications that rely on last-release reset for in-process recovery must instead recycle the owning process to clear that retain.
Reviewing files that changed from the base of the PR and between db858c1 and 79050e9.
Files selected for processing: 5
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
cuda_core/cuda/core/_cpp/rt/api.hpp
cuda_core/cuda/core/_cpp/rt/context.cpp
cuda_core/tests/test_context.py
cuda_core/tests/test_device.py
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.
create_context_handle_ref registered a plain, non-owning handle for any
context cuda.core did not retain or create. That entry could outlive its
context. When the driver reused the address for a new green context,
Device.create_context() got the stale plain handle back, dropped the only
owner of the new green context, and returned a destroyed Context with
is_green == False.
Plain handles are now created fresh and never registered, so
context_registry holds green contexts only. A plain handle carries no
metadata and Context compares raw CUcontext values, so sharing one gained
nothing. With only owning handles registered, an entry is erased before
its context can be destroyed, and no ownership-checked erase or
replacement policy is needed.
Covers the green-context address-reuse part of NVIDIA#3533.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Describe the two NVIDIA#3533 fixes in the 1.4.0 release notes, and the behavior
change that cuda.core now keeps its retain of a primary context until the
process exits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The primary-context deleter discarded the status of
cuDevicePrimaryCtxRelease. With the process-wide cache, it runs during
normal calls when a thread loses the race to publish its retain. Report a
failure through a new pw_cuDevicePrimaryCtxRelease wrapper, as other
deleters do. The deleter runs with the GIL released and no lock held.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai Re the trivial finding that the primary context stays retained until process exit: this is intended and is noted in the PR description and the 1.4.0 release notes. The old per-thread cache already held the main thread's retain until exit, so only worker-thread-only use changes. No change planned.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments
1
Device-backed VirtualMemoryResource allocations with an omitted or default stream still select the primary context for deallocation ordering. At the merge base, closing the buffer and ending the worker could allow automatic reset once all other owners released their retains. At the reviewed head, those same actions leave cuda.core’s retain in place. The synchronous memory resource also resolves and caches a primary context before validating the stream or attempting device allocation, so a failed call can leave the process-wide retain in place even though no buffer was returned.
1
A successful out-of-band cuDevicePrimaryCtxReset resets device state but does not retire cuda.core’s cached owner. A populated thread-local slot already bypassed a fresh retain at the merge base, but after old owners were dropped a new worker took the driver retain path. At the reviewed head, replacing the worker no longer provides that path. Every worker reuses the same unchecked cache entry, so an integration cannot assume that a successful raw reset followed by worker replacement restores a usable cuda.core context.
Reviewing files that changed from the base of the PR and between 79050e9 and fffeb31.
Files selected for processing: 5
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
cuda_core/cuda/core/_cpp/rt/context.cpp
cuda_core/cuda/core/_cpp/rt/internal.hpp
cuda_core/docs/source/release/1.4.0-notes.rst
cuda_core/tests/test_green_context.py
Files skipped from review as they are similar to previous changes: 1
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.
@juenglin suggestion: I withdraw the finding. The 1.4.0 release notes document the intended process-lifetime retention. The change affects cases where only worker threads used the primary context.
Learnings added
Learnt from: juenglin
URL: https://github.com/NVIDIA/cuda-python/pull/3693
Timestamp: 2026-12-03T00:15:24.259Z
Learning: Within repository "NVIDIA/cuda-python", only for files matching one of ["cuda_core/cuda/core/_cpp/rt/context.cpp"]: In cuda_core/cuda/core/_cpp/rt/context.cpp, cuda.core intentionally retains a primary context until process exit, including when only worker threads used it. The previous thread-local cache already retained the main thread's primary context until exit. Do not flag process-lifetime retention alone as an unintended leak or regression.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
The cache's mutex and vector were namespace-scope globals, so static
destructors ran them after Py_Finalize. A thread still in nogil code
could then reach a destroyed mutex or vector through
find_primary_context or lookup_primary_context, and the deleters would
release the cached retains during exit.
Move both into one heap-allocated object behind a function-local static
that is never deleted. The pointer stays reachable, so leak checkers do
not report it.
A box's deleter now runs only when get_primary_context fails to publish
it: the thread lost the publish race or publishing threw. That happens
right after a successful retain, so remove the Py_IsInitialized() and
py_is_finalizing() check. It dates from NVIDIA#2743, when the release went
through a Cython wrapper that needed Python.
init_cuda calls Device(0).set_current() on the main thread before the test body runs. The primary-context cache is therefore warm when the eight workers start. The workers read a cached context, so the barrier does not make them race to populate the cache. The docstring should describe the test as a concurrent cache-hit check. The fresh-process test in test_context.py already covers concurrent cold initialization. The assertions in this test are still valid, so only the docstring needs to change.
Suggested docstring fix
- """Threads racing to fill the process-wide primary-context cache all see the same Context."""
+ """Concurrent threads reading the warm primary-context cache all see the same Context."""
A nonempty device-backed VirtualMemoryResource allocation or IPC import using a default stream can pin the primary context solely to order deallocation; allocation also does so when the stream is omitted. A synchronous memory resource without an explicit context can publish the retain before rejecting a stream or failing an allocation. At the merge base, dropping all owners and ending the retaining worker could allow last-release cleanup. At head, closing the buffer, dropping the resource, and replacing the worker cannot clear CUDA Core’s cache retain.
1
The merge base could reuse an unchecked handle on a worker with a populated slot, but a new worker attempted a driver retain. At head all workers reuse the populated slot, and a failed Device.set_current does not invalidate it. If an out-of-band reset leaves the cached handle unusable, replacing the worker no longer provides a fresh retain attempt. The driver’s post-reset handle validity and whether a fresh retain would recover were not established.
Reviewing files that changed from the base of the PR and between 6493db0 and d08a31a.
Files selected for processing: 2
cuda_core/cuda/core/_cpp/rt/context.cpp
cuda_core/tests/test_device.py
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.
…nal reset
The process-wide primary-context cache does not detect a cuDevicePrimaryCtxReset issued outside cuda.core, and cuda.core has no reset API. State the assumption in REGISTRY_DESIGN.md so a future change that adds reset support knows the cache needs an invalidation design.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workingcuda.coreEverything related to the cuda.core module
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
closes #3533
Summary
get_primary_contextkept athread_localcache. Every thread retained the primary context and registered its own box under the sameCUcontextkey incontext_registry. Boxes overwrote each other's entries and a dying box erased another box's entry, so anEventorContextcould end up referring to a primary context the driver then destroyed (CUDA_ERROR_CONTEXT_IS_DESTROYED).Separately,
create_context_handle_refregistered a plain, non-owning box for any contextcuda.coredid not create. That entry could outlive its context. When the driver reused the address for a new green context,Device.create_context()got the stale plain box back, dropped the only owner of the new green context, and returned a destroyedContextwithis_green == False.context_registry.create_context_handle_refchecks the cache first, then the registry.context_registryholds green contexts only. A plain box carries no metadata andContextcompares rawCUcontextvalues, so sharing it gained nothing. With only owning boxes registered, an entry is erased before its context can be destroyed, so no ownership-checked erase or replacement policy is needed.Not covered, unchanged by this PR: a
Contextfor a primary context that only another library retained holds no retain and stays valid only as long as that library keeps it alive.Release notes for both fixes and the behavior change are in
cuda_core/docs/source/release/1.4.0-notes.rst.Tests
set_currenttest, adapted from fix(cuda.core): keep one owning context handle per live context #3538 (the assertion that the primary context is released after the lastContextis dropped is removed, since the retain is now held to process exit).Context.test_green_context.py::test_create_context_at_reused_address_is_green, adapted from fix(cuda.core): keep one owning context handle per live context #3538: a green context created and destroyed throughcuda.bindingsleaves a plainContext, and the test retries until the driver reuses that address forcreate_context(). It fails without the registry change (is_greenisFalse).cuda_coresuite run locally: 4366 passed, 357 skipped. Not yet run on a free-threaded interpreter.🤖 Generated with Claude Code