You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
cuda.core: treat the NULL stream as a default-stream token - #3243
Stream_handle_is_default_token now also matches handle 0, so a Stream over the NULL stream resolves its context and device on every call, as LEGACY_DEFAULT_STREAM and PER_THREAD_DEFAULT_STREAM do since #2485. The synchronous and virtual memory resources, which check the same predicate before recording a deallocation stream, now handle a handle-0 stream like the other two tokens as well. The test switches into a green context so it runs on a single GPU, and there is a 1.3.0 release note.
Stream_is_default_token matched only CU_STREAM_LEGACY and
CU_STREAM_PER_THREAD, so a Stream over handle 0, such as
Stream.from_handle(0), still cached the first context and device it
resolved. The driver resolves handle 0 against the current context like
the other two, so after a context switch .context, .device, .resources
and record() kept naming the old context.
ClosesNVIDIA#3242
Signed-off-by: Vyron Vasileiadis <hi@fedonman.com>
NULL-stream wrappers now use the current context when checking stream properties or recording events, rather than retaining the context and device first observed.
NULL-stream behavior now follows the active context when switching between device and green contexts.
Documentation
Clarified that the NULL stream, like other default streams, has no context of its own and uses the current context at call time.
The change treats handle 0 as a default-stream token. Tests check its context resolution across context changes, and documentation describes the behavior of its context-dependent properties.
Changes: NULL-stream context resolution
Layer / File(s)
Summary
NULL-stream recognition and context checks cuda_core/cuda/core/_stream.pxd, cuda_core/tests/test_green_context.py, cuda_core/tests/test_stream.py, cuda_core/cuda/core/_stream.pyx, cuda_core/docs/source/release/1.4.0-notes.rst
The default-token check now includes handle 0. Tests check context resolution across green-context and device-context changes. API documentation and release notes describe how NULL-stream properties resolve against the current context.
Assessment against linked issues
Objective
Addressed
Explanation
Handle 0 resolves against the current context instead of retaining the first context it sees, including for context-dependent stream properties and record() [#3242]
This change makes streams over the NULL stream track the current CUDA context, which fixes the cached-context problem reported in the linked issue. One open question remains. A host-located virtual memory deallocation that passes the NULL stream may now skip the explicit sync it did before, so queued work could run after the unmap. Resolve or explicitly accept this before merging.
Security architecture risk: Moderate · up to 99a42
Making the NULL stream follow the active CUDA context is consistent with the other default streams. The same change can also remove a wait before host-located virtual memory is unmapped, so a caller that relied on that wait may release a buffer while GPU work still uses it.
Retained concerns
Minor · reliability · inferred: For host-located virtual memory, an explicit handle-0 stream previously reached the deallocation synchronization path; it now bypasses that wait before unmap. Nonempty host-located allocations also stop recording a supplied handle-0 stream for teardown. If GPU work is still using the mapping and the caller has not independently synchronized it, release can race that work.
inferred — The supported exposure is to in-process CUDA callers and the buffers and GPU work they manage. The inspected change does not establish a remote, cross-tenant, or privilege-escalation path.
Hardening Proposals
proposed — Separate context-cache classification from release ordering. Preserve the wait for an explicitly supplied NULL stream, or require and document an equivalent fence. Cover both explicit release and teardown with pending GPU work in legacy and per-thread modes.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
suggestion: Add NULL-stream coverage for device, resources, and foreign wrappers.
The added test covers context and record() for Stream.from_handle(0) only. The existing default-stream test covers LEGACY_DEFAULT_STREAM and PER_THREAD_DEFAULT_STREAM, but not handle 0. Add device and resources assertions for the NULL stream, and create a foreign object whose __cuda_stream__ returns (0, 0). A handle-0 regression in either path can pass the current tests.
Reviewing files that changed from the base of the PR and between 590a8bf and 2a33c03.
Files selected for processing: 3
cuda_core/cuda/core/_stream.pyx
cuda_core/docs/source/release/1.3.0-notes.rst
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; 10 remain after this review.
Stream_handle_is_default_token now also matches handle 0, so a Stream over the NULL stream resolves its context and device on every call, as LEGACY_DEFAULT_STREAM and PER_THREAD_DEFAULT_STREAM do since #2485.
FYI just a note, this is true for the "re-resolve, don't cache" property this PR cares about. It is not true semantically under a green ctx: PTDS with a green ctx current is a hard CUDA_ERROR_INVALID_HANDLE ("CUDA Green Contexts cannot be used with stream-per-thread mode"), while handle 0 and CU_STREAM_LEGACY resolve to the green ctx's own null stream, which is a distinct stream object from the primary ctx's null stream (and only exists if the green ctx was created with CU_GREEN_CTX_DEFAULT_STREAM). Its default sync semantics are also different — PTDS-like non-blocking rather than the legacy sync-with-all, blocking behavior of the primary ctx's NULL stream.
The reason will be displayed to describe this comment to others. Learn more.
I traced this through the whole chain and it's a clean, correct extension of #2485. The predicate's consumers — Stream_get_ctx and Stream_get_ctx_device (so .context, .device, .resources, .record()) plus the synchronous and virtual memory resources that check the token before recording a deallocation stream — all pick up the handle-0 case automatically from the single-line predicate change, which matches the issue #3242 report exactly.
I specifically checked the one thing that could have broken the whole PR: Stream_check_open tests if not self._h_stream, which looks like it would reject a handle-0 stream as "closed". It doesn't, because _h_stream is a std::shared_ptr<const CUstream> and create_stream_handle_ref boxes the raw handle in a heap StreamBox (_cpp/rt/stream.cpp:111-123) — the shared_ptr is truthy regardless of the CUstream value it holds, so Stream.from_handle(0) passes every Stream_check_open gate. Worth having on record given how close that is.
Two more things I verified deliberately:
Keeping Stream_is_legacy_default_token at 0x1-only is right: the docstring's quirk is that cuMemcpyWithAttributesAsync/cuMemcpyBatchAsync reject the LEGACY token outright, whereas the NULL stream is a real stream to those entry points — so widening the narrow check would have been a bug, not a gap.
_from_handle still eagerly caches _h_context at construction (s._h_context = get_stream_context(h_stream)), including for handle 0; the fix works because Stream_get_ctx skips the sticky field whenever the token check is true, and the existing "defense in depth for #2485" comment covers this case now too.
One small doc touch-up to consider: the Note sections on the context, device, resources and record() docstrings still say a default stream means LEGACY_DEFAULT_STREAM or PER_THREAD_DEFAULT_STREAM — after this change the same statement applies to Stream.from_handle(0), so either enumerate it there or point at the predicate. The release note already documents it properly.
The test is well-placed (green context so it runs single-GPU, existing use_context helper, and it asserts both the context switch and that record() resolves against the current context — the exact stale-cache symptom from the issue).
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Heavy lift
Supported by static analysis
Script executed:
sed -n '890,940p' cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx
git diff 57b27097c1263da6da0eccdcea8e85b793696365 HEAD -- cuda_core/cuda/core/_stream.pxd
git show 57b27097c1263da6da0eccdcea8e85b793696365:cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx | rg -n -B6 -A10 'sync\(\)'
Repository: NVIDIA/cuda-python
Length of output: 4926
important: Keep the explicit sync for handle-0 streams in VirtualMemoryResource.deallocate.
On a host-located resource, deallocate(ptr, size, stream=Stream.from_handle(0)) now skips stream.sync(). The predicate change in _stream.pxd makes handle 0 a default-stream token. The guard at _virtual_memory_resource.pyx:915-916 then exempts it. Before this PR, the same call synced the stream.
cuMemUnmap takes no stream argument, so it does not wait for work queued on the NULL stream. Queued work that accesses the range can run after the unmap. The docstring promises stream.sync() when a stream is given. The exemption is written for unbound teardown tokens, not for a stream the caller passes explicitly.
Keep the sync when the caller supplies the NULL stream. Confirm how Buffer teardown passes its token before changing the guard. A check on the handle value alone may not separate the two cases.
The reason will be displayed to describe this comment to others. Learn more.
Handle 0 now takes the same path as an explicit LEGACY_DEFAULT_STREAM, which the deallocate docstring already exempts on a host-located resource. If that exemption is too broad for caller-supplied streams, it is too broad for both, so I kept it out of this fix.
The reason will be displayed to describe this comment to others. Learn more.
Analysis chain
Script executed:
#!/bin/bashset -u
printf'%s\n''--- HEAD ---'
git rev-parse HEAD
printf'%s\n''--- source outline ---'
ast-grep outline cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx --items all --match 'deallocate|VirtualMemoryResource'||trueprintf'%s\n''--- deallocation definitions ---'
rg -n -C 4 'def deallocate|cpdef deallocate|cdef deallocate|Stream_is_default_token|stream\.sync\(' cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx
printf'%s\n''--- implementation and documentation ---'
cat -n cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx | sed -n '810,945p'printf'%s\n''--- baseline implementation and documentation ---'
git show 57b27097c1263da6da0eccdcea8e85b793696365:cuda_core/cuda/core/_memory/_virtual_memory_resource.pyx | cat -n | sed -n '810,945p'
Length of output: 19340
web_search executed:
Find NVIDIA CUDA Driver API documentation for cuMemUnmap: does it synchronize with outstanding GPU work accessing the virtual address range, or must callers synchronize before unmapping? Prefer official CUDA documentation and quote the relevant contract.
Length of output: 13500
@fedonman important: I was wrong that the docstring promises synchronization for every supplied stream. It already exempts default-stream tokens on host-located resources.
Handle 0 was synchronized before this change. I could not verify whether cuMemUnmap waits for queued work. I accept your decision to leave the broader exemption outside this PR, but I’m not marking the finding as addressed.
I couldn't check this conversation for new learnings, so no new learning was saved.
Learnings used
Learnt from: CR
Repo: NVIDIA/cuda-python PR: 0
File: cuda_core/CLAUDE.md:0-0
Timestamp: 2026-10-31T05:09:21.347Z
Learning: Applies to cuda_core/** : Source excerpt:
## API design guidelines
### API stability
Reviews should point out where existing public APIs are broken.
Learnt from: CR
Repo: NVIDIA/cuda-python PR: 0
File: cuda_core/CLAUDE.md:0-0
Timestamp: 2026-11-24T00:47:06.269Z
Learning: Applies to cuda_core/** : Source excerpt:
## Editing guidance
- Keep user-facing behaviors coherent with docs and samples, especially around
stream semantics, memory ownership, and compile/link flows.
The reason will be displayed to describe this comment to others. Learn more.
Treating the NULL stream (handle 0) as a default token is semantically right — the driver treats 0 and CU_STREAM_LEGACY interchangeably as the current context's default stream — and the release note is clear about what changes (no more context/device caching on from_handle(0)). The new test covers context switching via Stream.record(). One consistency gap inline.
The reason will be displayed to describe this comment to others. Learn more.
With handle 0 now accepted into Stream_handle_is_default_token, the sibling predicate Stream_is_legacy_default_token (line 60, unchanged) is now inconsistent: a Stream.from_handle(0) stream is a "default token" to Stream_get_ctx/record()/sync(), but not a "legacy default token" to the copy paths.
Concretely, copy_batch() (_copy_ops.pyx:179) and copy(options=...) (_buffer.pyx:222) gate on Stream_is_legacy_default_token(s) to raise the friendly TypeError before calling cuMemcpyBatchAsync/cuMemcpyWithAttributesAsync — the same driver entry points whose own docs reject the NULL stream exactly like the legacy token. After this change, Stream.from_handle(0) slips past that gate and hits the driver with a raw 0 handle, where the user gets an opaque driver error (or undefined behavior for entry points that treat 0 as legacy) instead of the intended message.
If handle 0 is meant to behave like CU_STREAM_LEGACY everywhere, Stream_is_legacy_default_token should also match h == 0 — and the error messages in those two call sites may need to mention the NULL handle too. Worth adding a copy-path test with a from_handle(0) stream.
The reason will be displayed to describe this comment to others. Learn more.
This PR doesn't change the copy paths: Stream.from_handle(0) got past Stream_is_legacy_default_token before it too. You're right that the driver rejects handle 0 there, though. Both calls return CUDA_ERROR_INVALID_VALUE for it, except that cuMemcpyWithAttributesAsync accepts it in per-thread mode, so the guard needs more than h == 0. I'd rather fix that in a separate issue than widen this one. sync() doesn't read either predicate, so it isn't affected here.
The reason will be displayed to describe this comment to others. Learn more.
The fix itself (h == 0 as a default token) matches the bug report: the NULL stream is per-context by definition, so resolving context/device per call instead of caching is right. But it widens the divergence between the two token predicates in _stream.pxd:
Stream_handle_is_default_token now returns True for h == 0 (NULL), CU_STREAM_LEGACY and CU_STREAM_PER_THREAD, while Stream_is_legacy_default_token still returns True only for CU_STREAM_LEGACY — and the .pxd documents that the legacy default stream (but not CU_STREAM_PER_THREAD) is rejected with CUDA_ERROR_INVALID_VALUE by cuMemcpyWithAttributesAsync/cuMemcpyBatchAsync.
The NULL stream is a legacy default stream in the driver: it carries exactly the implicit-synchronization semantics the narrow check exists to refuse. After this PR, Stream.from_handle(0) is a default token but not a legacy-default token, so a guard written on Stream_is_legacy_default_token (used wherever the distinction matters per the .pxd comment) will let handle 0 through to those entry points as if it were a real stream — getting CUDA_ERROR_INVALID_VALUE at runtime, or, if the driver accepts NULL with implicit sync, an async-copy contract violation. Either mirror h == 0 into Stream_is_legacy_default_token (with a copy test through a from_handle(0) stream), or extend the docstring to state why NULL is exempt, and audit the callers of the narrow predicate for NULL-handle inputs.
Related: the new test only covers context resolution. stream.record() on the NULL stream while a different context is current records into the current context's legacy default stream — that is the documented per-call token semantics, but sync() (cuStreamSynchronize(0)) is just as current-context-dependent and would be worth asserting under the green context too.
The notes on Stream.context, .device, .resources and record() now list
the NULL stream next to LEGACY_DEFAULT_STREAM and
PER_THREAD_DEFAULT_STREAM. The release note moves to 1.4.0, since 1.3.0
has been released.
test_null_stream_follows_current_context now skips when
CUDA_PYTHON_CUDA_PER_THREAD_DEFAULT_STREAM is set. Handle 0 is then the
per-thread default stream, which the driver rejects with
CUDA_ERROR_INVALID_HANDLE under a green context.
test_default_stream_follows_current_context also covers
Stream.from_handle(0), which checks .device and .resources across
devices.
Signed-off-by: Vyron Vasileiadis <hi@fedonman.com>
Sorry for the long wait on this one. I merged main again, moved the release note to 1.4.0 since 1.3.0 is out, and added Stream.from_handle(0) to the multi-GPU default-stream test, which checks .device and .resources across a context switch.
@rahul05ranjan Thanks, done: the notes on context, device, resources and record() now list the NULL stream. One correction, though: the NULL stream isn't a real stream to cuMemcpyBatchAsync and cuMemcpyWithAttributesAsync. By default both return CUDA_ERROR_INVALID_VALUE for handle 0, as they do for CU_STREAM_LEGACY.
@leofang Thanks, that matches what CI hit. The Windows job that sets CUDA_PYTHON_CUDA_PER_THREAD_DEFAULT_STREAM=1 makes handle 0 the per-thread stream, which a green context rejects, so the new test now skips in that mode.
The reason will be displayed to describe this comment to others. Learn more.
Architecture findings (1)
Advisory architecture findings (1)
Minor — For host-located virtual memory, an explicit handle-0 stream previously reached the deallocation synchronization path; it now bypasses that wait before unmap. Nonempty host-located allocations also stop recording a supplied handle-0 stream for teardown. If GPU work is still using the mapping and the caller has not independently synchronized it, release can race that work.
Reviewing files that changed from the base of the PR and between 2d0c7f7 and 99a4272.
Files selected for processing: 4
cuda_core/cuda/core/_stream.pyx
cuda_core/docs/source/release/1.4.0-notes.rst
cuda_core/tests/test_green_context.py
cuda_core/tests/test_stream.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.
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cuda.coreEverything related to the cuda.core moduleenhancementAny code-related improvements
5 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stream_handle_is_default_tokennow also matches handle 0, so aStreamover the NULL stream resolves its context and device on every call, asLEGACY_DEFAULT_STREAMandPER_THREAD_DEFAULT_STREAMdo since #2485. The synchronous and virtual memory resources, which check the same predicate before recording a deallocation stream, now handle a handle-0 stream like the other two tokens as well. The test switches into a green context so it runs on a single GPU, and there is a 1.3.0 release note.Closes #3242