Skip to content

Updates for the array/size argument changes - #3561

Open
mdboom wants to merge 4 commits into
NVIDIA:mainfrom
mdboom:array-size-arguments
Open

mdboom wants to merge 4 commits into
NVIDIA:mainfrom
mdboom:array-size-arguments

Conversation

@mdboom

@mdboom mdboom commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

This brings in generator changes so that array/size argument pairs are handled by using buffers, to prevent buffer overruns.

There are intentional changes to the _v2 APIs here (which are not stable yet, so this if fine).

There is a minor bugfix in the return value in an error case in NVML (see release notes), but otherwise this should have no behavioral change.

@copy-pr-bot

copy-pr-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@mdboom

mdboom commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@mdboom

mdboom commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@github-actions github-actions Bot added the cuda.bindings Everything related to the cuda.bindings module label Nov 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

@mdboom mdboom self-assigned this Nov 30, 2026
@mdboom mdboom added the enhancement Any code-related improvements label Nov 30, 2026
@mdboom mdboom added this to the cuda.bindings 13.6.0 & 12.9.12 milestone Nov 30, 2026
@mdboom
mdboom marked this pull request as ready for review November 30, 2026 14:33
@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Explain Change →

Summary

Summary by CodeRabbit

  • New Features
    • Added support for clearing NVML device field values.
    • Many CUDA driver APIs now accept Python sequences for array inputs and infer item counts automatically. None can represent null pointers or empty dependency lists.
  • Bug Fixes
    • Improved buffer handling to keep buffers available for the duration of native calls.
    • Fixed clearing NVML field values with an empty list.

CUDA bindings update buffer-export lifetimes, revise CUDA 13 driver APIs to accept collections and infer counts, and add NVML field-value clearing. Tests and 13.6.0 release notes reflect these changes.

Changes: Buffer export lifetimes

Layer / File(s) Summary
Buffer guard implementation
cuda_bindings_12/cuda/bindings/{nvfatbin,nvjitlink,nvvm}.pyx, cuda_bindings_13/cuda/bindings/{cudla,nvfatbin,nvjitlink,nvvm}.pyx
Private guards retain acquired buffer exports during native calls. They support None, integer addresses, contiguous buffers, optional size checks, and writable access.
Guarded native calls
cuda_bindings_12/cuda/bindings/{nvfatbin,nvjitlink,nvvm}.pyx, cuda_bindings_13/cuda/bindings/{cudla,nvfatbin,nvjitlink,nvvm}.pyx, cuda_bindings_13/docs/source/release/13.6.0-notes.rst
NVFatbin, NVJitLink, NVVM, and cuDLA calls use guards for buffer arguments. The release notes describe buffer lifetime during C calls.

CUDA driver collection APIs

Layer / File(s) Summary
Array wrappers and driver declarations
cuda_bindings_13/cuda/bindings/_internal/utils.{pxd,pyx}, cuda_bindings_13/cuda/bindings/_v2/driver.{pxd,pyx}, cuda_bindings_13/cuda/bindings/_v2/nvrtc.pyx
Driver parameter wrappers support arrays and sized pointer-backed views. Declarations add functions and replace pointer/count arguments with collection-style inputs. Internal resource conversion accepts None and indexable integer values.
Collection-based driver calls
cuda_bindings_13/cuda/bindings/_v2/driver.{pxd,pyx}, cuda_bindings_13/tests/test_cuda.py, cuda_bindings_13/docs/source/release/13.6.0-notes.rst, cuda_python/docs/source/release/13.6.0-notes.rst
Driver wrappers infer counts from collections and validate lengths and bounds. Tests and release notes reflect revised arguments.
Graph dependency collections
cuda_bindings_13/cuda/bindings/_v2/driver.{pxd,pyx}, cuda_bindings_13/tests/{test_cuda.py,test_interoperability.py}
Graph and stream-capture wrappers infer dependency counts from sequences and validate dependency and edge-data lengths. Tests pass None or node-handle sequences.

NVML field-value handling

Layer / File(s) Summary
Field-value clearing and allocation
cuda_bindings_12/cuda/bindings/nvml.{pxd,pyx}, cuda_bindings_13/cuda/bindings/nvml.{pxd,pyx}, cuda_bindings_13/docs/source/release/13.6.0-notes.rst
The bindings add device_clear_field_values with count validation and an empty-input return. NVML output-array allocation counts are cast to Py_ssize_t. The release notes describe the empty-input behavior.

Suggested reviewers: rwgk

Change: Refactor

Merge Risk: Moderate · up to 1fa0e

This PR keeps buffers alive through native calls and moves several CUDA 13 driver APIs to inferred counts. Several memory-safety and API-contract issues remain open: length checks that disappear under optimized Python, array views that can outlive their owner, JIT output values that are no longer returned, and host-copy sizes that are not checked against buffer length. Resolve or explicitly accept these before merging.

Security architecture risk: Moderate · up to 1fa0e

The update fixes premature buffer release, but a changed module-loading API can still pass a count larger than the storage it allocated. A mutable collection can therefore cause an out-of-bounds access in the calling process without the caller supplying an invalid count.

Retained concerns

  • Minor · security · inferred: CUDA 13 module loading infers its native option count from mutable Python inputs rather than from the storage the binding allocated. The marshaling helpers also query sequence length independently for allocation and copy. If a length changes between those steps, the binding can exceed its vector bounds during marshaling or pass an oversized count to the native driver.

View findings in the submitted review

Security review details

Security Blast Radius

  • inferred — The demonstrated path starts with a caller able to pass Python collections to the CUDA 13 driver binding. A bounds failure affects that caller's process; the inspected path does not establish a remote entrypoint, privilege gain, or cross-tenant effect.

Security Findings and Attack Paths

  • inferred — The new collection route permits a changing sequence length to make the storage extent and inferred count disagree. Cross-argument length agreement cannot detect that mismatch, and checking the native return status happens after the driver has received the pointer and count.

Trust Boundaries and Controls

  • observed — For exported buffers, the guard requests contiguity and, when needed, writability. Once acquisition succeeds, cleanup releases the export even if subsequent validation fails. This protects export lifetime but does not make other Python inputs immutable.

Hardening Proposals

  • proposed — Marshal each sequence into stable owned storage once. Validate the sizes of the resulting native buffers against one another and derive the native count from that same storage. Add regression coverage for changing input lengths and for cleanup when conversion fails.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Finishing Touches
Fix failing CI checks

  • Create a new PR

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

Architecture findings (2)

Advisory architecture findings (2)

  • Minor — CUDA 13 sequence marshalling does not use one authoritative length for allocation, conversion, and native dispatch. If a Python sequence reports different lengths during conversion, the helper can index past its vector or the wrapper can pass a count larger than the backing storage. The base loader accepted raw pointers and a caller-supplied count; the head introduces this mismatch on the sequence path the binding now manages.
  • Minor — LaunchParams_v1.from_ptr now returns a borrowed view when no owner is supplied, whereas the base copied the struct in that case. A caller that releases the original storage after construction can leave the wrapper with a dangling view. Supplying a valid owner retains that owner, but the default no longer preserves the prior lifetime guarantee.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between d95bb2b and dba48e1.

Files selected for processing: 20

  • cuda_bindings_12/cuda/bindings/nvfatbin.pyx
  • cuda_bindings_12/cuda/bindings/nvjitlink.pyx
  • cuda_bindings_12/cuda/bindings/nvml.pxd
  • cuda_bindings_12/cuda/bindings/nvml.pyx
  • cuda_bindings_12/cuda/bindings/nvvm.pyx
  • cuda_bindings_13/cuda/bindings/_internal/utils.pxd
  • cuda_bindings_13/cuda/bindings/_internal/utils.pyx
  • cuda_bindings_13/cuda/bindings/_v2/driver.pxd
  • cuda_bindings_13/cuda/bindings/_v2/driver.pyx
  • cuda_bindings_13/cuda/bindings/_v2/nvrtc.pyx
  • cuda_bindings_13/cuda/bindings/cudla.pyx
  • cuda_bindings_13/cuda/bindings/nvfatbin.pyx
  • cuda_bindings_13/cuda/bindings/nvjitlink.pyx
  • cuda_bindings_13/cuda/bindings/nvml.pxd
  • cuda_bindings_13/cuda/bindings/nvml.pyx
  • cuda_bindings_13/cuda/bindings/nvvm.pyx
  • cuda_bindings_13/docs/source/release/13.6.0-notes.rst
  • cuda_bindings_13/tests/test_cuda.py
  • cuda_bindings_13/tests/test_interoperability.py
  • cuda_python/docs/source/release/13.6.0-notes.rst

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 code was automatically generated across versions from 12.4.1 to 13.5.0. Do not modify it directly.
# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=5017cbd422315ed05d8c8d89fcf7ee2efa806dbccab0e7cc58a646a037f8053a
# CYTHON-BINDINGS-GENERATED-DO-NOT-MODIFY-THIS-FILE: format=1; content-sha256=93a3aa883e727ee9fb62ffe1decd27a9c8f56eb75312e1c3c8ab5457a880c10c

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Maintainability & Code Quality · Quick win

important: Record the generation inputs and command in the PR.

The PR description identifies a generator update, but it does not identify the generator revision, the toolkit inputs for each root, or the regeneration command. A seal verifies file content, not how the file was generated. Add those details so reviewers can reproduce the artifacts. As per coding guidelines, “record the generator revision, toolkit inputs, and command in the pull request.” (github.com)

Source: Coding guidelines

cdef void* ptr
cdef Py_ssize_t nbytes

def __cinit__(self, buf, Py_ssize_t size, bint readonly, bint wrap_errors):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Keep oversized explicit counts on the ValueError path in the buffer guard.

_BufferGuard.__cinit__ declares Py_ssize_t size, but the public wrappers pass a size_t. For a count above PY_SSIZE_T_MAX, Cython can raise OverflowError during argument conversion. This happens before the wrap_errors handler runs. The merge-base helper raised ValueError for the same input, so these calls now raise a different exception type.

Declare the guard's count as size_t. Range-check it inside the guarded body so that an oversized count raises ValueError, as a size mismatch does.

self._held = True
if size != -1:
assert view.len == size
assert self._view.len == size

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 · Quick win

important: Keep the buffer length check active under optimized Python.

Cython omits this check when assertions are disabled. A buffer with a mismatched byte count then reaches the native call with the caller's original size. If the count exceeds the export, the native call can read past it. The old helper had the same gap. Replace assert with an explicit mismatch check in the generator and regenerate both roots. Preserve ValueError for mismatches and allow matching exports to proceed. This applies to the equivalent guards in nvjitlink.pyx and nvvm.pyx. (raw.githubusercontent.com)

deref(vec)[i] = <PtrT*><intptr_t>(obj[i])
# `PyNumber_Index` (`__index__`) since the elements may be NumPy integers, which the cast does not accept,
# and unlike `int()` it rejects floats and strings
deref(vec)[i] = <PtrT*><intptr_t>cpython.PyNumber_Index(obj[i])

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 · Quick win

important: graph_add_empty_node reads len(dependencies) after conversion, so a mutating __index__ can desynchronize the count from the allocation.

get_resource_ptrs allocates the pointer vector with len(obj) and converts each element with PyNumber_Index. That conversion runs the element's __index__, which is caller code. An element can append to the caller's dependencies list during conversion. The loop still writes only the original number of elements. graph_add_empty_node then reads len(dependencies) again at driver.pyx:38678, and that larger value becomes num_dependencies. The native call can read past the vector allocation if it uses that count with the vector's data.

This is new in this PR. At the merge base, graph_add_empty_node takes num_dependencies from the caller and does not re-read the sequence length after conversion.

Use one count for both the allocation and the native argument. Snapshot the sequence before conversion and derive both the vector and the count from that snapshot, or derive num_dependencies from the allocated vector size. Make this change in the generator that emits this wrapper. _v2/driver.pyx is generated, so do not hand-edit it.

Comment on lines +89 to +93
raise ValueError(
"buf must be None, a Python int representing the pointer "
f"address to a valid buffer, or a contiguous {adj}"
f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}"
) from e

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

important: The wrapped error message always includes of size {size}. Every guard call in this file passes size=-1. A wrong-type name, fname, symbol or src_host argument therefore reports "... of size -1". That text is wrong and confusing for users. Add the size clause only when size != -1.

-                    f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}"
+                    f"buffer (a ctypes object, NumPy array, bytes, ...)"
+                    + (f", of size {size}" if size != -1 else "")

Make this change in the generator and regenerate both roots.

Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
raise ValueError(
"buf must be None, a Python int representing the pointer "
f"address to a valid buffer, or a contiguous {adj}"
f"buffer (a ctypes object, NumPy array, bytes, ...), of size {size}"
) from e
raise ValueError(
"buf must be None, a Python int representing the pointer "
f"address to a valid buffer, or a contiguous {adj}"
f"buffer (a ctypes object, NumPy array, bytes, ...)"
+ (f", of size {size}" if size != -1 else "")
) from e

Comment on lines +11051 to +11055
cdef flag = _cyb_cpython_buffer.PyBUF_READ if readonly else _cyb_cpython_buffer.PyBUF_WRITE
cdef object buf = _cyb_cpython_memoryview.PyMemoryView_FromMemory(
<char*>ptr, sizeof(CUDA_LAUNCH_PARAMS_v1) * size, flag)
obj._data = _numpy.ndarray(size, buffer=buf, dtype=launch_params_v1_dtype_record)
obj._owner = owner

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

important: keep owner alive for NumPy views returned by array-backed from_ptr wrappers.

from_ptr keeps owner alive only through the wrapper object. The NumPy array in _data wraps a PyMemoryView_FromMemory buffer, and that buffer holds no reference to owner. A view returned from _data keeps the array and buffer alive, but not owner.

For size > 1, the function getter returns self._data["function"], which is such a view:

w = LaunchParams_v1.from_ptr(p, size=2, owner=o)
f = w.function
del w, o

After del w, o, owner can free the memory at p. Reading or writing through f then accesses freed memory. The integer-key path of __getitem__ keeps owner, but the field getters do not.

Each buffer that _data wraps must hold a strong reference to owner. Then every view derived from _data keeps owner alive. Apply this in the generator template and regenerate both roots. Check the other array-backed from_ptr wrappers in this change for the same construction.

The nvml.pyx wrappers at the merge base use the same owner-less buffer. That pattern predates this PR and needs its own correction.

Comment on lines +25 to +27
library, and released when the function returns. Before, the buffer was released before the call, so another
thread could resize a ``bytearray`` and free its memory during the call. This applies to all the bindings
that take a buffer, such as those of ``nvfatbin``, ``nvjitlink``, ``nvvm`` and ``cudla``. The accepted

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

important: Limit the before-and-after claim to wrappers that changed.

The legacy cuda.bindings.driver.cuModuleLoadData already held a buffer export until the native call returned. It does so in both the merge base and this revision. Limit this note to wrappers that switched from releasing the export before the native call to retaining it through the call. (raw.githubusercontent.com)

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: 1

Architecture findings (1)

Advisory architecture findings (1)

  • Minor — CUDA 13 module loading infers its native option count from mutable Python inputs rather than from the storage the binding allocated. The marshaling helpers also query sequence length independently for allocation and copy. If a length changes between those steps, the binding can exceed its vector bounds during marshaling or pass an oversized count to the native driver.
Nitpick comments: 1

cuda_bindings_13/cuda/bindings/_v2/driver.pyx: 1

32165-32166: Trivial · Stability & Availability · Quick win

suggestion: _cyb_BufferGuard now records nbytes, but memcpy_dtoh_v2 never compares it with byte_count. For example, memcpy_dtoh_v2(bytearray(4), src, 1 << 20) writes past the host buffer. This behavior existed before this PR. It is still an unchecked array/size pair, which is the defect class this PR targets.

The same gap exists in these wrappers:

  • memcpy_htod_v2
  • memcpy_htoa_v2 and memcpy_atoh_v2
  • the *_async_v2 variants
  • mem_host_register_v2

When the guard holds a buffer, raise ValueError if byte_count > guard.nbytes. Skip the check for integer addresses. Make this change in the generator.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between dba48e1 and 1fa0e17.

Files selected for processing: 3

  • cuda_bindings_13/cuda/bindings/_v2/driver.pyx
  • cuda_bindings_13/tests/test_cuda.py
  • cuda_bindings_13/tests/test_interoperability.py
Files with no reviewable changes: 1

  • cuda_bindings_13/tests/test_interoperability.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.

@@ -29853,20 +30538,27 @@ cpdef intptr_t library_load_data(code, intptr_t jit_options, intptr_t jit_option
compilation.
Options are passed as an array via ``jit_options`` and any corresponding
parameters are passed in ``jit_optionsValues``. The number of total JIT options
is supplied via ``num_jit_options``. Any outputs will be returned via
is supplied via ``len(jit_options)``. Any outputs will be returned via

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

important: JIT output values are dropped, but the docstring still says "Any outputs will be returned via jit_optionsValues".

_cyb_get_resource_ptrs[void] copies jit_options_values into a temporary _cyb_vector[void*]. The driver writes output options into that vector, for example CU_JIT_WALL_TIME and the log sizes it actually used. The vector is freed when the call returns. The wrapper now rejects integer addresses, so a caller can no longer pass their own array and read it back.

The same loss applies to module_load_data_ex, link_add_data_v2 and link_add_file_v2. link_create_v2 documents this limitation; these functions do not.

Fix this in the generator. Either return the written-back values, or remove the "outputs returned" claim and state the limitation as link_create_v2 does.

Also applies to: 30661-30661

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

cuda.bindings Everything related to the cuda.bindings module enhancement Any code-related improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant