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
Updates for the array/size argument changes - #3561
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.
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.
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 TouchesFix failing CI checks
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.
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.
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)
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.
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)
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.
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
raiseValueError(
"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
raiseValueError(
"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, ...)"
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.functiondelw, 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.
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)
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.
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.
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.
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
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.bindingsEverything related to the cuda.bindings moduleenhancementAny code-related improvements
1 participant
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.
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
_v2APIs 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.