Fix primary context cleanup during Python shutdown - #2744
Open
bdice wants to merge 1 commit into
Open
Conversation
Author
|
I do not have permission to set metadata on the upstream repository. Suggested PR metadata: labels |
|
bdice
commented
Sep 1, 2026
|
|
||
|
|
||
| @pytest.mark.agent_authored(model="gpt-5.6-sol") | ||
| def test_primary_context_cleanup_is_safe_during_python_shutdown(init_cuda, tmp_path): |
Author
There was a problem hiding this comment.
This test will only reproduce the failure I saw if it is run with cuda-bindings <=12.9.2 or cuda-bindings >=13.0.0,<=13.0.1. However, it is good to include to prevent regression.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
cuDevicePrimaryCtxReleaseduring normal thread cleanup while leaving process-exit cleanup to CUDA/the OSDevice().set_current()followed by interpreter shutdownFixes #2743.
Root cause
get_primary_context()caches aContextHandlein thread-local storage. When the main thread's TLS destructors run afterPy_Finalize(), the handle deleter callsp_cuDevicePrimaryCtxRelease. That pointer targetscuda.bindings.cydriver.__pyx_capi__["cuDevicePrimaryCtxRelease"], whose generated Cython entry path touches Python thread state. The result is a post-atexitsegfault inPyThreadState_New.The existing
GILReleaseGuardavoids manipulating the GIL after finalization, but the Cython driver wrapper invoked immediately afterward has the same Python-runtime requirement. The new guard skips that wrapper only when Python is no longer usable.Testing
pixi run --manifest-path cuda_core -e cu12 python -m pytest cuda_core/tests/test_device.py -qpython -c 'from cuda.core import Device; Device().set_current(); print("initialized")'