# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import contextlib import ctypes import gc import threading import pytest import helpers from cuda.core import ( LaunchConfig, LegacyPinnedMemoryResource, Program, ProgramOptions, launch, ) class LatchKernel: """ Manages a kernel that blocks stream progress until released. The kernel gives up after ``timeout_sec`` so that a test that never releases it cannot hang. The timeout is counted in GPU clock cycles at the peak clock rate, so it can last longer in wall-clock time. A test that expects to release the latch should check :attr:`timed_out` after synchronizing: if the latch ran into its timeout, the release protocol did not drive the test. """ def __init__(self, device, timeout_sec=60): if helpers.CUDA_INCLUDE_PATH is None: pytest.skip("need CUDA header") code = """ #include extern "C" __global__ void latch(int* val, unsigned long long timeout_cycles) { cuda::atomic_ref signal{val[0]}; cuda::atomic_ref timed_out{val[1]}; // Start time unsigned long long start = clock64(); while (true) { // Check if signal is set if (signal.load(cuda::memory_order_relaxed)) { break; } // Check for timeout if (clock64() - start >= timeout_cycles) { timed_out.store(1, cuda::memory_order_relaxed); break; // Timeout reached } // Avoid 100% spin. __nanosleep(1000000); // 1 ms } } """ program_options = ProgramOptions( std="c++17", arch=f"sm_{''.join(f'{i}' for i in device.compute_capability)}", include_path=helpers.CCCL_INCLUDE_PATHS, ) prog = Program(code, code_type="c++", options=program_options) mod = prog.compile(target_type="cubin") self.kernel = mod.get_kernel("latch") mr = LegacyPinnedMemoryResource() self.buffer = mr.allocate(8) self.busy_wait_flag[0] = 0 self.busy_wait_flag[1] = 0 clock_rate_hz = device.properties.clock_rate * 1000 self.timeout_cycles = int(timeout_sec * clock_rate_hz) def launch(self, stream): """Launch the latch kernel, blocking stream progress via busy waiting.""" self.busy_wait_flag[1] = 0 config = LaunchConfig(grid=1, block=1) launch(stream, config, self.kernel, int(self.buffer.handle), self.timeout_cycles) def release(self): """Release the latch, allowing stream progress.""" self.busy_wait_flag[0] = 1 def close(self): """Free the flag buffer; the stream that ran the latch must have synchronized.""" self.buffer.close() @property def timed_out(self): """Whether the last launch ended by timeout rather than release; valid after the stream syncs.""" return bool(self.busy_wait_flag[1]) @property def busy_wait_flag(self): return ctypes.cast(int(self.buffer.handle), ctypes.POINTER(ctypes.c_int32)) class HostCallbackLatch: """A host callback that holds a stream or graph launch until released. Prefer :class:`LatchKernel` with :func:`hold_stream`. Use this when the test must make host calls during the hold that may wait for the held work, for example a ``gc.collect()`` whose effect on an in-flight launch is under test; holding on the device would not make those calls safer. Pass the instance as the callback, wait for :attr:`started`, and wrap the hold in :func:`released_on_exit`. The callback gives up after ``timeout_sec`` and reports that through :attr:`timed_out` rather than raising, since an exception in a host callback cannot fail the test. """ def __init__(self, timeout_sec): self.timeout_sec = timeout_sec self.started = threading.Event() self._release = threading.Event() self.timed_out = False def __call__(self): self.started.set() self.timed_out = not self._release.wait(timeout=self.timeout_sec) def release(self): """Release the hold, allowing stream progress.""" self._release.set() @contextlib.contextmanager def released_on_exit(latch, stream): """Release ``latch`` and synchronize ``stream`` when the block exits. ``latch`` holds work on ``stream`` and provides ``release()`` and ``timed_out``. A host call that waits for outstanding work blocks until the latch times out (#3296), and the checks in the block then run against completed work. If the latch timed out, fail with that instead of the check's own message; the check's exception, if any, is chained. """ try: yield finally: latch.release() stream.sync() if latch.timed_out: raise AssertionError( "the latch timed out instead of being released: a host call most likely " "blocked until then, so the checks made during the hold saw completed work" ) @contextlib.contextmanager def hold_stream(latch, stream): """Hold ``stream`` with the :class:`LatchKernel` ``latch`` for the block. Create the objects the block needs before entering it. A finalizer that frees memory synchronizes the context, so if the cycle collector ran one during the hold, the host would block until the latch timed out (#3296). Collect now and keep the collector off until the latch is released. """ gc.collect() gc_enabled = gc.isenabled() gc.disable() try: latch.launch(stream) with released_on_exit(latch, stream): yield finally: if gc_enabled: gc.enable()