Skip to content

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

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

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

Conversation

@juenglin

@juenglin juenglin commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Checklist

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

🤖 Generated with Claude Code

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.

Fixes NVIDIA#3533

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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.

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

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>
@juenglin juenglin self-assigned this Nov 23, 2026
…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>
@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
…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>

@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
…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

/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 and others added 4 commits November 24, 2026 16:00
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>
juenglin and others added 6 commits November 25, 2026 06:46
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>
@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.

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>
@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test 6037c1a

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test d46da3f

…gistry

# Conflicts:
#	cuda_core/cuda/core/_cpp/rt/memory.cpp
@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 and others added 3 commits November 25, 2026 15:43
…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>
@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

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>
@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 and others added 2 commits November 25, 2026 17:17
…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>
@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.

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.

[BUG]: Primary context can be destroyed while a cuda.core Context still refers to it after a thread exits

3 participants