agentleFS
NVIDIAKnown publisherNVIDIA/cuda-python/cuda_core/tests/AGENTS.md

cuda-python / tests

AGENTS.md3.4k starsChanged 4 months agoApache-2.0View on GitHub

Package-wide conventions live in ../AGENTS.md; repository-wide ones in ../../AGENTS.md. This file covers conventions specific to the tests. A memory pool created without max_size reserves virtual address space similar in size to the installed physical device memory regardless of what the test actually allocates. The reservation is charged to the process address space even though it is not backed by physical memory, and it is not returned until the pool is destroyed and the stream-ordered frees of its outstanding allocations retire.…

Trending

More talk lately.thin dataabout the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 1 mentionMar 2026: 1 mentionApr 2026: 1 mentionMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 1 mentionAug 2026: 0 mentionsSep 2026: 0 mentionsOct 2026: 2 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the NVIDIA/cuda-python repository that our weekly crawl found: only 12 in all, so this is a hint, not a trend. There is no adoption data for this file yet.

Who's talking about NVIDIA/cuda-python

The biggest 5 of 12 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 12

Talked about on GitHub, Hacker News and Bluesky (12 times).

On GitHub · 10

5 more on GitHub

On Hacker News · 1

On Bluesky · 1

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

15 rules. About 0 are common, 2 are distinctive, and 13 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 13

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When a test needs its own pool, use the suite-wide cap from helpers/constants.py:

    line 16
  2. Very specific:

    Use a larger value only if a test genuinely requires it, and prefer adding a shared constant to helpers/constants.py over redefining one …

    line 25
  3. Very specific:

    Do not add max_size to a call that currently passes no options: that converts a free default-pool wrapper into a new pool and makes things …

    line 41
  4. Very specific:

    When a call is deliberately exempt -- most often because it sits inside pytest.raises and no pool is ever created -- annotate it:

    line 52
  5. Distinctive:

    Follow these rules when adding or moving shared test code:

    line 73
  6. Very specific:

    Never import from a conftest.py.

    line 75
  7. Very specific:

    Put suite-wide fixtures and pytest hooks in tests/conftest.py.

    line 76
  8. Very specific:

    Put a pytest hook in a nested conftest.py only if pytest supports that hook there.

    line 78
  9. Very specific:

    Import helpers explicitly from the test root, for example: from helpers.memory import create_managed_memory_resource_or_skip.

    line 84
  10. Very specific:

    Search tests/helpers/ and cuda_python_test_helpers/ for prior art before adding a new helper.

    line 86
  11. Very specific:

    Do not add __init__.py solely because a test directory contains a conftest.py.

    line 94
  12. Very specific:

    When a CUDA call's error means "feature refused by this driver" (e.g.

    line 137
  13. Very specific:

    Before adding importorskip, check cuda_core/pyproject.toml's test and test-cu* groups and cuda_core's dependencies.

    line 150
  14. Very specific:

    Do not catch ImportError for a hard runtime dependency (e.g.

    line 201
  15. Distinctive:

    If a setup step allocates a resource (GL object, window, file handle) and a later step fails, clean up the partial resource before …

    line 207

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

cuda.core test suite

Package-wide conventions live in ../AGENTS.md; repository-wide ones in ../../AGENTS.md. This file covers conventions specific to the tests.

Never create an uncapped memory pool

A memory pool created without max_size reserves virtual address space similar in size to the installed physical device memory regardless of what the test actually allocates. The reservation is charged to the process address space even though it is not backed by physical memory, and it is not returned until the pool is destroyed and the stream-ordered frees of its outstanding allocations retire. The whole suite shares one process and one device, so these reservations accumulate across tests.

When a test needs its own pool, use the suite-wide cap from helpers/constants.py:

from helpers.constants import POOL_SIZE

mr = DeviceMemoryResource(dev, DeviceMemoryResourceOptions(max_size=POOL_SIZE))

Use a larger value only if a test genuinely requires it, and prefer adding a shared constant to helpers/constants.py over redefining one per module.

Passing no options is different from passing empty options

DeviceMemoryResource(dev) with no options does not create a pool. It wraps the device's existing default mempool (_mempool_owned is false) and costs no additional address space. Passing any options object creates a new owned pool, and a new pool without max_size is uncapped:

DeviceMemoryResource(dev)  # wraps default pool, free
DeviceMemoryResource(dev, DeviceMemoryResourceOptions())  # NEW uncapped pool, expensive
DeviceMemoryResource(dev, {"ipc_enabled": True})  # NEW uncapped pool, expensive

Do not add max_size to a call that currently passes no options: that converts a free default-pool wrapper into a new pool and makes things worse.

Managed pools are exempt

cuMemPoolCreate requires CUmemPoolProps.maxSize to be zero for managed pools, so ManagedMemoryResourceOptions has no max_size option. Managed pools cannot be right-sized and are not checked.

Document exemptions

When a call is deliberately exempt -- most often because it sits inside pytest.raises and no pool is ever created -- annotate it:

with pytest.raises(RuntimeError, match="IPC is not available"):
    # uncapped-pool-ok: raises before the pool is created
    DeviceMemoryResource(mempool_device, DeviceMemoryResourceOptions(ipc_enabled=True))

Release resources at test boundaries

The init_cuda fixture in conftest.py runs gc.collect() followed by cuCtxSynchronize() before popping the context. Tests should not rely on that as a substitute for cleaning up explicitly: prefer context managers for resources whose lifetime fits a single scope, and keep pool lifetimes inside the test that creates them.

Shared test support

See also: https://docs.pytest.org/en/stable/reference/fixtures.html#conftest-py-sharing-fixtures-across-multiple-files

Follow these rules when adding or moving shared test code:

  • Never import from a conftest.py.
  • Put suite-wide fixtures and pytest hooks in tests/conftest.py. Put fixtures needed only by one test subtree in that subtree's nearest conftest.py.
  • Put a pytest hook in a nested conftest.py only if pytest supports that hook there. If the hook receives suite-wide data, explicitly limit its effects to the intended subtree.
  • Code used only to implement fixtures or hooks may remain in the same conftest.py. Put functions and constants imported by test modules in tests/helpers/ instead.
  • Import helpers explicitly from the test root, for example: from helpers.memory import create_managed_memory_resource_or_skip.
  • Search tests/helpers/ and cuda_python_test_helpers/ for prior art before adding a new helper; consolidate duplicates across

    packages into cuda_python_test_helpers (both cuda_core and cuda_bindings test environments already depend on it).

  • Fixtures in a nested conftest.py are available to tests in its directory and descendants; fixtures from applicable parent conftest.py files remain available.
  • Do not add __init__.py solely because a test directory contains a conftest.py.
  • In directories without __init__.py, keep test-module basenames unique within this test suite.

Skip only real setup failures

pytest.skip(reason) records the test as SKIPPED with reason in the report. A helper that wraps yield in except Exception: pytest.skip(...) therefore records every test-body failure as a skip — a real regression, a TypeError, an AttributeError all become "SKIPPED: <reason>" instead of "FAILED", and the suite goes green regardless of whether the code under test works.

Catch only the specific exception that legitimately means "not available", and only around the setup call — never around yield:

@contextlib.contextmanager
def _gl_context():
    try:
        win, tex_id = _setup_gl_texture()  # setup only
    except (pyglet.NoSuchConfigException, GLContextError) as e:
        pytest.skip(f"GL unavailable: {e}")
    try:
        yield tex_id  # body exceptions propagate
    finally:
        _cleanup(win, tex_id)

The exception names in the example are illustrative — GLContextError is not a real pyglet class. Match real pyglet exception names by type, or use the shared is_gl_context_unavailable helper in cuda_python_test_helpers.graphics.

GLException is pyglet's generic GL-error class, raised after any GL call that reports an error (GL_INVALID_ENUM, etc.). Do not include it in the "GL unavailable" set — it hides real bugs in GL allocation code as skips.

Platform-specific "library not loadable" manifestations (genuine "GL unavailable"):

  • Linux without libGL/libEGL: ImportError('Library "GL" not found.') / ImportError('Library "EGL" not found.') from pyglet/lib.py.
  • Windows without opengl32.dll: FileNotFoundError from ctypes.windll.opengl32; on Python 3.12+ ctypes.LibraryLoader re-raises AttributeError("opengl32").

When a CUDA call's error means "feature refused by this driver" (e.g. CUDA_ERROR_OPERATING_SYSTEM for CUDA-GL interop on WSL), skip at the call site with a narrow catch on the specific error, not inside the GL helper — see _register_gl_buffer / _register_gl_image in tests/test_graphics.py.

importorskip is for optional dependencies only

pytest.importorskip("X") is correct when X is genuinely optional (platform-gated binding, parametrized "test each available module"). It is dead code when X is a declared test or runtime dependency: the skip then fires only when the environment is broken, which is the case you want to fail loudly, not hide. Use a bare top-level import for declared deps.

Before adding importorskip, check cuda_core/pyproject.toml's test and test-cu* groups and cuda_core's dependencies. If the target is listed, import it directly.

Capability probes must not swallow real bugs

A probe function that answers "is feature X available?" by catching Exception and returning False will report "not available" even when the probed API failed for a real, unexpected reason — silently enabling a skip that hides the bug. Catch only the exception that genuinely means "not available", and split the checks so each catch is narrow:

def _is_nvfatbin_available():
    from cuda.bindings._internal.utils import FunctionNotFoundError
    from cuda.pathfinder import DynamicLibNotFoundError

    try:
        from cuda.bindings import nvfatbin
    except ImportError:
        return False
    try:
        nvfatbin.version()
    except (DynamicLibNotFoundError, FunctionNotFoundError):
        # libnvfatbin not loadable, or nvFatbinVersion symbol missing.
        return False
    return True

Catch only the exceptions that mean "not installed / not loadable". A genuine API-status failure (e.g. nvfatbin.nvFatbinError from a successfully loaded library) must propagate so a real bug is not hidden as "unavailable".

For a probe that calls a CUDA API returning a CUresult, let handle_return raise on any non-success result and classify only a successful bitmask lacking the documented bit as False; other failures propagate so a real driver bug is not hidden as "unsupported":

@functools.cache
def supports_ipc_mempool(device_id):
    from cuda.bindings import driver

    handle_return(driver.cuInit(0))
    dev_id = int(getattr(device_id, "device_id", device_id))
    attr = driver.CUdevice_attribute.CU_DEVICE_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES
    mask = handle_return(driver.cuDeviceGetAttribute(attr, dev_id))
    posix_fd = driver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR
    return (int(mask) & int(posix_fd)) != 0

Do not catch ImportError for a hard runtime dependency (e.g. cuda.bindings for cuda.core) — that is a broken environment and should surface at collection time.

Clean up partial setup on failure

If a setup step allocates a resource (GL object, window, file handle) and a later step fails, clean up the partial resource before re-raising so it does not leak. Wrap the allocation in try/except and delete the generated object in the except before re-raising:

def _allocate_gl_buffer(win, nbytes):
    from pyglet.gl import gl as _gl

    buf_id = _gl.GLuint(0)
    try:
        _gl.glGenBuffers(1, ctypes.byref(buf_id))
        _gl.glBindBuffer(_gl.GL_ARRAY_BUFFER, buf_id.value)
        _gl.glBufferData(_gl.GL_ARRAY_BUFFER, nbytes, None, _gl.GL_DYNAMIC_DRAW)
        return buf_id
    except Exception:
        if buf_id.value:
            with contextlib.suppress(Exception):
                _gl.glDeleteBuffers(1, ctypes.byref(buf_id))
        raise

Initialize handles to None before the protected region so the finally cleanup does not NameError when allocation raises before returning a handle.

Tests that touch CUDA must establish their own context

The init_cuda fixture pops the CUDA context on teardown, so a test that calls a CUDA API without init_cuda (or an explicit Device.set_current()) inherits whatever context the previous test happened to leave current on the thread — possibly none. With pytest-randomly that makes the pass/fail outcome depend on test order, so it moves seed to seed and looks like flakiness. Request init_cuda for any test that calls into the driver, or set up and tear down a context yourself.

Assert on behavior, not implementation

Pin on observable behavior the contract guarantees — return values, raised exception types, public state transitions. Avoid asserting on internal call counts, private helper invocation order, or error message substrings that are not part of the contract. A refactor that preserves behavior but changes internals should not break the test.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.