Skip to content

fix(cuda.core): make the primary-context cache process-wide - #3693

Open
juenglin wants to merge 6 commits into
NVIDIA:mainfrom
juenglin:context-take-two
Open

juenglin wants to merge 6 commits into
NVIDIA:mainfrom
juenglin:context-take-two

Conversation

@juenglin

@juenglin juenglin commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

closes #3533

Summary

get_primary_context kept a thread_local cache. Every thread retained the primary context and registered its own box under the same CUcontext key in context_registry. Boxes overwrote each other's entries and a dying box erased another box's entry, so an Event or Context could end up referring to a primary context the driver then destroyed (CUDA_ERROR_CONTEXT_IS_DESTROYED).

Separately, create_context_handle_ref registered a plain, non-owning box for any context cuda.core did not create. That entry could outlive its context. When the driver reused the address for a new green context, Device.create_context() got the stale plain box back, dropped the only owner of the new green context, and returned a destroyed Context with is_green == False.

  • One owning handle per device in a process-wide cache, filled lazily on first use (no CUDA work at import).
  • Primary contexts are no longer registered in context_registry. create_context_handle_ref checks the cache first, then the registry.
  • Plain context handles are created fresh and never registered, so context_registry holds green contexts only. A plain box carries no metadata and Context compares raw CUcontext values, so sharing it gained nothing. With only owning boxes registered, an entry is erased before its context can be destroyed, so no ownership-checked erase or replacement policy is needed.
  • The cache holds its retain until process exit (behavior change: a primary context used only by worker threads is no longer released when those threads exit).
  • Free-threading: the cache is read and written only under a mutex held for vector access alone. The driver call runs with no lock held, and a thread that loses the publish race releases its extra retain outside the lock.

Not covered, unchanged by this PR: a Context for a primary context that only another library retained holds no retain and stays valid only as long as that library keeps it alive.

Release notes for both fixes and the behavior change are in cuda_core/docs/source/release/1.4.0-notes.rst.

Tests

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Dec 2, 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.

@github-actions github-actions Bot added the cuda.core Everything related to the cuda.core module label Dec 2, 2026
get_primary_context kept a thread_local cache, so every thread retained
the primary context and registered its own box under the same CUcontext
key in context_registry. Boxes overwrote each other's entries, and a
dying box erased another box's entry, which could leave an Event or
Context referring to a primary context the driver then destroyed.

Keep one owning handle per device in a process-wide cache that is filled
lazily on first use. Primary contexts no longer go in context_registry;
create_context_handle_ref checks the cache first. The retain is held
until process exit. The driver call runs with no lock held.

Fixes the primary-context part of NVIDIA#3533.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@juenglin juenglin self-assigned this Dec 2, 2026
@juenglin juenglin added this to the cuda.core 1.4.0 milestone Dec 2, 2026
@juenglin

juenglin commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 79050e9

@juenglin
juenglin marked this pull request as ready for review December 2, 2026 23:45
@juenglin juenglin added the bug Something isn't working label Dec 2, 2026
@coderabbitai

coderabbitai Bot commented Dec 2, 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 CUDA contexts are shared across threads and retained until process exit, so they remain available after the thread that obtained them exits.
    • Contexts obtained through device operations, streams, and events resolve consistently to the same primary context.
    • Device.create_context no longer returns a stale context when the driver reuses an address previously associated with a destroyed context.
    • Contexts not retained by cuda.core remain dependent on the library that retains them.
  • Documentation
    • Clarified primary-context caching and lifetime behavior.

The runtime now shares one retained primary-context handle per device across threads for the process lifetime. Context resolution checks the cache before the green-context registry and leaves plain, non-owning handles unregistered. Tests cover context use after thread exit and green-context address reuse.

Changes: Primary context cache and resolution

Layer / File(s) Summary
Process-wide cache and context resolution
cuda_core/cuda/core/_cpp/rt/context.cpp, cuda_core/cuda/core/_cpp/rt/api.hpp, cuda_core/cuda/core/_cpp/rt/internal.hpp, cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md, cuda_core/docs/source/release/1.4.0-notes.rst
The runtime caches retained primary-context handles per device and checks the cache before the green-context registry. Contexts without a green-context owner receive plain, unregistered handles. The API comment, design document, and release notes describe the cache and context-lifetime behavior.
Thread lifetime and handle reuse coverage
cuda_core/tests/test_context.py, cuda_core/tests/test_device.py, cuda_core/tests/test_green_context.py, cuda_core/docs/source/release/1.4.0-notes.rst
Tests cover context equality across threads, context use after worker threads exit, and green-context creation after driver address reuse.

Assessment against linked issues

Objective Addressed Explanation
Keep a primary context alive while cuda.core context references use it, including after retaining threads exit [#3533] ✅

Possibly related issues

  • NVIDIA/cuda-python#1389 — The PR adds a mutex-protected process-wide primary-context cache, but the issue concerns thread safety of module-level state more broadly.

Change: Bug fix · Severity of issue fixed: High

Merge Risk: Minimal · up to 12f6c

The primary-context cache now shares one retained context per device across threads. It fixes stale contexts after worker threads exit and the reused-address green-context mix-up. Failed context releases are still reported through the existing warning path. No remaining merge-blocking concern was found.

Security architecture risk: Moderate · up to d08a3

The shared retain fixes premature context destruction when workers exit. The tradeoff is that memory operations can now keep a device’s primary context active until the process exits, even when an allocation returns no buffer. Applications that relied on releasing their last owner and recycling a worker must now recycle the process to clear CUDA Core’s retain.

Retained concerns

  • Minor · reliability · observed: A nonempty device-backed VirtualMemoryResource allocation or IPC import using a default stream can pin the primary context solely to order deallocation; allocation also does so when the stream is omitted. A synchronous memory resource without an explicit context can publish the retain before rejecting a stream or failing an allocation. At the merge base, dropping all owners and ending the retaining worker could allow last-release cleanup. At head, closing the buffer, dropping the resource, and replacing the worker cannot clear CUDA Core’s cache retain.
  • Trivial · reliability · inferred: The merge base could reuse an unchecked handle on a worker with a populated slot, but a new worker attempted a driver retain. At head all workers reuse the populated slot, and a failed Device.set_current does not invalidate it. If an out-of-band reset leaves the cached handle unusable, replacing the worker no longer provides a fresh retain attempt. The driver’s post-reset handle validity and whether a fresh retain would recover were not established.

View findings in the submitted review

Security review details

Security Blast Radius

  • observed — The lifetime change is scoped to each populated device slot in the calling process. All threads using that slot share its owner; an IPC import that populates the slot does so in the importing process, not the exporting process.

Trust Boundaries and Controls

  • observed — The IPC descriptor carries peer-supplied data, but the importing caller supplies the memory resource and stream. The VMM path checks that the resource is IPC-enabled and validates handle type and device location before reaching deallocation binding. The new effect occurs after those checks: an accepted, nonempty device-backed import with a default stream can establish a process-lifetime retain for the importer’s resource device.

Dependencies

  • inferred — CUDA Core assumes that a cached driver handle remains usable for later callers. It does not revalidate that handle after an out-of-band reset, and the reviewed source does not establish what the driver guarantees in that state.

Data and control flow

  • observed — On a miss, the driver retain runs outside the mutex. A failed retain publishes nothing. Publication keeps the first successful owner for the device; a losing publisher attempts to release its extra retain outside the mutex.

Resilience and Maintainability Implications

  • observed — No returned buffer does not necessarily mean no persistent state change. A rejected synchronous allocation can leave the same cached owner as a successful allocation followed by buffer closure. The failed driver retain itself does not populate the cache; the difference is whether publication preceded the later failure.
  • inferred — An external reset and an uninterrupted run leave the same CUDA Core cache entry. Replacing a worker cannot force revalidation or a fresh retain, even if the old handle fails when made current. Restarting the process clears the cache; whether reset alone leaves CUDA Core usable is not established.

Rollout and rollback

  • observed — At the merge base, callers could end the retaining worker and drop outstanding owners to allow last-release cleanup, provided no other driver retain remained. At head the cache owns the retain independently of those callers. An operator who needs to clear CUDA Core’s retain must terminate the owning process, not just replace a worker.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d08a31a and 12f6cb3.

Files selected for processing: 1

  • cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Files skipped from review as they are similar to previous changes: 1

  • cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.

@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

Minor 1
  1. Report a failed primary-context release from the losing publisher.
Trivial 1
  1. Device-backed VirtualMemoryResource allocation with an omitted or default stream can pin the device’s primary context for the rest of the process, even though the caller only requested memory. At the merge base, once the worker exited and the last handle and driver retain were released, CUDA could reset the context automatically. At the head, closing the buffer and stopping the worker no longer drops cuda.core’s cache retain. Applications that rely on last-release reset for in-process recovery must instead recycle the owning process to clear that retain.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between db858c1 and 79050e9.

Files selected for processing: 5

  • cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
  • cuda_core/cuda/core/_cpp/rt/api.hpp
  • cuda_core/cuda/core/_cpp/rt/context.cpp
  • cuda_core/tests/test_context.py
  • cuda_core/tests/test_device.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.

Comment thread cuda_core/cuda/core/_cpp/rt/context.cpp Resolved
create_context_handle_ref registered a plain, non-owning handle for any
context cuda.core did not retain or create. That entry could outlive its
context. When the driver reused the address for a new green context,
Device.create_context() got the stale plain handle back, dropped the only
owner of the new green context, and returned a destroyed Context with
is_green == False.

Plain handles are now created fresh and never registered, so
context_registry holds green contexts only. A plain handle carries no
metadata and Context compares raw CUcontext values, so sharing one gained
nothing. With only owning handles registered, an entry is erased before
its context can be destroyed, and no ownership-checked erase or
replacement policy is needed.

Covers the green-context address-reuse part of NVIDIA#3533.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

juenglin and others added 2 commits December 2, 2026 16:04
Describe the two NVIDIA#3533 fixes in the 1.4.0 release notes, and the behavior
change that cuda.core now keeps its retain of a primary context until the
process exits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The primary-context deleter discarded the status of
cuDevicePrimaryCtxRelease. With the process-wide cache, it runs during
normal calls when a thread loses the race to publish its retain. Report a
failure through a new pw_cuDevicePrimaryCtxRelease wrapper, as other
deleters do. The deleter runs with the GIL released and no lock held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@juenglin

juenglin commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai Re the trivial finding that the primary context stays retained until process exit: this is intended and is noted in the PR description and the 1.4.0 release notes. The old per-thread cache already held the main thread's retain until exit, so only worker-thread-only use changes. No change planned.

@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

Minor 1
  1. Device-backed VirtualMemoryResource allocations with an omitted or default stream still select the primary context for deallocation ordering. At the merge base, closing the buffer and ending the worker could allow automatic reset once all other owners released their retains. At the reviewed head, those same actions leave cuda.core’s retain in place. The synchronous memory resource also resolves and caches a primary context before validating the stream or attempting device allocation, so a failed call can leave the process-wide retain in place even though no buffer was returned.
Trivial 1
  1. A successful out-of-band cuDevicePrimaryCtxReset resets device state but does not retire cuda.core’s cached owner. A populated thread-local slot already bypassed a fresh retain at the merge base, but after old owners were dropped a new worker took the driver retain path. At the reviewed head, replacing the worker no longer provides that path. Every worker reuses the same unchecked cache entry, so an integration cannot assume that a successful raw reset followed by worker replacement restores a usable cuda.core context.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 79050e9 and fffeb31.

Files selected for processing: 5

  • cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
  • cuda_core/cuda/core/_cpp/rt/context.cpp
  • cuda_core/cuda/core/_cpp/rt/internal.hpp
  • cuda_core/docs/source/release/1.4.0-notes.rst
  • cuda_core/tests/test_green_context.py
Files skipped from review as they are similar to previous changes: 1

  • cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.

@juenglin

juenglin commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test fffeb31

@coderabbitai

coderabbitai Bot commented Dec 3, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
echo "=== Locate release notes ==="
fd -HI '^1\.4\.0-notes\.rst$' .
echo "=== Release note context ==="
rg -n -C 8 -i 'primary context|thread.*exit|process.*exit' cuda_core/docs/source/release/1.4.0-notes.rst
echo "=== Context implementation outline ==="
ast-grep outline cuda_core/cuda/core/_cpp/rt/context.cpp --items all --match 'primary_context_cache|get_primary_context' --view expanded
echo "=== Context implementation matches ==="
rg -n -C 7 'primary_context_cache|get_primary_context\(' cuda_core/cuda/core/_cpp/rt/context.cpp
echo "=== Applicable repository instructions ==="
for f in AGENTS.md cuda_core/AGENTS.md cuda_core/cuda/AGENTS.md cuda_core/cuda/core/AGENTS.md cuda_core/cuda/core/_cpp/AGENTS.md cuda_core/cuda/core/_cpp/rt/AGENTS.md; do if [ -f "$f" ]; then echo "=== $f ==="; cat "$f"; fi; done

Length of output: 21209


@juenglin suggestion: I withdraw the finding. The 1.4.0 release notes document the intended process-lifetime retention. The change affects cases where only worker threads used the primary context.


Learnings added

Learnt from: juenglin
URL: https://github.com/NVIDIA/cuda-python/pull/3693

Timestamp: 2026-12-03T00:15:24.259Z
Learning: Within repository "NVIDIA/cuda-python", only for files matching one of ["cuda_core/cuda/core/_cpp/rt/context.cpp"]: In cuda_core/cuda/core/_cpp/rt/context.cpp, cuda.core intentionally retains a primary context until process exit, including when only worker threads used it. The previous thread-local cache already retained the main thread's primary context until exit. Do not flag process-lifetime retention alone as an unintended leak or regression.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

coderabbitai[bot]

This comment was marked as outdated.

@juenglin
juenglin requested review from Andy-Jost and leofang December 3, 2026 01:48
The cache's mutex and vector were namespace-scope globals, so static
destructors ran them after Py_Finalize. A thread still in nogil code
could then reach a destroyed mutex or vector through
find_primary_context or lookup_primary_context, and the deleters would
release the cached retains during exit.

Move both into one heap-allocated object behind a function-local static
that is never deleted. The pointer stays reachable, so leak checkers do
not report it.

A box's deleter now runs only when get_primary_context fails to publish
it: the thread lost the publish race or publishing threw. That happens
right after a successful retain, so remove the Py_IsInitialized() and
py_is_finalizing() check. It dates from NVIDIA#2743, when the release went
through a Cython wrapper that needed Python.

@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

Minor 2
  1. Docstring says the test covers a cold-cache race it does not reach.
    cuda_core/tests/test_device.py, lines 688 · 📐 Maintainability & Code Quality · 💤 Low value
    init_cuda calls Device(0).set_current() on the main thread before the test body runs. The primary-context cache is therefore warm when the eight workers start. The workers read a cached context, so the barrier does not make them race to populate the cache. The docstring should describe the test as a concurrent cache-hit check. The fresh-process test in test_context.py already covers concurrent cold initialization. The assertions in this test are still valid, so only the docstring needs to change.
    Suggested docstring fix
    -    """Threads racing to fill the process-wide primary-context cache all see the same Context."""
    +    """Concurrent threads reading the warm primary-context cache all see the same Context."""
    
  2. A nonempty device-backed VirtualMemoryResource allocation or IPC import using a default stream can pin the primary context solely to order deallocation; allocation also does so when the stream is omitted. A synchronous memory resource without an explicit context can publish the retain before rejecting a stream or failing an allocation. At the merge base, dropping all owners and ending the retaining worker could allow last-release cleanup. At head, closing the buffer, dropping the resource, and replacing the worker cannot clear CUDA Core’s cache retain.
Trivial 1
  1. The merge base could reuse an unchecked handle on a worker with a populated slot, but a new worker attempted a driver retain. At head all workers reuse the populated slot, and a failed Device.set_current does not invalidate it. If an out-of-band reset leaves the cached handle unusable, replacing the worker no longer provides a fresh retain attempt. The driver’s post-reset handle validity and whether a fresh retain would recover were not established.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 6493db0 and d08a31a.

Files selected for processing: 2

  • cuda_core/cuda/core/_cpp/rt/context.cpp
  • cuda_core/tests/test_device.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

…nal reset

The process-wide primary-context cache does not detect a cuDevicePrimaryCtxReset issued outside cuda.core, and cuda.core has no reset API. State the assumption in REGISTRY_DESIGN.md so a future change that adds reset support knows the cache needs an invalidation design.
@juenglin

juenglin commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 12f6cb3

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

1 participant