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
Part of #3533 (the follow-up PR, #3658, completes it).
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
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
The registry no longer lets one handle erase another's entry.HandleRegistry records each entry's element address, so a handle erases only its own entry. The new insert_or_get() registers a handle without displacing a live entry unless a policy allows it. The stream, event and graph registries use the ownership-checked erase too.
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 share one retaining primary-context box per device.
No handle is destroyed under the registry lock, because deleters take the same lock.
The thread-local primary cache closes during thread exit, so a warning hook that runs while the cache is destroyed bypasses it.
The primary-context deleter reports cuDevicePrimaryCtxRelease failures through a pw_ wrapper instead of discarding the status. When the deleter runs during thread exit, the report is deferred to the main thread, because native thread teardown must not run Python warning hooks (on Windows the loader lock is held).
A losing primary-context candidate is dropped after the winner is cached, so a warning hook that re-enters get_primary_context() finds the cache entry.
Tests
test_primary_context_survives_thread_exit: after a thread that used the device exits, a lookup's Context, Stream or Event keeps the primary context alive. Fails on main, passes with the fix.
test_green_context_replaces_stale_plain_entry: covers the stale-address case. Fails on main, passes with the fix.
test_failed_primary_release_at_thread_exit_is_reported_from_main_thread: a failed release in the last exiting thread is reported once, from the main thread. Fails on the previous code, where the report came from the exiting thread.
test_concurrent_set_current_keeps_primary_active_after_threads_exit: after concurrent Device.set_current() calls, a held Context keeps the primary context active and dropping the last one releases it. This is a cleanup check; main passes it too.
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.
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.
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.
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?
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.
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.
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
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.
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 NVIDIA#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>
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>
…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>
…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>
Unfortunately I couldn't not complete reviewing this PR as I hoped, since this PR has grown unexpectedly large than I anticipated.
@leofang I split this PR so it is reviewable. #3538 now holds only the registry fix for #3533: one owning context handle per live context, and a handle erases only its own registry entry (6 commits).
The change that retains each primary context once and never releases it moved to #3658, stacked on this PR. #3658 is a draft until this one merges, and its last commit is the only one to review. The contents are unchanged, only the split is new.
P2 · A release warning can deadlock Windows thread exit. If the thread-local cache drops the last context handle and cuDevicePrimaryCtxRelease() fails, the deleter can run Python warning hooks while Windows holds the loader lock. A hook that calls Thread.start() waits for a new thread that needs the same lock to start. Defer Python warning delivery out of native thread teardown. This finding is based on source inspection. Context teardown · Windows loader-lock guidance
P3 · A release warning can reenter before the winning handle is cached. A warning hook that calls Device.set_current() repeats the retain-and-release path because the cache is still empty. With an injected release error, the callback reentered repeatedly. Publishing the cache entry first produced one callback. Cache publication
P3 · The concurrent-retain test checks cleanup but misses deduplication. Both revisions pass its active/inactive assertions because it drops seven of eight wrappers before the first check. With all eight wrappers held, the mocked driver measured eight retains on the base and one on the PR. Keep the cleanup check and either narrow the test name or verify sharing before dropping the wrappers. Concurrent test · Saved probe
I asked codex to help me understand the first (P2) finding, showing the response here JIC you find it useful:
Yes. That’s the deleter, and pw_cuDevicePrimaryCtxRelease(device_id) is the call that can reach Python. It’s a WarnOnFailure wrapper. It calls the CUDA driver’s cuDevicePrimaryCtxRelease, checks the returned status, and reports failures other than CUDA_ERROR_DEINITIALIZED. Wrapper implementation
The reporting runs synchronously on the same thread. report_cuda_error() calls report_message(), which acquires the GIL and calls PyErr_WarnEx(). If the warning is displayed, Python can call a custom warnings.showwarning hook. If a filter turns it into an exception, PyErr_WriteUnraisable() can invoke sys.unraisablehook. The outer GILReleaseGuard lets the driver call run without the GIL, and the nested reporting path explicitly acquires it again. Error reporting · Python warning delivery
The Windows concern is the case where native thread exit drops the last reference in PrimaryContextCache. That runs this same deleter during TLS teardown, so a release failure can reach the Python hook while the exiting thread still holds the loader lock. TLS cache destructor
…ndidate
get_primary_context() dropped its candidate box before it stored the winning
handle in the thread-local cache. When another thread's box won, dropping the
candidate releases the extra retain, and a failure there is reported through a
warning hook. A hook that called Device.set_current() found the cache still
empty and repeated the retain-and-release path, so the callback reentered.
Store the handle in the cache first, so a reentrant call finds it.
Found by rwgk's review of NVIDIA#3538, using a mocked driver whose release fails.
A test needs a losing candidate, which two threads racing the first retain
produce only by chance, so none is added.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…he main thread
The primary context's deleter reports a failed cuDevicePrimaryCtxRelease through
a pw_ wrapper, which runs Python warning hooks on the calling thread. When the
last thread that cached the context exits, the deleter runs from the
thread_local cache's destructor, in native thread teardown. On Windows the
loader lock is held there, so a hook that starts a thread waits for a thread
that cannot start. Python state is torn down at that point on every platform.
When the thread's cache is closed, the deleter now calls the driver without
reporting and, on failure, hands a report to the deferred-cleanup queue, which
delivers it from the main thread. The report is preallocated with the box, so
the deleter does not allocate. It is dropped during interpreter finalization,
like other deleter work.
The test makes the release fail by releasing cuda.core's only retain from the
child, then lets the last thread exit. On the previous code the one
CUDAWarning arrives from the exiting thread.
Found by rwgk's review of NVIDIA#3538, from source inspection.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
test_concurrent_set_current_shares_one_primary_retain claimed to count
retains, but it drops seven of its eight Contexts before the first check, so it
only checks cleanup: a held Context keeps the primary context active, and
dropping the last one releases it. main passes that too. Rename it to match,
and leave the lifetime guarantee to test_primary_context_survives_thread_exit.
Start the workers with run_in_threads instead of a ThreadPoolExecutor, so a
failing worker aborts the barrier and its error is re-raised instead of the
other workers blocking until the child times out.
In test_green_context_replaces_stale_plain_entry, note rollback failures on
the propagating exception with add_note() instead of the private
_attach_rollback_failure_for_testing hook, which exists to test the C++
attach_rollback_failure() itself.
Found by rwgk's review of NVIDIA#3538.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
I think we should discuss the design offline. We need to be clear about the requirements, current state, bug, and fix. There are several things going on here and not everything claimed is true. For instance:
cuda.core has released its primary-context retain when the last handle drops; before #1368 it never released
The context handle is held in a thread-local global for the life of the program, and release is skipped in finalization. So 1368 kept the old behavior (never release).
This branch has not been deployed
No deployments
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
4 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
Part of #3533 (the follow-up PR, #3658, completes it).
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
In
context.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
HandleRegistryrecords each entry's element address, so a handle erases only its own entry. The newinsert_or_get()registers a handle without displacing a live entry unless a policy allows it. The stream, event and graph registries use the ownership-checked erase too.cuDevicePrimaryCtxReleasefailures through apw_wrapper instead of discarding the status. When the deleter runs during thread exit, the report is deferred to the main thread, because native thread teardown must not run Python warning hooks (on Windows the loader lock is held).get_primary_context()finds the cache entry.Tests
test_primary_context_survives_thread_exit: after a thread that used the device exits, a lookup'sContext,StreamorEventkeeps the primary context alive. Fails onmain, passes with the fix.test_green_context_replaces_stale_plain_entry: covers the stale-address case. Fails onmain, passes with the fix.test_failed_primary_release_at_thread_exit_is_reported_from_main_thread: a failed release in the last exiting thread is reported once, from the main thread. Fails on the previous code, where the report came from the exiting thread.test_concurrent_set_current_keeps_primary_active_after_threads_exit: after concurrentDevice.set_current()calls, a heldContextkeeps the primary context active and dropping the last one releases it. This is a cleanup check;mainpasses it too.Checklist