Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions cuda_core/cuda/core/_stream.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@ cdef inline bint Stream_handle_is_default_token(cydriver.CUstream s) noexcept no

These tokens carry no context of their own; they refer to whatever context
is current, so nothing resolved from one may be cached on the object.
The NULL stream (handle 0) is such a token too.
"""
cdef uintptr_t h = <uintptr_t>s
return h == <uintptr_t>cydriver.CU_STREAM_LEGACY or h == <uintptr_t>cydriver.CU_STREAM_PER_THREAD
return h == 0 or h == <uintptr_t>cydriver.CU_STREAM_LEGACY or h == <uintptr_t>cydriver.CU_STREAM_PER_THREAD

@coderabbitai coderabbitai Bot Nov 2, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Analysis chain

Script executed:

#!/bin/bash
set -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' || true
printf '%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.

You are interacting with an AI system.

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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.



cdef inline bint Stream_is_default_token(Stream self) noexcept nogil:
"""Return True when this stream is CU_STREAM_LEGACY or CU_STREAM_PER_THREAD."""
"""Return True when this stream is the NULL stream, CU_STREAM_LEGACY or CU_STREAM_PER_THREAD."""
return Stream_handle_is_default_token(as_cu(self._h_stream))


Expand Down
16 changes: 8 additions & 8 deletions cuda_core/cuda/core/_stream.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,8 @@ cdef class Stream:

Note
----
A default stream (:obj:`LEGACY_DEFAULT_STREAM` or
:obj:`PER_THREAD_DEFAULT_STREAM`) carries no context of its own; it
A default stream (:obj:`LEGACY_DEFAULT_STREAM`, :obj:`PER_THREAD_DEFAULT_STREAM`
or the NULL stream, handle 0) carries no context of its own; it
refers to whichever context is current, so a newly created event is
associated with the current context at call time.

Expand Down Expand Up @@ -385,8 +385,8 @@ cdef class Stream:

Note
----
A default stream (:obj:`LEGACY_DEFAULT_STREAM` or
:obj:`PER_THREAD_DEFAULT_STREAM`) carries no context of its own; it
A default stream (:obj:`LEGACY_DEFAULT_STREAM`, :obj:`PER_THREAD_DEFAULT_STREAM`
or the NULL stream, handle 0) carries no context of its own; it
refers to whichever context is current, so this returns the device for
the current context at call time.

Expand All @@ -408,8 +408,8 @@ cdef class Stream:

Note
----
A default stream (:obj:`LEGACY_DEFAULT_STREAM` or
:obj:`PER_THREAD_DEFAULT_STREAM`) carries no context of its own; it
A default stream (:obj:`LEGACY_DEFAULT_STREAM`, :obj:`PER_THREAD_DEFAULT_STREAM`
or the NULL stream, handle 0) carries no context of its own; it
refers to whichever context is current, so this returns the current
context at call time.

Expand All @@ -430,8 +430,8 @@ cdef class Stream:

Note
----
A default stream (:obj:`LEGACY_DEFAULT_STREAM` or
:obj:`PER_THREAD_DEFAULT_STREAM`) carries no context of its own; it
A default stream (:obj:`LEGACY_DEFAULT_STREAM`, :obj:`PER_THREAD_DEFAULT_STREAM`
or the NULL stream, handle 0) carries no context of its own; it
refers to whichever context is current, so this queries the current
context at call time.

Expand Down
7 changes: 7 additions & 0 deletions cuda_core/docs/source/release/1.4.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,10 @@ Fixes and enhancements
later driver; with a CUDA 12 build or an older driver, imports behave as
before.
(`#3502 <https://github.com/NVIDIA/cuda-python/issues/3502>`__)

- A :class:`Stream` over the NULL stream (handle 0), such as
``Stream.from_handle(0)``, no longer caches the first context and device it
observes. Like ``LEGACY_DEFAULT_STREAM`` and ``PER_THREAD_DEFAULT_STREAM``
since 1.2.0, it now resolves ``Stream.context``, ``Stream.device``,
``Stream.resources`` and ``Stream.record()`` against the current context.
(`#3242 <https://github.com/NVIDIA/cuda-python/issues/3242>`__)
18 changes: 18 additions & 0 deletions cuda_core/tests/test_green_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#
# SPDX-License-Identifier: Apache-2.0

import os

import numpy as np
import pytest
from helpers.contexts import assert_device_operations_use_bound_context, current_context_handle, use_context
Expand All @@ -15,6 +17,7 @@
ProgramOptions,
SMResource,
SMResourceOptions,
Stream,
WorkqueueResource,
WorkqueueResourceOptions,
launch,
Expand Down Expand Up @@ -578,6 +581,21 @@ def test_stream_and_event_track_green_context(self, green_ctx):
stream.sync()
event.sync()

@pytest.mark.skipif(
bool(int(os.environ.get("CUDA_PYTHON_CUDA_PER_THREAD_DEFAULT_STREAM", "0"))),
reason="handle 0 is the per-thread default stream, which green contexts reject",
)
@pytest.mark.agent_authored(model="claude-opus-5-5")
def test_null_stream_follows_current_context(self, init_cuda, green_ctx):
stream = Stream.from_handle(0)
assert stream.context == init_cuda.context

with use_context(init_cuda, green_ctx):
assert stream.context == green_ctx
assert stream.record().context == green_ctx

assert stream.context == init_cuda.context

@pytest.mark.agent_authored(model="gpt-5.6")
def test_device_receiver_targets_stored_green_context(self, init_cuda, green_ctx):
primary_ctx = init_cuda.context
Expand Down
5 changes: 4 additions & 1 deletion cuda_core/tests/test_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,10 @@ def _skip_unless_multi_gpu():


@pytest.mark.agent_authored(model="claude-opus-5")
@pytest.mark.parametrize("stream", [LEGACY_DEFAULT_STREAM, PER_THREAD_DEFAULT_STREAM])
@pytest.mark.parametrize(
"stream",
[LEGACY_DEFAULT_STREAM, PER_THREAD_DEFAULT_STREAM, pytest.param(Stream.from_handle(0), id="null")],
)
def test_default_stream_follows_current_context(stream):
"""A default-stream token denotes whatever context is current, so its
queries follow a context switch instead of reporting the first context
Expand Down