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): keep one owning context handle per live context - #3538
Milestone: cuda.core 1.4.0 (release note in cuda_core/docs/source/release/1.4.0-notes.rst).
After other threads that used the same device exited, a Context, Stream or Event could fail with CUDA_ERROR_CONTEXT_IS_DESTROYED. When the driver reused a context's address, Device.create_context() could return an already-destroyed context with is_green == False.
Root cause
Since #1368 (first released in 0.6.0), cuda.core released its primary-context retains when the last handle dropped. Before that, it retained the primary context and never released it. In context.cpp, each thread's get_primary_context() retained the primary context separately and overwrote the previous thread's registry entry. Every context deleter then erased the registry entry unconditionally, even when it belonged to another, still-live box. Later lookups returned handles that held no retain, so the driver could destroy the context while it was still in use.
Fix
Primary contexts are never released again.cuda.core retains each device's primary context at most once per process and never releases it, as the CUDA runtime does. One retaining box per device is pinned in a process-wide table that is never freed and is read without a lock. There is no per-thread cache, so a thread's exit does not affect primary contexts.
Lookups retain a primary context that another library made current. Context lookups share one resolver (create_context_handle_ref(), create_current_context_handle_ref(), get_current_context()). When it resolves the calling thread's current context, and that is its device's active primary context, it is retained and pinned the same way. 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 it is still current.
The registry no longer lets one handle erase another's entry.HandleRegistry lets a handle erase only its own entry, and the new insert_or_get() registers a handle without displacing a live entry unless a policy allows it. No handle is destroyed while the registry lock is held, because deleters take the same lock. For contexts, a box that keeps its context alive (a pinned primary context or a green context) replaces a plain one, and nothing replaces it. The stream, event and graph registries use the ownership-checked erase too.
Context lookups stay out of C++ locks. A lookup can take a mutex and report a failure, which acquires the GIL, so deviceptr_import_ipc() resolves the deallocation stream before it takes the IPC pointer cache's mutex.
One primary-context helper in Cython.Device.set_current() and both memory resources use Context_primary() / Context_get_primary_handle(), which raise consistently on failure.
Not covered: a Context resolved for a context that is not current at the time, such as another context's stream or a graph node's update context, holds no retain if cuda.core has not retained that primary context. Its device cannot be queried without switching contexts.
Tests
test_concurrent_set_current_keeps_one_primary_retain: threads call Device.set_current() concurrently and exit; the primary context stays active, with exactly one retain.
test_lookup_retains_foreign_primary_context and test_set_current_previous_context_retains_foreign_primary: another owner retains the primary context and makes it current; the Context and Event that cuda.core resolves keep it alive after that owner releases it.
test_green_context_lookup_does_not_retain_primary: a lookup of a current green context leaves no primary-context retain behind.
test_green_context_replaces_stale_plain_entry covers the stale-address case.
Tests that need a process without other retains run in a child process. The concurrent and lookup tests fail on main; everything passes with the fix. Tested on one GPU (RTX 6000 Ada, driver 595.99.02).
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.
FixesNVIDIA#3533
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
I need to understand better what is happening. We should never, ever destroy the default primary contexts in cuda-core. It is against the design from Day 1.
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 <noreply@anthropic.com>
…otes
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 <noreply@anthropic.com>
I need to understand better what is happening. We should never, ever destroy the default primary contexts in cuda-core. It is against the design from Day 1.
To clarify what this PR does: it adds no release. Since #1368, cuda.core has released its primary-context retain when the last handle drops; before #1368 it never released. #3533 addresses a case where that release happens while a Context is still in use: each thread took its own retain, and a thread's exit erased the registry entry of another thread's live box. This PR keeps one shared retain per primary context, so the release can only happen once no cuda.core object refers to the context.
Sounds like you want to go back to the pre-#1368 guarantee. Should I open another issue for that change?
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 contexts are retained at most once per device and remain available for the process lifetime.
Resolving a thread’s current primary context keeps it available, including when another library made it current.
Fixed stale context returns when a new context reuses a handle.
Device.set_current preserves access to the previously current context.
Registry cleanup avoids removing entries that belong to a different resource.
Failures when releasing a primary context are reported as warnings.
Documentation
Updated context-lifecycle guidance and release notes to describe primary-context retention and stale-context handling.
The change updates registry ownership and cleanup rules, pins each device’s primary context for the process lifetime, and adopts eligible current primary contexts. It also updates context consumers, adds lifecycle regression tests, and changes IPC import stream-resolution timing.
Changes: Context Registry Ownership and Lifetime
Layer / File(s)
Summary
Registry identity and replacement rules cuda_core/cuda/core/_cpp/rt/internal.hpp, cuda_core/cuda/core/_cpp/rt/event.cpp, cuda_core/cuda/core/_cpp/rt/graph.cpp, cuda_core/cuda/core/_cpp/rt/stream.cpp, cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Registry entries store the resource address. Unregistration removes an entry only when its resource matches. insert_or_get supports conditional replacement, and event, graph, and stream cleanup callbacks pass the resource address.
Primary-context ownership and lookup cuda_core/cuda/core/_cpp/rt/context.cpp, cuda_core/cuda/core/_cpp/rt/driver_api.hpp, cuda_core/cuda/core/_cpp/rt/api.hpp, cuda_core/cuda/core/_cpp/rt/DESIGN.md
Context boxes record primary-context retains. A process-wide table pins primary-context handles, and lookups adopt eligible current primary contexts.
Tests cover primary-context lifetime across thread exit, concurrent lookups, external release, and green-context handle reuse. Release notes describe the lifetime and reused-handle behavior.
IPC Import Stream Resolution
Layer / File(s)
Summary
Resolve stream before cache lookup cuda_core/cuda/core/_cpp/rt/memory.cpp
deviceptr_import_ipc now resolves the deallocation stream before cache lookup. A failed resolution discards a fresh import and returns the recorded status.
Assessment against linked issues
Objective
Addressed
Explanation
[3533] Keep a primary context alive while a cuda.coreContext still refers to it, including across thread exit.
✅
Assessment against linked issues: Out-of-scope changes
Code Change
Explanation
Resolve the deallocation stream before IPC cache lookup (cuda_core/cuda/core/_cpp/rt/memory.cpp:683-694, 726-733)
Issue #3533 concerns context lifetime and registry ownership. It does not specify changes to IPC import stream resolution.
Change: Bug fix · Severity of issue fixed: High
Security architecture risk: Low · up to f54f3
The change prevents one thread’s exit from invalidating CUDA resources still in use by another. The remaining risk is narrow: if host memory allocation fails while establishing process-wide ownership, a retry can take an extra CUDA retain that remains until process exit. The inspected IPC path keeps its existing descriptor checks.
Retained concerns
Low · reliability · observed: After the driver grants a primary-context retain, boxing and snapshot publication allocate memory without a rollback guard. If allocation fails before publication, no table entry records the retain and the box deleter does not release it. A later attempt can retain the same device again, violating the one-retain-per-device guarantee. This adds a retain failure path to foreign-current-context lookup and extends the existing allocation-failure window on explicit primary-context acquisition.
Security review details
Security Blast Radius
inferred — The new retain failure is scoped to the affected device’s primary context within the importing process. Normal thread exit no longer ends ownership, and the process-wide pin is not a guarantee against an external CUDA device reset.
Trust Boundaries and Controls
observed — The existing pool-backed IPC descriptor path checks the resource type, IPC enablement, and payload length before invoking the native import, then rejects a claimed buffer size beyond the mapped extent. Reordering stream preparation inside the native import does not bypass those checks.
Resilience and Maintainability Implications
observed — An unbound default stream can trigger context adoption and a warning callback during cleanup preparation. Performing that work before locking removes the new callback path from the IPC cache critical section, while the cache still serializes import and publication.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Reviewing files that changed from the base of the PR and between f501c0b and 652eabd.
Files selected for processing: 3
cuda_core/tests/helpers/contexts.py
cuda_core/tests/test_context.py
cuda_core/tests/test_green_context.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.
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
suggestion: Use the suite's synchronous child-process runner.
Move the child bodies into top-level worker functions and invoke them with helpers.child_processes.run_child. The suite already forces spawn, so the tests can keep fresh-process isolation and share the suite's timeout, termination, and process-handle cleanup. As per coding guidelines, “Reuse run_child and noop from helpers.child_processes for synchronous child-process tests.” (raw.githubusercontent.com)
Reviewing files that changed from the base of the PR and between edf1b31 and f54a3fa.
Files selected for processing: 9
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
cuda_core/cuda/core/_cpp/rt/context.cpp
cuda_core/cuda/core/_cpp/rt/event.cpp
cuda_core/cuda/core/_cpp/rt/graph.cpp
cuda_core/cuda/core/_cpp/rt/internal.hpp
cuda_core/cuda/core/_cpp/rt/stream.cpp
cuda_core/docs/source/release/1.4.0-notes.rst
cuda_core/tests/test_context.py
cuda_core/tests/test_green_context.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.
…ten NVIDIA#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 <noreply@anthropic.com>
Reviewing files that changed from the base of the PR and between f54a3fa and 34fd0d3.
Files selected for processing: 4
cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
cuda_core/cuda/core/_cpp/rt/context.cpp
cuda_core/tests/test_context.py
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; 9 remain after this review.
…h 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 <noreply@anthropic.com>
Reviewing files that changed from the base of the PR and between 34fd0d3 and a8f0d38.
Files selected for processing: 2
cuda_core/tests/test_context.py
cuda_core/tests/test_green_context.py
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 9 remain after this review.
I need to understand better what is happening. We should never, ever destroy the default primary contexts in cuda-core. It is against the design from Day 1.
To clarify what this PR does: it adds no release. Since #1368, cuda.core has released its primary-context retain when the last handle drops; before #1368 it never released. #3533 addresses a case where that release happens while a Context is still in use: each thread took its own retain, and a thread's exit erased the registry entry of another thread's live box. This PR keeps one shared retain per primary context, so the release can only happen once no cuda.core object refers to the context.
Sounds like you want to go back to the pre-#1368 guarantee. Should I open another issue for that change?
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
(NVIDIA#1368). get_primary_context() pins one retaining box per device in a
process-wide table that is never freed, so no thread exit or handle
release can drop it. The thread-local cache stays as a fast path; its
destructor now only drops references, so the closed-cache guard for
re-entrant warning hooks is no longer needed.
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.
These lookups may now 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; a cached import is still returned without a
current context.
Tests: the concurrent set_current() test now checks that exactly one
retain remains after every thread has exited. New tests cover lookups
and set_current() of a primary context that another owner made current,
and that a lookup of a current green context leaves no primary retain.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
test_concurrent_set_current_keeps_one_primary_retain runs its workers
with run_in_threads (NVIDIA#3544), which aborts the barrier if a worker fails
and bounds the joins.
test_green_context_replaces_stale_plain_entry notes rollback failures
with BaseException.add_note() instead of the _attach_rollback_failure_for_testing
production hook, which NVIDIA#3555 moves out of _rt.
test_driver_calls_go_through_the_table: the primary-context table's mutex
is a second site of raw driver calls under a lock.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN.md: add a "Primary contexts" section (one pinned retain per device,
adoption of a current primary context, what a lookup of a non-current
context returns), say that resolving a context handle must not run under a
C++ lock, and note that insert_or_get releases a displaced handle after the
unlock.
REGISTRY_DESIGN.md: a primary context's Box is the one entry that does not
expire with its weak reference.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
With cuda.core pinning each primary context for the life of the process,
test_primary_context_survives_thread_exit no longer covers anything that
test_concurrent_set_current_keeps_one_primary_retain does not: the latter
fails on releasing code for the same cause, deterministically, and also
checks that exactly one retain is held. Remove it and its two one-second
waits.
Fold the two parameters of test_lookup_retains_foreign_primary_context
into one child: the Context and Event lookups go through the same
Stream_get_ctx path, so one process records an event and resolves the
stream's Context, then uses both after the foreign release.
Share primary_context_active() in helpers/contexts.py instead of a
private copy in each test file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
create_context_handle_ref(), get_current_context() and the green-context
path now share resolve_context_handle(), which takes the primary-context
adoption step as a callable. A caller that already knows the current
context passes that knowledge instead of querying the driver again:
get_current_context() skips the second cuCtxGetCurrent, and
Device.set_current() resolves the previous context with the new
create_current_context_handle_ref(ctx, device), which skips both
cuCtxGetCurrent and cuCtxGetDevice. Behavior is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The process-wide table of pinned primary contexts is now the only cache:
it is published as immutable, leaked snapshots that readers load with
one acquire load, and pinning publishes a new snapshot under the mutex.
This replaces the thread_local primary_context_cache, which was only a
fast path in front of the table's mutex, so a thread's exit no longer
touches primary-context handles at all. A table hit also skips the GIL
release and the driver-table check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pinned primary-context box and the plain or green box had two copies
of the same construction and deleter. make_context_handle() now builds
both; the deleter's ownership-checked unregister is unchanged, and the
pinned box's deleter stays unreachable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…elper
Device.set_current(), _SynchronousMemoryResource and
VirtualMemoryResource each called get_primary_context() and handled an
empty handle in their own way; the synchronous memory resource did not
raise if no error was recorded. Context_get_primary_handle() and
Context_primary() in _context.pyx now drain get_last_error(), raise the
recorded CUDA error if there is one, and otherwise raise
RuntimeError("Failed to retain the primary context for device N"). All
three sites use them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reflow the "Primary contexts" bullet on context-handle resolution, note
that the pinned table's mutex and snapshot pointer are constant-initialized
globals (no static-initialization guard), and point Cython code at
Context_get_primary_handle() and Context_primary() instead of calling
get_primary_context() directly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The deallocation-stream resolve looks up the current context through
get_current_context(), not create_context_handle_ref().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
P2 · A fresh worker can no longer reactivate the primary context after a reset. Once a device is pinned, get_primary_context() always returns the cached handle. After cuDevicePrimaryCtxReset(), a fresh worker on the base revision calls cuDevicePrimaryCtxRetain() again. On this PR, Device.set_current() can appear to succeed while the next CUDA operation fails with CUDA_ERROR_CONTEXT_IS_DESTROYED. A mocked driver check reproduced the difference between the base and PR head. Primary context cache · NVIDIA driver probe
P2 · Borrowed streams can bypass the new retain logic. If a real stream’s first .context lookup happens while its primary context is non-current, the wrapper caches a non-owning handle. Later .context and .record() calls reuse that handle even after the primary context becomes current. Releasing the foreign retain can then invalidate the returned context and event. The new test uses a default-stream token, which bypasses this cache. Add a real-stream case that queries from another context first. Stream context cache · Current test
P2 · Device.set_current(ctx) can return a stale wrapper after address reuse. If Device still caches a plain wrapper and a new green context takes the same CUcontext address, the resolver finds the live owning handle. The raw-address comparison then returns the stale wrapper, which reports is_green == False and carries no ownership. Compare the resolved handle’s identity before reusing the Python wrapper. Previous-context return
P3 · Allocation failure can leave an untracked primary retain. The driver retain succeeds before the pinned handle and table snapshot are allocated. If allocation throws before publication, a retry takes another retain. With an injected allocation failure, the base held one retain after retry and the PR held two. Retain and publication
P3 · A cached IPC import can retain a context for a stream it never uses. Deallocation-stream resolution now runs before the cache lookup. A duplicate import can permanently pin the ambient primary context or emit a warning even though the cached mapping keeps its original deallocation stream. IPC import cache
Validation
All nine layout tests passed, and the changed C++ files passed syntax checks against CUDA 12.9 and 13.5 headers. Both bindings majors already resolve cuDevicePrimaryCtxGetState on Linux and Windows.
…location stream
A repeat import keeps the cached mapping's deallocation stream, so resolving
one for the call only to discard it could pin the ambient primary context or
report a failure for a stream that is never used. Peek at the cache first with
a non-waiting find_live(), and return a live entry directly. A miss or a
release in flight still goes through get_or_create(). This also makes the
cache-hit path cheaper: it skips the box allocation and the stream lookup.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ning
A Stream wrapped from a raw handle caches the context handle that
cuStreamGetCtx resolved. If the stream's primary context was not current at
that first lookup, the cached handle is a plain reference that keeps nothing
alive, and later .context and .record() calls reused it even after the primary
context became current. Releasing another owner's retain could then destroy
the context under the returned Context and Event.
Mark such a handle as borrowed and look it up again on each call until the
registry returns an owning handle. Export the existing ownership predicate as
context_handle_is_owning() for this.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…(ctx)
set_current(ctx) reused the Device's remembered Context as the previous
context whenever its CUcontext address matched the one that was current. The
driver reuses the address of a destroyed context, so a Context for a destroyed
context could be returned in place of a live green context at the same
address: it reported is_green == False and held no ownership.
Compare the remembered Context's handle with the handle just resolved for the
current context instead of comparing raw addresses.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Reset: not addressed here. cuda.core never resets a primary context, and supporting a reset needs more than re-retaining: live Stream/Event/Buffer objects would hold destroyed handles, and the registries key on a CUcontext address that the driver reuses. Main only recovers in threads that never touched the device, and that was never tested or documented. This is better handled as a separate design question.
Borrowed stream: fixed in d85472d. A borrowed stream's cached context handle is looked up again until it is owning. New real-stream test; it fails without the fix.
Stale wrapper: fixed in f464c1f. Device.set_current(ctx) compares the resolved handle instead of the raw address. New test; it fails without the fix.
Allocation failure: not changed. A retry after a failed allocation can leave a second retain, which is never released and is harmless; the primary context stays alive either way.
Cached IPC import: fixed in 1dac64c. A non-waiting cache lookup now runs before the deallocation stream is resolved. A concurrent duplicate import can still resolve one; that window is not closed.
Consumer modules call the functions declared in _rt.pxd through Cython
function pointers typed from the .pxd, not from the C++ header. Five
functions that return C++ bool were declared bint (int), so callers read
all of EAX while MSVC sets only AL for a bool return.
For context_handle_is_owning, MSVC returns false with `xor al, al` while
EAX still holds the low bits of the box pointer, so a non-owning handle
read as owning on Windows. A borrowed stream then never re-resolved its
context, and test_borrowed_stream_lookup_retains_primary_context failed on
every Windows job. The event getters and mem_allocation_is_imported happen
to compile to movzx today, but have the same mismatch.
Declare all five as cpp_bool, and note the rule in _rt.pxd.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
P1 · Concurrent reads can race on the stream’s context cache. Two threads can read .context on the same borrowed stream while one replaces _h_context. The assignment holds the GIL, but the other reader accesses the same std::shared_ptr under nogil. That reader can access the old context box after its last reference is released. Keep the cached handle immutable and resolve into a local handle, or synchronize every cache access. Stream context cache
P2 · A cuda.core-created stream can bypass primary-context adoption. Obtain a non-owning primary Context from a foreign stream while its primary is non-current, bind it with Device.set_current(ctx) from a thread with no current context, then call Device.create_stream(). The new stream inherits the non-owning handle, and _ctx_borrowed is false. Its .context and .record() calls therefore skip adoption even while the primary is current. Releasing the foreign retain can invalidate the returned context and event. Base cache reuse on whether the context handle owns the context. Stream construction · Cache condition
P3 · The green-context regression test can turn a skip into a teardown error. If the driver never reuses the address, the test skips with Device still bound to the destroyed foreign context. The raw driver call restores the thread’s current context, but fixture teardown calls device.sync() on the stale Device binding. Restore the binding with dev.set_current(primary) in an outer finally. Address-reuse test · Fixture teardown
…it is owning"
This reverts commit d85472d.
Re-resolving the cached handle replaced Stream._h_context while another
thread could be copying it without the GIL, and it covered only streams
wrapped from a raw handle: a stream that cuda.core creates under a non-owning
Context has the same gap, as does everything else created from such a Context.
A context handle resolved while its primary context was not current does not
keep that context alive. That is unchanged from before this PR, which adds
adoption only for a context that is current at lookup time, and is stated in
api.hpp. Upgrading such handles later is left to a follow-up.
The cpp_bool declarations added since are kept; only the declaration of the
removed context_handle_is_owning() goes.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…or fails
test_set_current_returns_live_context_after_address_reuse makes the Device
remember a Context for a context it then destroys. When the driver never
reused the address, the test skipped with the Device still bound to it, and
the init_cuda teardown failed in Device.sync() with
CUDA_ERROR_CONTEXT_IS_DESTROYED. Rebind the Device to the primary context in
an outer finally.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Reset: not addressed here. cuda.core never calls cuDevicePrimaryCtxReset, and after a reset every existing stream, event, buffer and cached handle is dead, so recovering only the Device.set_current() step would not make a reset work. On main it only works for threads that have not touched the device yet. Supporting a reset needs its own design, so I'd keep it out of this PR.
Borrowed stream: not addressed. A handle resolved while its primary context is not current is a plain reference, as on main, and api.hpp says so. My first fix re-resolved on every lookup; your second round showed it raced on the cached handle and left other routes open, so I reverted it (f469e32).
Stale wrapper after address reuse: fixed in f464c1f, with a test.
Allocation failure: not addressed. After a failed retry cuda.core holds one extra retain at most. It never releases its retain, so this is safe.
Cached IPC import: fixed in 1dac64c. A cache peek now runs before the deallocation stream is resolved. A concurrent duplicate import can still resolve one stream it does not use, which is harmless.
Re-reviewed PR #3538 at a26036a. The stream cache race is gone, and the green-context test now restores the Device binding on skip and failure paths. I found no new code blocker in this update.
P2 · Fresh-worker recovery after an external primary reset still regresses. Even after all old CUDA objects are gone, a fresh worker now gets the pinned inactive handle from Device.set_current(). On the base revision, the fresh worker took a new retain and reactivated the context. A mocked driver check reproduced the difference. If reset recovery is deferred, call out this behavior change in the release notes. Primary cache
P3 · Clarify the stream adoption guarantee. A stream first queried while its primary context is non-current can cache a borrowed handle. Later .context and .record() calls reuse that handle even when the primary is current. The release notes should distinguish a fresh lookup from reuse of a cached handle. The design rationale should also name the driver API in use, since CUDA 13’s cuCtxGetDevice_v2 can query an explicit context without switching. Stream cache · Release notes · CUDA driver API
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately I couldn't not complete reviewing this PR as I hoped, since this PR has grown unexpectedly large than I anticipated. Allow me to put a pause here and circle back after the US holidays.
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
3 participants
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.
Description
closes #3533
Milestone: cuda.core 1.4.0 (release note in
cuda_core/docs/source/release/1.4.0-notes.rst).After other threads that used the same device exited, a
Context,StreamorEventcould fail withCUDA_ERROR_CONTEXT_IS_DESTROYED. When the driver reused a context's address,Device.create_context()could return an already-destroyed context withis_green == False.Root cause
Since #1368 (first released in 0.6.0),
cuda.corereleased its primary-context retains when the last handle dropped. Before that, it retained the primary context and never released it. Incontext.cpp, each thread'sget_primary_context()retained the primary context separately and overwrote the previous thread's registry entry. Every context deleter then erased the registry entry unconditionally, even when it belonged to another, still-live box. Later lookups returned handles that held no retain, so the driver could destroy the context while it was still in use.Fix
cuda.coreretains each device's primary context at most once per process and never releases it, as the CUDA runtime does. One retaining box per device is pinned in a process-wide table that is never freed and is read without a lock. There is no per-thread cache, so a thread's exit does not affect primary contexts.create_context_handle_ref(),create_current_context_handle_ref(),get_current_context()). When it resolves the calling thread's current context, and that is its device's active primary context, it is retained and pinned the same way. 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 it is still current.HandleRegistrylets a handle erase only its own entry, and the newinsert_or_get()registers a handle without displacing a live entry unless a policy allows it. No handle is destroyed while the registry lock is held, because deleters take the same lock. For contexts, a box that keeps its context alive (a pinned primary context or a green context) replaces a plain one, and nothing replaces it. The stream, event and graph registries use the ownership-checked erase too.deviceptr_import_ipc()resolves the deallocation stream before it takes the IPC pointer cache's mutex.Device.set_current()and both memory resources useContext_primary()/Context_get_primary_handle(), which raise consistently on failure.Not covered: a
Contextresolved for a context that is not current at the time, such as another context's stream or a graph node's update context, holds no retain ifcuda.corehas not retained that primary context. Its device cannot be queried without switching contexts.Tests
test_concurrent_set_current_keeps_one_primary_retain: threads callDevice.set_current()concurrently and exit; the primary context stays active, with exactly one retain.test_lookup_retains_foreign_primary_contextandtest_set_current_previous_context_retains_foreign_primary: another owner retains the primary context and makes it current; theContextandEventthatcuda.coreresolves keep it alive after that owner releases it.test_green_context_lookup_does_not_retain_primary: a lookup of a current green context leaves no primary-context retain behind.test_green_context_replaces_stale_plain_entrycovers the stale-address case.Tests that need a process without other retains run in a child process. The concurrent and lookup tests fail on
main; everything passes with the fix. Tested on one GPU (RTX 6000 Ada, driver 595.99.02).Checklist
🤖 Generated with Claude Code