Skip to content

test(cuda.core): move test hooks out of production code - #3555

Open
juenglin wants to merge 9 commits into
NVIDIA:mainfrom
juenglin:remove-production-test-hooks
Open

juenglin wants to merge 9 commits into
NVIDIA:mainfrom
juenglin:remove-production-test-hooks

Conversation

@juenglin

@juenglin juenglin commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Addresses this review comment on #3511 about shipping test hooks in production code.

This PR removes three test-only hooks from cuda.core's production modules and puts their replacements in the test-only module cuda/core/_utils/_testing.pyx. That module was _utils/_weak_handles.pyx until this PR; it is renamed because it now holds more than weak handles.

  • _attach_rollback_failure_for_testing: the wrapper and the extern alias that served it move out of _rt.pyx. The new wrapper cimports attach_rollback_failure from _rt.pxd unchanged.
  • set_ipc_pool_release_delay_for_testing: the global delay and the sleep in the imported-pool deleter are removed from memory.cpp.
  • set_context_restore_fault_for_testing: the thread-local fault and the check in restore_context() are removed from context.cpp.

The last two are replaced by wrappers around driver functions. The C++ layer calls the driver through a function table that it fills once per process from cuda.bindings._internal.driver._inspect_function_pointers(). install_driver_fn_wrappers() replaces that function before the first fill, so that selected table entries (cuCtxSetCurrent, cuMemPoolSetAccess, cuMemPoolImportFromShareableHandle) are C++ wrappers in _testing.pyx. When a test arms them, they fail or hold a call; otherwise they call the driver.

  • conftest.py installs the wrappers for the test session. The IPC race test's spawned child installs them itself.
  • Arming a wrapper raises unless the table holds the wrappers, so a test cannot run without its fault or hold.
  • The wrappers are plain C++ that never calls Python, because pool deleters can run without the GIL and during interpreter shutdown.

The IPC race test now holds the pool's release with a gate instead of a fixed delay, so it no longer depends on timing to make the re-import overlap the release.

The context fault now fails the next switch back to the context that was current when it was armed, instead of the next restore. enter_context() never switches to the context that is already current, so only the restore can fail. The tests needed no logic changes.

The PR also adds a section to cuda_core/tests/AGENTS.md that lists the test-only patterns production code must not contain and the alternatives to use instead, plus a pointer to it from cuda_core/AGENTS.md. One known hook remains: _capture_callback_with_tail_failure_for_testing in graph/_graph_builder.pyx. Removing it first needs tail discovery to call cuStreamGetCaptureInfo through the C++ function table, so it is left for a follow-up.

Verification:

  • With the release wait in ReleasingHandleRegistry disabled (the fix(cuda.core): share ownership of repeat imports of an IPC memory pool #3511 fix), the race test fails for both pinned and device pools. With the fix, it passes.
  • The cuda_core tests that use _testing pass locally on one GPU. test_memset_update_keeps_new_owners_alive_when_context_cannot_be_restored needs two GPUs and was not run locally.

Checklist

  • I have read the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

🤖 Generated with Claude Code

…st-only module

The Python wrapper that tests call to exercise attach_rollback_failure() lived
in _rt.pyx, together with an extern alias that existed only for it. Move it to
the test-only module that already provides weak handles, and rename that
module from _utils/_weak_handles to _utils/_testing now that it holds more
than weak handles. The wrapper cimports attach_rollback_failure from _rt.pxd,
so _rt keeps no test code for it.
…ot a production hook

The re-import race test made an imported pool's owner sleep before it revoked
access through set_ipc_pool_release_delay_for_testing(), a global delay read
by the production deleter. Remove that hook from memory.cpp, api.hpp and _rt.

The test now delays the same step from the test-only _utils/_testing module.
The C++ layer calls the driver through a function table that it fills once
per process from cuda.bindings' _inspect_function_pointers(). The race
test's spawned child replaces that function before its first driver call, so
that the table's cuMemPoolSetAccess entry is a C++ wrapper that sleeps when
armed and then calls the driver. The C++ layer calls cuMemPoolSetAccess only
for the revoke before a pool is destroyed, the point where the hook slept.
Arming the delay raises if the table was filled without the wrapper.

Disabling the release wait in ReleasingHandleRegistry makes the test fail
for both pinned and device pools with the delay armed, and pass without it.
…t a production hook

restore_context() checked a thread-local fault that tests set through
set_context_restore_fault_for_testing(). Remove that hook from context.cpp,
error.hpp and _rt.

The test-only _utils/_testing module now wraps the driver function table's
cuCtxSetCurrent entry, the same way it wraps cuMemPoolSetAccess for the IPC
race test. set_context_restore_fault(status) records the context that is
current on the calling thread, and the wrapper fails the next switch back to
it on that thread without switching, which leaves the operation's context
current as a real failure would. enter_context() never switches to the
context that is already current, so only the restoration fails.

conftest.py installs the wrappers before any test makes a driver call. When
disarmed, the wrappers only check a thread-local or an atomic before calling
the driver.
Add a tests/AGENTS.md section that lists the test-only patterns production
modules must not contain and the alternatives to use instead, in order of
preference: the public API, objects the code under test calls back into,
the test-only _utils/_testing module, and its driver function wrappers.
Agents editing production code follow cuda_core/AGENTS.md, not
tests/AGENTS.md, so add an editing-guidance bullet that forbids test-only
hooks and points to the alternatives in tests/AGENTS.md.
@juenglin juenglin added this to the cuda.core 1.4.0 milestone Nov 24, 2026
@juenglin juenglin added test Improvements or additions to tests cuda.core Everything related to the cuda.core module labels Nov 24, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@juenglin juenglin self-assigned this Nov 24, 2026
…g it

The race test held the owner's release with a fixed 50 ms sleep and started
the re-import 12.5 ms in. If the release thread stalled past that offset,
the re-import joined the still-live owner and the test passed without
exercising the race.

Replace the delay with a gate built from two driver function wrappers in
cuda.core._utils._testing:

- The first cuMemPoolSetAccess on the target pool after arming (the
  release's access revocation, after its last reference is gone) blocks.
- A new wrapper on cuMemPoolImportFromShareableHandle signals when an
  import returns that pool while the release is held, which proves the
  overlap.
- The release then stays held until the test opens the gate after the
  import has finished, or a grace period passes. A correct registry makes
  the import wait for the release, so the grace period always ends the
  hold; a broken one lets the import finish first, so the revocation lands
  after the access grant and the test sees the damage.

The re-import waits for the release to be held instead of sleeping, and the
test asserts the overlap, so a pass always means the race was exercised.
With the registry's release wait disabled, the test now fails for both
device and pinned pools; without the grace phase, the pinned case passed.

Also:
- Name both causes in the error raised when a wrapper is armed before the
  table holds the wrappers, and document arming after the first driver call.
- Use one C++ namespace for the module's inline blocks, explain why the
  real driver pointers are atomic and why the rollback wrapper keeps its
  _for_testing suffix, and rewrap the module docstring.
- Describe the gate pattern and the revert-the-fix check in tests/AGENTS.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@juenglin
juenglin marked this pull request as ready for review November 24, 2026 22:51
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b226298 and 051cf7c.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Tests
    • Improved reliability of tests covering concurrent memory-pool imports and releases with controlled synchronization instead of timing-based delays.
    • Consolidated test support for observing resource lifetimes and simulating driver and error conditions.
    • Updated error-handling tests to use the consolidated test support; runtime behavior remains unchanged for end users.
  • Documentation
    • Added contributor guidance on testing hard-to-reach behavior without adding test-only hooks to production code.

The pull request consolidates test-only helpers in cuda.core._utils._testing, removes corresponding hooks from runtime modules, and updates tests and contributor guidance. It also replaces the IPC pool release-delay mechanism with a synchronized release gate.

Changes: Test utility consolidation

Layer / File(s) Summary
Test-only helper module
cuda_core/cuda/core/_utils/_testing.pyx, cuda_core/cuda/core/_utils/_testing.pyi, cuda_core/cuda/core/_utils/_weak_handles.pyx, cuda_core/cuda/core/_utils/_weak_handles.pyi
The new module provides weak handles, rollback-failure reporting, driver-function wrappers, context-restore fault injection, and pool-release gate controls. The previous weak-handle module is deleted.
Move tests to testing helpers
cuda_core/cuda/core/_cpp/rt/context.cpp, cuda_core/cuda/core/_cpp/rt/error.hpp, cuda_core/cuda/core/_rt.pyx, cuda_core/cuda/core/_rt.pyi, cuda_core/tests/conftest.py, cuda_core/tests/test_error_handling.py, cuda_core/tests/graph/*, cuda_core/AGENTS.md, cuda_core/tests/AGENTS.md, cuda_core/cuda/core/_cpp/rt/DESIGN.md
Runtime test hooks for context restoration and rollback failures are removed. Context restoration now proceeds through cuCtxSetCurrent. Tests use the new helpers, pytest installs driver wrappers, and contributor guidance describes alternatives for testing hard-to-reach paths.
Gate the IPC pool release race
cuda_core/cuda/core/_cpp/rt/api.hpp, cuda_core/cuda/core/_cpp/rt/memory.cpp, cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py
The release-delay hook and sleep are removed. The IPC duplicate-import test coordinates release and re-import with a gate and asserts that they overlap.

Change: Other

Merge Risk: Minimal · previous review b2262

This PR moves test-only hooks out of production runtime code and into a test-only module, and replaces a fixed release delay with a synchronized gate in the IPC race test. No outstanding defects were identified, so the risk to merge is minimal.

Security architecture risk: Low · up to b2262

Normal CUDA use keeps the same pool ownership and cleanup behavior. The replacement hooks are inactive unless explicitly installed, but in a process that installs them, a missing driver function can turn a clear initialization error into a process crash.

Retained concerns

  • Low · reliability · observed: After explicit wrapper installation, a zero address for a required driver function is replaced with a non-null wrapper address. The table can therefore accept an entry it previously rejected, and a later pass-through call can dereference the missing function and terminate that process. Ordinary startup without the installer retains the original validation.
Security review details

Security Blast Radius

  • inferred — The shipped helper can change driver dispatch within a process, but only after code already executing in that process explicitly installs it before the driver table is filled. The inspected change does not expose installation through IPC descriptors or create a cross-process control channel.

Resilience and Maintainability Implications

  • observed — The race test arms the gate before starting the threads and disarms it in a finally block after they join. The one-shot hold has bounded waits, and the test arranges cleanup for resources acquired by either thread before checking the result.

Hardening Proposals

  • proposed — Preserve zero-valued driver entries when installing wrappers so the runtime retains its original missing-symbol diagnostics. If the helper is intended to be absent from production distributions, enforce that separately in the build configuration.
- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4343742 and b226298.

Files selected for processing: 1

  • cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py

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

@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

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between afcdf40 and 0959243.

Files selected for processing: 18

  • cuda_core/AGENTS.md
  • cuda_core/cuda/core/_cpp/rt/DESIGN.md
  • cuda_core/cuda/core/_cpp/rt/api.hpp
  • cuda_core/cuda/core/_cpp/rt/context.cpp
  • cuda_core/cuda/core/_cpp/rt/error.hpp
  • cuda_core/cuda/core/_cpp/rt/memory.cpp
  • cuda_core/cuda/core/_rt.pyi
  • cuda_core/cuda/core/_rt.pyx
  • cuda_core/cuda/core/_utils/_testing.pyi
  • cuda_core/cuda/core/_utils/_testing.pyx
  • cuda_core/cuda/core/_utils/_weak_handles.pyi
  • cuda_core/cuda/core/_utils/_weak_handles.pyx
  • cuda_core/tests/AGENTS.md
  • cuda_core/tests/conftest.py
  • cuda_core/tests/graph/test_graph_definition_lifetime.py
  • cuda_core/tests/graph/test_graph_node_update.py
  • cuda_core/tests/memory_ipc/test_ipc_pool_duplicate_import.py
  • cuda_core/tests/test_error_handling.py
Files with no reviewable changes: 8

  • cuda_core/cuda/core/_cpp/rt/api.hpp
  • cuda_core/cuda/core/_cpp/rt/context.cpp
  • cuda_core/cuda/core/_cpp/rt/error.hpp
  • cuda_core/cuda/core/_cpp/rt/memory.cpp
  • cuda_core/cuda/core/_rt.pyi
  • cuda_core/cuda/core/_rt.pyx
  • cuda_core/cuda/core/_utils/_weak_handles.pyi
  • cuda_core/cuda/core/_utils/_weak_handles.pyx

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

Comment thread cuda_core/cuda/core/_utils/_testing.pyx Resolved
After the pool release gate timed out, its "entered" flag stayed set, so a
later import still marked the release as overlapped and the race test's
overlap check could pass without an overlap.

Track whether the release is still blocked in a separate "held" flag, cleared
under the mutex when the release proceeds, and require it before an import
counts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test 4343742

@github-actions

Copy link
Copy Markdown
Contributor

juenglin added a commit to juenglin/cuda-python that referenced this pull request Nov 25, 2026
test_concurrent_set_current_keeps_one_primary_retain runs its workers
with run_in_threads (NVIDIA#3544), which aborts the barrier if a worker fails
and bounds the joins.

test_green_context_replaces_stale_plain_entry notes rollback failures
with BaseException.add_note() instead of the _attach_rollback_failure_for_testing
production hook, which NVIDIA#3555 moves out of _rt.

test_driver_calls_go_through_the_table: the primary-context table's mutex
is a second site of raw driver calls under a lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…est-hooks

Resolve the test_ipc_pool_duplicate_import.py constants conflict: keep the
gate's RELEASE_GRACE_SEC once and take REENTRY_ITERATIONS and
LOOKUP_RACE_SECONDS from main. Restore the 'time' import that the gate
commit removed and main's new lookup race test uses.

@jpascucci-nv jpascucci-nv left a comment

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.

Codex 6.1 high says no actionable findings. lgtm

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test b226298

@juenglin

Copy link
Copy Markdown
Contributor Author

/ok to test 051cf7c

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.core Everything related to the cuda.core module test Improvements or additions to tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants