Skip to content

fix(cuda.core): keep one owning context handle per live context - #3538

Open
juenglin wants to merge 9 commits into
NVIDIA:mainfrom
juenglin:fix-3533-context-registry
Open

juenglin wants to merge 9 commits into
NVIDIA:mainfrom
juenglin:fix-3533-context-registry

Conversation

@juenglin

@juenglin juenglin commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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, 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.

Checklist

  • I have read the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

@juenglin juenglin added this to the cuda.core 1.4.0 milestone Nov 23, 2026
@juenglin juenglin added bug Something isn't working cuda.core Everything related to the cuda.core module labels Nov 23, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@leofang

leofang commented Nov 23, 2026

Copy link
Copy Markdown
Member

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.

@juenglin juenglin self-assigned this Nov 23, 2026
@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test f54a3fa

@juenglin

Copy link
Copy Markdown
Contributor Author

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?

@juenglin
juenglin requested review from Andy-Jost and leofang and removed request for leofang November 23, 2026 21:30
@juenglin
juenglin marked this pull request as ready for review November 23, 2026 21:30
@github-actions

Copy link
Copy Markdown
Contributor

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

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.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

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.
Context resolution integrations
cuda_core/cuda/core/_context.pxd, cuda_core/cuda/core/_context.pyx, cuda_core/cuda/core/_rt.pxd, cuda_core/cuda/core/_rt.pyx, cuda_core/cuda/core/_device.pyx, cuda_core/cuda/core/_memory/*
Cython helpers and context consumers use the primary-context APIs. Device.set_current resolves the previous context before switching.
Context lifetime regression coverage
cuda_core/tests/test_context.py, cuda_core/tests/test_green_context.py, cuda_core/tests/helpers/contexts.py, cuda_core/tests/test_rt_layout.py, cuda_core/docs/source/release/1.4.0-notes.rst
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.core Context 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
Recent review info

Run configuration

Commits

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Additional comments: 1

cuda_core/tests/test_context.py: 1

183-183: Trivial · Maintainability & Code Quality · Quick win

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)

Also applies to: 253-253

Source: Coding guidelines

Review info

Run configuration

Commits

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.

Comment thread cuda_core/cuda/core/_cpp/rt/context.cpp Resolved
Comment thread cuda_core/tests/test_context.py Resolved
Comment thread cuda_core/tests/test_green_context.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review info

Run configuration

Commits

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.

Comment thread cuda_core/tests/test_context.py Resolved
Comment thread cuda_core/tests/test_green_context.py Resolved
@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test a8f0d38

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

Commits

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.

Comment thread cuda_core/tests/test_context.py Resolved
@leofang

leofang commented Nov 24, 2026

Copy link
Copy Markdown
Member

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?

I am 100% sure this is a miss that agents keep adding back. I asked the very same question in here: https://github.com/NVIDIA/cuda-python/pull/2744/files#r4049442591. I am chasing after which PR it was changed.

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test f501c0b

@juenglin

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Action failed

Review failed.

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test 6037c1a

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test d46da3f

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test f1a8755

@rwgk rwgk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings at commit f1a8755

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

@juenglin

Copy link
Copy Markdown
Contributor Author

Thanks @rwgk, pushed f464c1f. Per finding:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test f464c1f

@rwgk

rwgk commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

— codex GPT-6.2-Sol ultra on behalf of Ralf —

  • 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

@juenglin

Copy link
Copy Markdown
Contributor Author

Thanks for both rounds. Status:

First round (at f1a8755)

  1. 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.
  2. 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).
  3. Stale wrapper after address reuse: fixed in f464c1f, with a test.
  4. 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.
  5. 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.

Second round (at fcfe267)

  • P1 and P2: gone with the revert of the borrowed-stream commit.
  • P3: fixed in a26036a. The test now rebinds the Device in an outer finally.

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test a26036a

@rwgk

rwgk commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Remaining codex GPT-6.2-Sol ultra findings:

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

@leofang leofang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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.

juenglin and others added 6 commits November 30, 2026 10:29
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>
@juenglin

Copy link
Copy Markdown
Contributor Author

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.

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test e8a92ef

@juenglin
juenglin requested a review from leofang November 30, 2026 19:29

@rwgk rwgk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings at commit e8a92ef

  • 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

juenglin and others added 3 commits November 30, 2026 13:43
…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>
@Andy-Jost

Copy link
Copy Markdown
Contributor

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working cuda.core Everything related to the cuda.core module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants