Skip to content

Add cuda.bindings._v2.runtime - #3688

Draft
mdboom wants to merge 3 commits into
NVIDIA:mainfrom
mdboom:runtime-v2
Draft

mdboom wants to merge 3 commits into
NVIDIA:mainfrom
mdboom:runtime-v2

Conversation

@mdboom

@mdboom mdboom commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

See generator MR !638.

This is based on #3561, which should be merged first.

@mdboom

mdboom commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test

@mdboom mdboom self-assigned this Dec 2, 2026
@mdboom mdboom added the cuda.bindings Everything related to the cuda.bindings module label Dec 2, 2026
@mdboom mdboom added this to the cuda.bindings 13.6.0 & 12.9.12 milestone Dec 2, 2026
@mdboom mdboom added the enhancement Any code-related improvements label Dec 2, 2026
@copy-pr-bot

copy-pr-bot Bot commented Dec 2, 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 marked this pull request as ready for review December 3, 2026 17:58
@coderabbitai

coderabbitai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Explain Change →

Summary

Summary by CodeRabbit

  • New Features
    • Added an experimental CUDA Runtime v2 API with modern naming, direct return values, and typed exceptions.
    • Expanded CUDA Driver v2 support, including newer APIs, simplified array-based inputs, and non-raising stream and event queries.
    • Added support for clearing NVML device field values and passing integer native handles directly.
  • Bug Fixes
    • Improved buffer handling and validation across CUDA operations, including checks for contiguity, writability, and expected sizes.
    • Added validation for mismatched NVML value lengths and improved handling of empty field-value lists.
  • Documentation
    • Added Runtime v2 API documentation and migration guidance.

Adds the experimental CUDA Runtime v2 module for CUDA 12.9–13.5 and revises CUDA 13 v2 driver APIs to infer array sizes and counts. Updates buffer lifetime handling across bindings, migrates tests, adds API and migration documentation, and updates legacy bindings and release tooling.

Changes: CUDA bindings and supporting updates

Layer / File(s) Summary
Buffer and resource handling
cuda_bindings_12/cuda/bindings/_internal/*, cuda_bindings_12/cuda/bindings/nvfatbin.pyx, cuda_bindings_12/cuda/bindings/nvjitlink.pyx, cuda_bindings_12/cuda/bindings/nvvm.pyx, cuda_bindings_13/cuda/bindings/_internal/*, cuda_bindings_13/cuda/bindings/{cudla,nvfatbin,nvjitlink,nvvm}.pyx
Adds contiguous-buffer acquisition and guards that retain buffer exports through native calls. Resource conversion now handles None, integer-like addresses, and character-resource subclasses.
NVML field clearing and array sizing
cuda_bindings_12/cuda/bindings/nvml.*, cuda_bindings_13/cuda/bindings/nvml.*
Adds device_clear_field_values with length and count validation. NVML result-array shapes now cast counts to Py_ssize_t.
Legacy runtime declarations and wrappers
cuda_bindings_12/cuda/bindings/cyruntime.*, cuda_bindings_12/cuda/bindings/runtime.pyx, cuda_bindings_12/docs/source/module/runtime.rst, cuda_bindings_13/cuda/bindings/cyruntime.*, cuda_bindings_13/cuda/bindings/runtime.pyx, cuda_bindings_13/cuda/bindings/_v2/nvrtc.pyx, cuda_bindings_13/docs/source/module/runtime.rst
Relocates CUDA runtime declarations and wrappers without changing the cudaGLGetDevices signature or delegation. Updates runtime API documentation and NVRTC array sizing.
Driver v2 data wrappers and declarations
cuda_bindings_13/cuda/bindings/_v2/driver.pxd, cuda_bindings_13/cuda/bindings/_v2/driver.pyx
Updates driver declarations and implements sized NumPy-backed parameter wrappers, owner-retaining views, and public type renames.
Driver v2 argument and status handling
cuda_bindings_13/cuda/bindings/_v2/driver.pyx
Changes wrappers to infer counts and sizes from sequences or typed arrays. Adds query variants, context creation, graph-update status handling, linker-option lifetime management, and caller-sized GL device results.
CUDA Runtime v2 module
cuda_bindings_13/cuda/bindings/_v2/runtime.pxd, cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, cuda_bindings_13/cuda/bindings/utils/__init__.py
Adds Runtime v2 declarations and implementation, including runtime types, error mapping, conversions, and API wrappers. Exact int objects now pass through native-handle extraction.
V2 API reference and migration documentation
cuda_bindings_13/docs/source/api.rst, cuda_bindings_13/docs/source/module/{driver_v2,runtime_v2,v2_migration}.rst, cuda_bindings_13/docs/source/release/13.6.0-notes.rst, cuda_python/docs/source/release/13.6.0-notes.rst
Adds Runtime v2 API and migration documentation. Updates Driver v2 references and release notes.
Legacy API test coverage
cuda_bindings_13/tests/legacy_api/*
Adds tests for legacy runtime operations, callback registration, graphics interoperability, utility functions, and graph-parameter wrapper lifetimes.
V2 API tests and call-site migration
cuda_bindings_13/tests/*
Migrates driver and runtime tests to v2 APIs and adds checks for queries, errors, graph updates, wrappers, and native handles.
Release and documentation environment updates
.pre-commit-config.yaml, cuda_python/docs/environment-docs.yml, toolshed/setup-docs-env.sh
Updates large-file exclusions and removes pyclibrary from the documentation environments.

Possibly related issues

  • NVIDIA/cuda-python#3193 — The PR adds owner-retaining buffer helpers and array wrappers in related v2 bindings, but the issue describes getter ownership behavior not confirmed by the supplied summaries for the new Runtime module.

Suggested reviewers: rwgk

Change: Feature

Merge Risk: Moderate · up to fcabe

The new Runtime v2 module and revised driver v2 calls introduce a few memory-safety and data-integrity concerns that should be addressed before merging. The main ones are batch copies silently pairing entries incorrectly when multidimensional buffers use different layouts, and several unresolved concerns about buffer sizing in the new Runtime v2 bindings. The affected APIs are experimental, but the remaining concerns should be resolved or explicitly accepted first.

Architecture risk: Low · up to fcabe

CUDA binding consumers gain a Runtime v2 module and must follow revised driver v2 call signatures, while native-call buffer lifetimes and selected NVML inputs receive stronger safeguards.

For affected driver v2 calls, callers must supply length-bearing sequences instead of explicit counts so the wrapper can derive sizes; Runtime v2 status-checking calls raise mapped errors while its no-raise queries return raw statuses.

Changed areas: cuda_bindings_13, cuda_bindings_12, cuda_python, toolshed

This update did not reassess the architecture findings from the earlier review.

Review details

Systems and components

  • observed — 36 changed files mapped to cuda_bindings_13.
  • observed — 11 changed files mapped to cuda_bindings_12.
  • observed — 2 changed files mapped to cuda_python.
  • observed — 1 changed file mapped to toolshed.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@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

Critical 1
  1. critical: mem_get_location_info passes a 1-element output buffer, but the driver writes ceil(size / summary_granularity) entries.
Major 7
  1. important: Keep NumPy optional at module import.
  2. important: TextureDesc.address_mode uses 8-byte items for a field of three 4-byte enums.
  3. important: stream_get_capture_info returns NumPy arrays that point into driver-owned memory.
  4. important:** Keep the backing array alive through native submission.
  5. important:** Derive num_library_options from the converted vector.
  6. important: Register a real log callback.
  7. Check buffer capacity before memcpy and memcpy_async.
Minor 16
  1. important: **Resolve the None attribute contract for nonempty copy batches.** The wrapper documents that callers can pass None for both attrs and attrs_idxs. For a batch with one copy, it forwards two null pointers and numAttrs=0. CUDA requires an attribute set for every copy in a nonempty batch. Either supply a documented default attribute set or require both buffers. Preserve the working case with an explicit attribute and starting index 0. ([raw.githubusercontent.com](https://raw.githubusercontent.com/NVIDIA/cuda-python/89cceb7a0ab2b7a7bebd74d77cff72c5a343f1c4/cuda_bindings_13/cuda/bindings/_v2/runtime.pyx))
  2. cuda_bindings_13/cuda/bindings/_v2/runtime.pxd, lines 141 · 🗄️ Data Integrity & Integration · ⚡ Quick win
    important: Do not return 0 as the continuation cursor for a full log dump. When iterator=None, the implementation passes NULL to CUDA. CUDA dumps the retained entries but does not update the local it. The wrapper then returns the initial 0, although its docstring promises a cursor that resumes after the dump. (raw.githubusercontent.com)
    Return and document None for the full-dump path, and preserve the updated integer for calls that supply a cursor. Update the generated declaration to represent both results.
  3. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 14069 · 🩺 Stability & Availability · ⚡ Quick win
    suggestion: The DeviceProp.name and DeviceProp.luid setters read past the end of the source bytes object.
    buf = val.encode() has len(buf) + 1 valid bytes. _cyb_memcpy(..., ptr, 256) and _cyb_memcpy(..., ptr, 8) always copy the full field size. A short value, for example "abc", reads up to 252 bytes past the bytes object. That copies unrelated heap memory into the struct and can fault.
    In the generator, zero the field first, then copy len(buf) + 1 bytes.
    -    _cyb_memcpy(<void *>(self._ptr[0].name), <void *>ptr, 256)
    +    _c_memset(<void *>(self._ptr[0].name), 0, 256)
    +    _cyb_memcpy(<void *>(self._ptr[0].name), <void *>ptr, len(buf) + 1)
    
    Also applies to: 14084-14084
    Source: Coding guidelines
  4. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 14074 · 🎯 Functional Correctness · ⚡ Quick win
    suggestion: DeviceProp.luid decodes an 8-byte binary identifier as a NUL-terminated UTF-8 string.
    luid holds raw bytes, and on non-TCC Windows they can be any value. PyUnicode_FromString stops only at a NUL byte. If the 8 bytes contain no NUL, it reads past the field into luidDeviceNodeMask. Non-UTF-8 bytes raise UnicodeDecodeError, so reading this property can fail on a valid device.
    In the generator, return the raw bytes value (self._ptr[0].luid[:8]), as Uuid.bytes already does. Make the setter take exactly 8 bytes.
    Source: Coding guidelines
  5. cuda_bindings_13/cuda/bindings/_v2/driver.pyx, lines 45776–45778 · 🎯 Functional Correctness · ⚡ Quick win
    important: Do not advertise a discovery-only mode that this wrapper cannot select.
    The docstring says callers can omit the result buffer and update only group_params. The wrapper always passes a non-NULL result buffer. CUDA can report success with a discovered group size of zero only in the NULL-result mode. Expose that mode explicitly, or state that this wrapper always requests concrete groups. (raw.githubusercontent.com)
  6. cuda_bindings_13/cuda/bindings/_v2/driver.pyx, lines 28067 · 🩺 Stability & Availability · ⚡ Quick win
    important: Handle registry failure after creating the link state.
    If registry insertion raises MemoryError, cuLinkCreate has already succeeded. The caller gets no handle to destroy, and neither the link state nor its retained option array is cleaned up. Arrange for ownership bookkeeping before native creation, or roll back the native state if registration fails. Do not free the option array while CUDA can still access it. (docs.nvidia.com)
  7. cuda_bindings_13/tests/test_cudart.py, lines 1393–1394 · 🎯 Functional Correctness · ⚡ Quick win
    important: Do not suppress every child-graph creation error.
    If graph_add_node raises InvalidValueError or another CudaError, this test now passes without checking either nested graph relationship. Remove this handler. If a supported environment requires an exception allowance, restrict it to the documented status and report an explicit skip.
    As per coding guidelines, “Do not add broad catches, success-shaped fallbacks, or silent early returns on invalid input; propagate or surface errors explicitly.”
    Source: Coding guidelines
  8. cuda_bindings_13/docs/source/module/runtime_v2.rst, lines 700 · 🎯 Functional Correctness · ⚡ Quick win
    important: Reference the v2 OpenGL enumeration.
    These directives document legacy attributes already listed in runtime.rst. Use GLDeviceList.ALL, CURRENT_FRAME and NEXT_FRAME from _v2.runtime, or remove these redundant directives. The v2 enumeration uses those names. (raw.githubusercontent.com)
    Also applies to: 704-704, 708-708
  9. cuda_bindings_13/docs/source/module/v2_migration.rst, lines 148 · 🎯 Functional Correctness · ⚡ Quick win
    important: Document the explicit-count exception for fabric copies.
    fabric_cpy_batch_async still requires (num_ops, op_list, flags, h_stream), with op_list as an integer address. Following this count-removal rule produces a missing-argument error. Qualify the rule and document this exception in its mapping row. (raw.githubusercontent.com)
  10. cuda_bindings_13/docs/source/module/v2_migration.rst, lines 3470–3472 · 🎯 Functional Correctness · ⚡ Quick win
    important: Document buffer-only Runtime batch inputs.
    The general rule permits lists, but memcpy_batch_async([dst], [src], [4], None, None, stream) raises TypeError: acquire_contiguous_buffer rejects lists. Add the required buffer inputs and item widths here. Correctly typed NumPy buffers remain supported. (raw.githubusercontent.com)
  11. important: Release both resources after the capture query.
    cuda_bindings_13/tests/legacy_api/test_legacy_cudart.py, lines 628 · 🩺 Stability & Availability · ⚡ Quick win
    This test returns after cudaStreamEndCapture without destroying pgraph or stream. The v2 test has the same omission, so the combined suite retains two streams and two graphs per run of the pair. If the active-status assertion fails, the legacy test also exits before ending capture. End capture in a cleanup block after a successful begin, destroy any graph returned by end-capture, and always destroy the stream. (raw.githubusercontent.com)
  12. important: Check the legacy unregister status.
    cuda_bindings_13/tests/legacy_api/test_legacy_graphics_apis.py, lines 120 · 🎯 Functional Correctness · ⚡ Quick win
    If cudaGraphicsUnregisterResource returns cudaErrorInvalidResourceHandle, this smoke test still passes and _gl_context tears down the texture and window. Assert cudaSuccess on the returned status before leaving the context. Keep the existing branch for environments that reject registration. (raw.githubusercontent.com)
  13. important: Fail the legacy graph test when the node query fails.
    cuda_bindings_13/tests/legacy_api/test_legacy_cudart.py, lines 251 · 🎯 Functional Correctness · ⚡ Quick win
    If the count query returns three but the filled query returns an error, this test can still pass. It ignores both statuses and never checks the returned nodes. Check both statuses and assert that the filled query returns the three nodes created above. The v2 test checks its result, but it does not exercise the legacy tuple-returning wrapper. (raw.githubusercontent.com)
  14. important: Keep the shared utility tests in the canonical suite.
    cuda_bindings_13/tests/legacy_api/test_legacy_utils.py, lines 63 · 📐 Maintainability & Code Quality · ⚡ Quick win
    Both files run the same PTX parser and NVVM option checks through the same functions. These copies add no legacy coverage and leave two places to maintain the same expectations. Remove the duplicate utility tests from this file. Keep only cases that exercise a distinct legacy contract, such as extracting handles from legacy wrapper types. (raw.githubusercontent.com)
    As per coding guidelines, “These test files should not be added to, only updated when necessary to fix test failures.”
    Also applies to: 151-151
    Source: Coding guidelines
  15. suggestion: A failed t.start() can leave the test process hanging.
    cuda_bindings_13/tests/legacy_api/test_legacy_callback_threads.py, lines 41 · 🩺 Stability & Availability · ⚡ Quick win
    If t.start() raises at line 41, the workers already started wait at barrier.wait() (line 30). The barrier needs all 16 parties, so they never leave. The threads are non-daemon, so the interpreter waits for them at exit. The test can fail and then the process does not exit. This needs a thread-start failure, which is rare.
    Abort the barrier when starting fails, then join the threads that did start. Released workers record a BrokenBarrierError in failures, and the test still reports the original error.
    Suggested fix
         threads = [threading.Thread(target=worker) for _ in range(NUM_THREADS)]
    -    for t in threads:
    -        t.start()
    -    for t in threads:
    -        t.join()
    +    try:
    +        for t in threads:
    +            t.start()
    +    except BaseException:
    +        barrier.abort()
    +        raise
    +    finally:
    +        for t in threads:
    +            if t.ident is not None:
    +                t.join()
    
    Failure path: thread 1 starts and waits at line 30. Thread 2 fails to start. barrier.abort() releases thread 1 with BrokenBarrierError, which the handler records. The finally block joins thread 1, and the RuntimeError propagates.
    Success path: all 16 threads start, no exception occurs, the finally block joins all threads, and the barrier releases normally, as before.
  16. important: Preserve the empty-input return value.
    cuda_bindings_13/cuda/bindings/nvml.pyx, lines 36345 · 🎯 Functional Correctness · ⚡ Quick win
    For values = FieldValue(0), the previous implementation returned values. This branch now returns None, so callers that use len(result) fail with TypeError. Restore return _values_obj_ in the generator and regenerate. Nonempty calls can keep their existing return behavior. As per coding guidelines, “prioritize correctness and API compatibili(raw.githubusercontent.com)
    Source: Coding guidelines
Trivial 2
  1. A Driver v2 link state created with options can be successfully destroyed through the legacy wrapper without releasing the v2-owned option array. The merge-base wrapper had no private allocation to strand. Repeating mixed-interface cleanup can accumulate process-local allocations; reusing a handle key does not free the old allocation.
  2. Driver v2 records its option-array allocation in a Python dictionary after native creation succeeds and outside the cleanup block. If registration raises, the caller receives no handle and the wrapper neither destroys the native state nor releases its retained option array. The merge-base wrapper did not have this post-create registration step.
Nitpick 1
  1. cuda_bindings_13/cuda/bindings/nvfatbin.pyx, lines 48 · 📐 Maintainability & Code Quality · ⚡ Quick win
    suggestion: Use one explicit buffer-size check in the generator. The replaced helper and the new nvfatbin, nvjitlink, and nvvm guards use assert to check the exported size. Runtime v2 already uses an explicit check. Reuse that pattern in the generator for both roots. A mismatched buffer should raise ValueError even when assertions are disabled. Exact-size buffers and unsized output calls should keep working. (raw.githubusercontent.com)

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 56dce6e and 89cceb7.

Files selected for processing: 51

  • .pre-commit-config.yaml
  • cuda_bindings_12/cuda/bindings/_internal/utils.pxd
  • cuda_bindings_12/cuda/bindings/_internal/utils.pyx
  • cuda_bindings_12/cuda/bindings/cyruntime.pxd
  • cuda_bindings_12/cuda/bindings/cyruntime.pyx
  • 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_12/cuda/bindings/runtime.pyx
  • cuda_bindings_12/docs/source/module/runtime.rst
  • 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/_v2/runtime.pxd
  • cuda_bindings_13/cuda/bindings/_v2/runtime.pyx
  • cuda_bindings_13/cuda/bindings/cudla.pyx
  • cuda_bindings_13/cuda/bindings/cyruntime.pxd
  • cuda_bindings_13/cuda/bindings/cyruntime.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/cuda/bindings/runtime.pyx
  • cuda_bindings_13/cuda/bindings/utils/__init__.py
  • cuda_bindings_13/docs/source/api.rst
  • cuda_bindings_13/docs/source/module/driver_v2.rst
  • cuda_bindings_13/docs/source/module/runtime.rst
  • cuda_bindings_13/docs/source/module/runtime_v2.rst
  • cuda_bindings_13/docs/source/module/v2_migration.rst
  • cuda_bindings_13/docs/source/release/13.6.0-notes.rst
  • cuda_bindings_13/tests/legacy_api/test_legacy_callback_threads.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_cudart.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_graph_node_params_lifetime.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_graphics_apis.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_utils.py
  • cuda_bindings_13/tests/test_callback_threads.py
  • cuda_bindings_13/tests/test_cuda.py
  • cuda_bindings_13/tests/test_cudart.py
  • cuda_bindings_13/tests/test_graph_node_params_lifetime.py
  • cuda_bindings_13/tests/test_graphics_apis.py
  • cuda_bindings_13/tests/test_interoperability.py
  • cuda_bindings_13/tests/test_kernelParams.py
  • cuda_bindings_13/tests/test_utils.py
  • cuda_python/docs/environment-docs.yml
  • cuda_python/docs/source/release/13.6.0-notes.rst
  • toolshed/setup-docs-env.sh
Files with no reviewable changes: 1

  • cuda_python/docs/environment-docs.yml

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

try:
barrier.wait()
for _ in range(NUM_ITERATIONS):
err, handle = driver.cuLogsRegisterCallback(0, None)

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: Register a real log callback.

The legacy binding accepts 0, stores it as the callback, and registers a non-null trampoline with CUDA. If CUDA delivers a log before unregister, the trampoline calls the null pointer and can terminate pytest. Use a no-op C callback, as the v2 test does. Keep it alive until all workers join. (raw.githubusercontent.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

Major 2
  1. important: Keep NumPy optional at module import.
  2. important: Register a real log callback.
Minor 15
  1. cuda_bindings_13/cuda/bindings/_v2/runtime.pxd, lines 141 · 🗄️ Data Integrity & Integration · ⚡ Quick win
    important: Do not return 0 as the continuation cursor for a full log dump. When iterator=None, the implementation passes NULL to CUDA. CUDA dumps the retained entries but does not update the local it. The wrapper then returns the initial 0, although its docstring promises a cursor that resumes after the dump. (raw.githubusercontent.com)
    Return and document None for the full-dump path, and preserve the updated integer for calls that supply a cursor. Update the generated declaration to represent both results.
  2. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 14069 · 🩺 Stability & Availability · ⚡ Quick win
    suggestion: The DeviceProp.name and DeviceProp.luid setters read past the end of the source bytes object.
    buf = val.encode() has len(buf) + 1 valid bytes. _cyb_memcpy(..., ptr, 256) and _cyb_memcpy(..., ptr, 8) always copy the full field size. A short value, for example "abc", reads up to 252 bytes past the bytes object. That copies unrelated heap memory into the struct and can fault.
    In the generator, zero the field first, then copy len(buf) + 1 bytes.
    -    _cyb_memcpy(<void *>(self._ptr[0].name), <void *>ptr, 256)
    +    _c_memset(<void *>(self._ptr[0].name), 0, 256)
    +    _cyb_memcpy(<void *>(self._ptr[0].name), <void *>ptr, len(buf) + 1)
    
    Also applies to: 14084-14084
    Source: Coding guidelines
  3. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 14074 · 🎯 Functional Correctness · ⚡ Quick win
    suggestion: DeviceProp.luid decodes an 8-byte binary identifier as a NUL-terminated UTF-8 string.
    luid holds raw bytes, and on non-TCC Windows they can be any value. PyUnicode_FromString stops only at a NUL byte. If the 8 bytes contain no NUL, it reads past the field into luidDeviceNodeMask. Non-UTF-8 bytes raise UnicodeDecodeError, so reading this property can fail on a valid device.
    In the generator, return the raw bytes value (self._ptr[0].luid[:8]), as Uuid.bytes already does. Make the setter take exactly 8 bytes.
    Source: Coding guidelines
  4. cuda_bindings_13/cuda/bindings/_v2/driver.pyx, lines 45776–45778 · 🎯 Functional Correctness · ⚡ Quick win
    important: Do not advertise a discovery-only mode that this wrapper cannot select.
    The docstring says callers can omit the result buffer and update only group_params. The wrapper always passes a non-NULL result buffer. CUDA can report success with a discovered group size of zero only in the NULL-result mode. Expose that mode explicitly, or state that this wrapper always requests concrete groups. (raw.githubusercontent.com)
  5. cuda_bindings_13/cuda/bindings/_v2/driver.pyx, lines 28067 · 🩺 Stability & Availability · ⚡ Quick win
    important: Handle registry failure after creating the link state.
    If registry insertion raises MemoryError, cuLinkCreate has already succeeded. The caller gets no handle to destroy, and neither the link state nor its retained option array is cleaned up. Arrange for ownership bookkeeping before native creation, or roll back the native state if registration fails. Do not free the option array while CUDA can still access it. (docs.nvidia.com)
  6. cuda_bindings_13/tests/test_cudart.py, lines 1393–1394 · 🎯 Functional Correctness · ⚡ Quick win
    important: Do not suppress every child-graph creation error.
    If graph_add_node raises InvalidValueError or another CudaError, this test now passes without checking either nested graph relationship. Remove this handler. If a supported environment requires an exception allowance, restrict it to the documented status and report an explicit skip.
    As per coding guidelines, “Do not add broad catches, success-shaped fallbacks, or silent early returns on invalid input; propagate or surface errors explicitly.”
    Source: Coding guidelines
  7. cuda_bindings_13/docs/source/module/runtime_v2.rst, lines 700 · 🎯 Functional Correctness · ⚡ Quick win
    important: Reference the v2 OpenGL enumeration.
    These directives document legacy attributes already listed in runtime.rst. Use GLDeviceList.ALL, CURRENT_FRAME and NEXT_FRAME from _v2.runtime, or remove these redundant directives. The v2 enumeration uses those names. (raw.githubusercontent.com)
    Also applies to: 704-704, 708-708
  8. cuda_bindings_13/docs/source/module/v2_migration.rst, lines 148 · 🎯 Functional Correctness · ⚡ Quick win
    important: Document the explicit-count exception for fabric copies.
    fabric_cpy_batch_async still requires (num_ops, op_list, flags, h_stream), with op_list as an integer address. Following this count-removal rule produces a missing-argument error. Qualify the rule and document this exception in its mapping row. (raw.githubusercontent.com)
  9. cuda_bindings_13/docs/source/module/v2_migration.rst, lines 3470–3472 · 🎯 Functional Correctness · ⚡ Quick win
    important: Document buffer-only Runtime batch inputs.
    The general rule permits lists, but memcpy_batch_async([dst], [src], [4], None, None, stream) raises TypeError: acquire_contiguous_buffer rejects lists. Add the required buffer inputs and item widths here. Correctly typed NumPy buffers remain supported. (raw.githubusercontent.com)
  10. important: Release both resources after the capture query.
    cuda_bindings_13/tests/legacy_api/test_legacy_cudart.py, lines 628 · 🩺 Stability & Availability · ⚡ Quick win
    This test returns after cudaStreamEndCapture without destroying pgraph or stream. The v2 test has the same omission, so the combined suite retains two streams and two graphs per run of the pair. If the active-status assertion fails, the legacy test also exits before ending capture. End capture in a cleanup block after a successful begin, destroy any graph returned by end-capture, and always destroy the stream. (raw.githubusercontent.com)
  11. important: Check the legacy unregister status.
    cuda_bindings_13/tests/legacy_api/test_legacy_graphics_apis.py, lines 120 · 🎯 Functional Correctness · ⚡ Quick win
    If cudaGraphicsUnregisterResource returns cudaErrorInvalidResourceHandle, this smoke test still passes and _gl_context tears down the texture and window. Assert cudaSuccess on the returned status before leaving the context. Keep the existing branch for environments that reject registration. (raw.githubusercontent.com)
  12. important: Fail the legacy graph test when the node query fails.
    cuda_bindings_13/tests/legacy_api/test_legacy_cudart.py, lines 251 · 🎯 Functional Correctness · ⚡ Quick win
    If the count query returns three but the filled query returns an error, this test can still pass. It ignores both statuses and never checks the returned nodes. Check both statuses and assert that the filled query returns the three nodes created above. The v2 test checks its result, but it does not exercise the legacy tuple-returning wrapper. (raw.githubusercontent.com)
  13. important: Keep the shared utility tests in the canonical suite.
    cuda_bindings_13/tests/legacy_api/test_legacy_utils.py, lines 63 · 📐 Maintainability & Code Quality · ⚡ Quick win
    Both files run the same PTX parser and NVVM option checks through the same functions. These copies add no legacy coverage and leave two places to maintain the same expectations. Remove the duplicate utility tests from this file. Keep only cases that exercise a distinct legacy contract, such as extracting handles from legacy wrapper types. (raw.githubusercontent.com)
    As per coding guidelines, “These test files should not be added to, only updated when necessary to fix test failures.”
    Also applies to: 151-151
    Source: Coding guidelines
  14. suggestion: A failed t.start() can leave the test process hanging.
    cuda_bindings_13/tests/legacy_api/test_legacy_callback_threads.py, lines 41 · 🩺 Stability & Availability · ⚡ Quick win
    If t.start() raises at line 41, the workers already started wait at barrier.wait() (line 30). The barrier needs all 16 parties, so they never leave. The threads are non-daemon, so the interpreter waits for them at exit. The test can fail and then the process does not exit. This needs a thread-start failure, which is rare.
    Abort the barrier when starting fails, then join the threads that did start. Released workers record a BrokenBarrierError in failures, and the test still reports the original error.
    Suggested fix
         threads = [threading.Thread(target=worker) for _ in range(NUM_THREADS)]
    -    for t in threads:
    -        t.start()
    -    for t in threads:
    -        t.join()
    +    try:
    +        for t in threads:
    +            t.start()
    +    except BaseException:
    +        barrier.abort()
    +        raise
    +    finally:
    +        for t in threads:
    +            if t.ident is not None:
    +                t.join()
    
    Failure path: thread 1 starts and waits at line 30. Thread 2 fails to start. barrier.abort() releases thread 1 with BrokenBarrierError, which the handler records. The finally block joins thread 1, and the RuntimeError propagates.
    Success path: all 16 threads start, no exception occurs, the finally block joins all threads, and the barrier releases normally, as before.
  15. important: Preserve the empty-input return value.
    cuda_bindings_13/cuda/bindings/nvml.pyx, lines 36345 · 🎯 Functional Correctness · ⚡ Quick win
    For values = FieldValue(0), the previous implementation returned values. This branch now returns None, so callers that use len(result) fail with TypeError. Restore return _values_obj_ in the generator and regenerate. Nonempty calls can keep their existing return behavior. As per coding guidelines, “prioritize correctness and API compatibili(raw.githubusercontent.com)
    Source: Coding guidelines
Trivial 2
  1. A Driver v2 link state created with options can be successfully destroyed through the legacy wrapper without releasing the v2-owned option array. The merge-base wrapper had no private allocation to strand. Repeating mixed-interface cleanup can accumulate process-local allocations; reusing a handle key does not free the old allocation.
  2. Driver v2 records its option-array allocation in a Python dictionary after native creation succeeds and outside the cleanup block. If registration raises, the caller receives no handle and the wrapper neither destroys the native state nor releases its retained option array. The merge-base wrapper did not have this post-create registration step.
Nitpick 1
  1. cuda_bindings_13/cuda/bindings/nvfatbin.pyx, lines 48 · 📐 Maintainability & Code Quality · ⚡ Quick win
    suggestion: Use one explicit buffer-size check in the generator. The replaced helper and the new nvfatbin, nvjitlink, and nvvm guards use assert to check the exported size. Runtime v2 already uses an explicit check. Reuse that pattern in the generator for both roots. A mismatched buffer should raise ValueError even when assertions are disabled. Exact-size buffers and unsized output calls should keep working. (raw.githubusercontent.com)
Outside diff 7
  1. cuda_bindings_13/cuda/bindings/_v2/driver.pyx, lines 30761 · 🗄️ Data Integrity & Integration · ⚡ Quick win
    important: Derive num_library_options from the converted vector.
    Both loaders convert library_options before converting library_option_values. The values sequence can run Python while it is read. If it changes the original options list, the later len(library_options) can match the values count but exceed the size of the options vector passed to CUDA. Use the converted vector’s size, as the JIT option path does. Preserve None for options that do not require a values array. (raw.githubusercontent.com)
    Based on learnings, library option elements are expected to be LibraryOption members or plain integers. This failure does not require custom option elements.
    Also applies to: 30881-30881
    Source: Learnings
  2. cuda_bindings_13/cuda/bindings/_v2/driver.pyx, lines 41000–41001 · 🩺 Stability & Availability · 🏗️ Heavy lift
    important: Keep the backing array alive through native submission.
    graph_add_node_v2 and graph_add_node_v3 save the edge-data address and length before calling int(node_params). That conversion can replace the array behind GraphEdgeData. The saved address and length still describe the old array, but the wrapper no longer retains it. The batch-copy and prefetch wrappers have the same gap when they borrow attributes or locations before converting the index sequence. Acquire a contiguous export and derive both the address and count from that export. Hold it until the native call returns. (raw.githubusercontent.com)
    Also applies to: 46813-46814, 44814-44815, 45163-45164, 45374-45375
  3. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 10666–10678 · 🗄️ Data Integrity & Integration · ⚡ Quick win
    important: TextureDesc.address_mode uses 8-byte items for a field of three 4-byte enums.
    cudaTextureDesc.addressMode is cudaTextureAddressMode[3]. The struct dtype in this file declares it as (_numpy.int32, 3), which is 12 bytes. The getter builds a view.array with itemsize=sizeof(intptr_t) and format="q", which covers 24 bytes. The returned values therefore mix addressMode with filterMode, readMode and sRGB. The setter copies sizeof(intptr_t) * 3 bytes and overwrites filterMode, readMode and sRGB. Any user who sets address_mode gets a corrupted texture descriptor.
    In the generator, use the element type of the field: itemsize=sizeof(int), format="i", dtype=_numpy.int32, and memcpy(..., sizeof(int) * 3). Then regenerate. Also check every other enum-array field that the template emits with format="q".
    As per coding guidelines: "Do not hand-edit generated binding files".
    Source: Coding guidelines
  4. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 20617 · 🗄️ Data Integrity & Integration · ⚡ Quick win
    important: Resolve the None attribute contract for nonempty copy batches. The wrapper documents that callers can pass None for both attrs and attrs_idxs. For a batch with one copy, it forwards two null pointers and numAttrs=0. CUDA requires an attribute set for every copy in a nonempty batch. Either supply a documented default attribute set or require both buffers. Preserve the working case with an explicit attribute and starting index 0. (raw.githubusercontent.com)
  5. Check buffer capacity before memcpy and memcpy_async.
    cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 24905–24907 · 🩺 Stability & Availability · ⚡ Quick win
    Both wrappers acquire dst and src with check_size=False. The guards check contiguity and writability, but not capacity. count then goes to CUDA unchanged. A dst export shorter than count lets CUDA write past the end of the Python buffer. For example, dst=bytearray(4) with count=1000 writes 1000 bytes into a 4-byte buffer. An undersized src has the same read problem.
    Check count against each acquired export. Raw integer addresses have no export length, so keep them unchecked. The _held flag identifies acquired exports.
         cdef _cyb_BufferGuard _dst_guard_ = _cyb_BufferGuard(dst, 0, False, False, True)
         cdef void* _dst_ = _dst_guard_.ptr
         cdef _cyb_BufferGuard _src_guard_ = _cyb_BufferGuard(src, 0, False, True, True)
         cdef void* _src_ = _src_guard_.ptr
    +    if _dst_guard_._held and <size_t>_dst_guard_.nbytes < count:
    +        raise ValueError("dst is smaller than count")
    +    if _src_guard_._held and <size_t>_src_guard_.nbytes < count:
    +        raise ValueError("src is smaller than count")
    
    Apply the change at the generation source for runtime.pyx. Do not hand-edit the generated output. Locations: memcpy at cuda_bindings_13/cuda/bindings/_v2/runtime.pyx:26984-26990 and memcpy_async at :27201-27203.
  6. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 33194 · 🩺 Stability & Availability · ⚡ Quick win
    important: stream_get_capture_info returns NumPy arrays that point into driver-owned memory.
    dependencies_out and edge_data_out point to arrays that the driver owns. The arrays are only valid "until the next API call which operates on the stream or until the capture is terminated". _numpy.frombuffer(PyMemoryView_FromMemory(...)) wraps that memory without copying it. If a caller keeps the returned tuple and then captures another node or calls stream_end_capture, reading the arrays reads freed or reused memory. A Python caller cannot see that lifetime limit.
    In the generator, copy both arrays before returning, for example _numpy.frombuffer(...).copy(). Then regenerate.
    Source: Coding guidelines
  7. cuda_bindings_13/cuda/bindings/_v2/runtime.pyx, lines 34989–34992 · 🩺 Stability & Availability · ⚡ Quick win
    critical: mem_get_location_info passes a 1-element output buffer, but the driver writes ceil(size / summary_granularity) entries.
    MemLocation() allocates exactly one cudaMemLocation. cudaMemGetLocationInfo fills one entry per summary region. Example: size = 1 GiB and summary_granularity = 128 MiB gives 8 entries, so the driver writes 7 structs past the end of the NumPy allocation. This corrupts the heap. The docstring itself says the caller must allocate enough room.
    Fix this in the generator, not in this sealed file. Compute the count before the call, reject summary_granularity == 0 with ValueError, and allocate MemLocation(n). Then regenerate.
    -    cdef MemLocation location_out_py = MemLocation()
    +    if summary_granularity == 0:
    +        raise ValueError("summary_granularity must be non-zero")
    +    cdef size_t n = (size + summary_granularity - 1) // summary_granularity
    +    cdef MemLocation location_out_py = MemLocation(max(n, 1))
    
    As per coding guidelines, generated files "must change at the generation source" ("Do not hand-edit generated binding files").
    Source: Coding guidelines

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 56dce6e and 89cceb7.

Files selected for processing: 51

  • .pre-commit-config.yaml
  • cuda_bindings_12/cuda/bindings/_internal/utils.pxd
  • cuda_bindings_12/cuda/bindings/_internal/utils.pyx
  • cuda_bindings_12/cuda/bindings/cyruntime.pxd
  • cuda_bindings_12/cuda/bindings/cyruntime.pyx
  • 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_12/cuda/bindings/runtime.pyx
  • cuda_bindings_12/docs/source/module/runtime.rst
  • 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/_v2/runtime.pxd
  • cuda_bindings_13/cuda/bindings/_v2/runtime.pyx
  • cuda_bindings_13/cuda/bindings/cudla.pyx
  • cuda_bindings_13/cuda/bindings/cyruntime.pxd
  • cuda_bindings_13/cuda/bindings/cyruntime.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/cuda/bindings/runtime.pyx
  • cuda_bindings_13/cuda/bindings/utils/__init__.py
  • cuda_bindings_13/docs/source/api.rst
  • cuda_bindings_13/docs/source/module/driver_v2.rst
  • cuda_bindings_13/docs/source/module/runtime.rst
  • cuda_bindings_13/docs/source/module/runtime_v2.rst
  • cuda_bindings_13/docs/source/module/v2_migration.rst
  • cuda_bindings_13/docs/source/release/13.6.0-notes.rst
  • cuda_bindings_13/tests/legacy_api/test_legacy_callback_threads.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_cudart.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_graph_node_params_lifetime.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_graphics_apis.py
  • cuda_bindings_13/tests/legacy_api/test_legacy_utils.py
  • cuda_bindings_13/tests/test_callback_threads.py
  • cuda_bindings_13/tests/test_cuda.py
  • cuda_bindings_13/tests/test_cudart.py
  • cuda_bindings_13/tests/test_graph_node_params_lifetime.py
  • cuda_bindings_13/tests/test_graphics_apis.py
  • cuda_bindings_13/tests/test_interoperability.py
  • cuda_bindings_13/tests/test_kernelParams.py
  • cuda_bindings_13/tests/test_utils.py
  • cuda_python/docs/environment-docs.yml
  • cuda_python/docs/source/release/13.6.0-notes.rst
  • toolshed/setup-docs-env.sh
Files with no reviewable changes: 1

  • cuda_python/docs/environment-docs.yml

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@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

Major 1
  1. important: Normalize multidimensional buffers to the same order before batch copies.
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 89cceb7 and fcabe07.

Files selected for processing: 2

  • cuda_bindings_12/cuda/bindings/_internal/utils.pyx
  • cuda_bindings_13/cuda/bindings/_internal/utils.pyx

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.

raise `TypeError` rather than being converted.
"""
try:
cpython.PyObject_GetBuffer(obj, view, cpython.PyBUF_ANY_CONTIGUOUS)

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 · Data Integrity & Integration · Quick win

important: Normalize multidimensional buffers to the same order before batch copies.

A C-contiguous 2×2 dsts buffer and an F-contiguous 2×2 srcs buffer both pass this check. The batch-copy wrappers count four elements and pass their physical storage directly to CUDA. Entries [0,1] and [1,0] are paired with the wrong destinations, which can corrupt copied data. Normalize to C order or reject multidimensional inputs. (raw.githubusercontent.com)

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

@mdboom
mdboom marked this pull request as draft December 3, 2026 19:26
@mdboom

mdboom commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai Please do not suggest changes to the legacy tests (tests/legacy_api/, test_legacy_*.py) in this PR. They are intentionally left unchanged: this PR does not deliberately change the behavior of the legacy modules, and keeping those tests as they are lets us confirm that the legacy behavior is not changing. Cleanups to the legacy tests can be considered separately.

@coderabbitai

coderabbitai Bot commented Dec 3, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@mdboom suggestion: Understood. I won’t suggest changes to tests/legacy_api/ or test_legacy_*.py in this PR. I’ll treat the legacy tests as a baseline for checking legacy behavior.


Learnings used

Learnt from: CR
Repo: NVIDIA/cuda-python PR: 0
File: cuda_bindings_13/AGENTS.md:0-0
Timestamp: 2026-10-24T18:42:28.301Z
Learning: Applies to cuda_bindings_13/tests/legacy_api/** : Source excerpt:
## Testing expectations

The `tests/legacy_api` subdirectory tests the old pre-v2 APIs of `driver`, `runtime`
and `nvrtc`.  These test files should not be added to, only updated when
necessary to fix test failures.  The canonical set of tests are those outside of
the `tests/legacy_api` subdirectory.
Learnt from: CR
Repo: NVIDIA/cuda-python PR: 0
File: cuda_bindings_13/CLAUDE.md:0-0
Timestamp: 2026-10-31T04:59:49.354Z
Learning: Applies to cuda_bindings_13/tests/legacy_api/** : Source excerpt:
## Testing expectations

The `tests/legacy_api` subdirectory tests the old pre-v2 APIs of `driver`, `runtime`
and `nvrtc`.  These test files should not be added to, only updated when
necessary to fix test failures.  The canonical set of tests are those outside of
the `tests/legacy_api` subdirectory.

You are interacting with an AI system.

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