Coverage for cuda/core/_utils/_testing.pyx: 78.46%

65 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-03 01:06 +0000

1# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. 

2# SPDX-License-Identifier: Apache-2.0 

3  

4"""Test-only helpers that reach into ``cuda.core`` internals. 

5  

6This module is **not** part of the public ``cuda.core`` API. It is built into 

7the package (like other private ``_utils`` modules) purely for the test suite, 

8so that production modules need no test hooks of their own. 

9  

10Weak handles 

11------------ 

12  

13Weak handles let tests observe, deterministically, when the strong references 

14that keep a CUDA resource alive have all been released -- without relying on 

15driver- or hardware-specific side effects (for example, whether freed device 

16memory happens to remain readable). 

17  

18Every resource handle is owned by a C++ ``std::shared_ptr``. A **weak handle** 

19is a non-owning ``std::weak_ptr`` observer of that control block: truthy while 

20some strong owner remains, falsy once the last one is gone. Use :func:`weak_handle` 

21to obtain a weak handle from a supported front-end object. 

22  

23To support another type, add a ``cdef _weak_from_<type>`` that reads its ``cdef`` 

24handle field (see ``*.pxd``), assigns to :ctype:`OpaqueHandle`, and extend the 

25``isinstance`` chain in :func:`weak_handle`. Types whose slots hold arbitrary 

26Python owners via ``make_opaque_py`` are not covered here -- use 

27:class:`weakref.ref` on a weak-referenceable owner object in tests instead. 

28  

29Driver function wrappers 

30------------------------ 

31  

32The C++ layer calls the driver through a table of function pointers that it 

33fills once per process, on its first driver call, from 

34``cuda.bindings._internal.driver._inspect_function_pointers()``. 

35:func:`install_driver_fn_wrappers` replaces that function so that the fill 

36stores test wrappers for selected entries. Each wrapper calls the real driver 

37function unless a test arms it. Install the wrappers before ``cuda.core``'s 

38first driver call in the process: conftest.py does so for the test session, 

39and a spawned child must do so itself. The setters raise unless the table was 

40filled with the wrappers, so a test cannot silently run unarmed. Arm a wrapper 

41only after the process's first driver call through ``cuda.core``, for example 

42after creating a device or a stream. 

43""" 

44  

45from libc.stdint cimport intptr_t 

46  

47from cuda.bindings cimport cydriver 

48from cuda.core._memory._buffer cimport Buffer 

49from cuda.core.graph._graph_definition cimport GraphDefinition 

50from cuda.core._rt cimport OpaqueHandle, attach_rollback_failure 

51from cuda.core._utils.cuda_utils cimport HANDLE_RETURN 

52  

53import cuda.bindings._internal.driver as _driver_loader 

54  

55  

56# Cython cannot spell ``weak_ptr[const void]`` inline (the ``const void`` 

57# template argument fails to parse), so the weak type and its one constructor 

58# are provided by a small inline C++ shim local to this test-only module. This 

59# keeps the production resource_handles translation units untouched. 

60cdef extern from *: 

61 """ 

62 #include <memory> 

63 namespace cuda_core_test { 

64 using OpaqueWeakHandle = std::weak_ptr<const void>; 

65 static inline OpaqueWeakHandle make_weak(const std::shared_ptr<const void>& h) { 

66 return OpaqueWeakHandle(h); 

67 } 

68 } // namespace cuda_core_test 

69 """ 

70 cppclass OpaqueWeakHandle "cuda_core_test::OpaqueWeakHandle": 

71 OpaqueWeakHandle() 

72 bint expired() 

73 long use_count() 

74 OpaqueWeakHandle make_weak "cuda_core_test::make_weak" (const OpaqueHandle& h) 

75  

76  

77cdef class WeakHandle: 

78 """Non-owning weak handle for a resource's shared control block. 

79  

80 Truthy while some strong owner of the underlying resource handle remains, 

81 falsy once the last strong reference is released. Obtain instances via 

82 :func:`weak_handle` rather than constructing directly. 

83 """ 

84  

85 cdef OpaqueWeakHandle _w 

86  

87 def __bool__(self): 

88 return not self._w.expired() 1defgbhcij

89  

90 def expired(self): 

91 """Return ``True`` once every strong owner of the handle is gone.""" 

92 return self._w.expired() 

93  

94 def use_count(self): 

95 """Number of strong owners currently sharing the handle.""" 

96 return self._w.use_count() 

97  

98  

99cdef WeakHandle _weak_from_opaque(OpaqueHandle h): 

100 # Build the weak handle from a (temporary) strong handle. The strong copy 

101 # lives only for the duration of this call, so it does not perturb the 

102 # reference count the weak handle later reports. 

103 cdef WeakHandle wh = WeakHandle.__new__(WeakHandle) 1defgbhcij

104 wh._w = make_weak(h) 1adefgbhcij

105 return wh 1defgbhcij

106  

107  

108cdef WeakHandle _weak_from_buffer(Buffer buf): 

109 cdef OpaqueHandle h = buf._h_ptr 1defghij

110 if not h: 1defghij

111 raise ValueError("Buffer has no active allocation") 

112 return _weak_from_opaque(h) 1defghij

113  

114  

115cdef WeakHandle _weak_from_graph_definition(GraphDefinition graph): 

116 cdef OpaqueHandle h = graph._h_graph 1bc

117 if not h: 1bc

118 raise ValueError("GraphDefinition has no active graph") 

119 return _weak_from_opaque(h) 1bc

120  

121  

122def weak_handle(obj): 

123 """Return a :class:`WeakHandle` observing the resource behind ``obj``. 

124  

125 Currently supports :class:`~cuda.core.Buffer` (allocation handle) and 

126 :class:`~cuda.core.graph.GraphDefinition` (graph hierarchy handle). See 

127 the module docstring for how to add more types. 

128  

129 Raises 

130 ------ 

131 ValueError 

132 If ``obj`` is a :class:`~cuda.core.Buffer` with no active allocation. 

133 TypeError 

134 If ``obj`` is not a supported type. 

135 """ 

136 if isinstance(obj, Buffer): 1defgbhcij

137 return _weak_from_buffer(obj) 1defghij

138 if isinstance(obj, GraphDefinition): 1bc

139 return _weak_from_graph_definition(obj) 1bc

140 raise TypeError( 

141 f"weak_handle() does not support {type(obj).__name__!r}; " 

142 "supported types: Buffer, GraphDefinition" 

143 ) 

144  

145  

146# Keeps the ``_for_testing`` suffix because it shares its name with the cimported 

147# ``attach_rollback_failure``, which this wrapper calls. 

148def attach_rollback_failure_for_testing(int status): 

149 """Attach a failed CUDA call to the exception being handled, or report it. 

150  

151 Calls ``attach_rollback_failure()`` for a fictitious ``cuTestOperation``. 

152 Called inside an ``except`` block it adds a note to the exception being 

153 handled (Python 3.11+); anywhere else it emits a ``CUDAWarning``. 

154 """ 

155 attach_rollback_failure(b"cuTestOperation", <cydriver.CUresult>status, b"failed while testing") 1t

156  

157  

158# The wrappers run on driver calls from any thread, with or without the GIL, 

159# and during interpreter shutdown, so they are plain C++ and never call Python. 

160cdef extern from *: 

161 """ 

162 #include <atomic> 

163 #include <chrono> 

164 #include <condition_variable> 

165 #include <cstdint> 

166 #include <mutex> 

167 #include <cuda.h> 

168 namespace cuda_core_test { 

169 // The real pointers are atomic because the fill may run on two threads at 

170 // once in a free-threaded build, and each run calls the wrap functions. 

171 using CtxSetCurrentFn = CUresult(CUDAAPI *)(CUcontext); 

172 static std::atomic<CtxSetCurrentFn> real_ctx_set_current{nullptr}; 

173 static thread_local CUresult ctx_set_current_fault = CUDA_SUCCESS; 

174 static thread_local CUcontext ctx_set_current_fault_target = nullptr; 

175  

176 static CUresult CUDAAPI faulty_ctx_set_current(CUcontext ctx) { 

177 if (ctx_set_current_fault != CUDA_SUCCESS && ctx == ctx_set_current_fault_target) { 

178 CUresult fault = ctx_set_current_fault; 

179 ctx_set_current_fault = CUDA_SUCCESS; 

180 return fault; 

181 } 

182 return real_ctx_set_current.load()(ctx); 

183 } 

184 static std::intptr_t wrap_ctx_set_current(std::intptr_t real) { 

185 real_ctx_set_current.store(reinterpret_cast<CtxSetCurrentFn>(real)); 

186 return reinterpret_cast<std::intptr_t>(&faulty_ctx_set_current); 

187 } 

188 static void set_ctx_set_current_fault(CUresult status, CUcontext target) { 

189 ctx_set_current_fault = status; 

190 ctx_set_current_fault_target = target; 

191 } 

192  

193 // The pool release gate: the first cuMemPoolSetAccess on the target pool 

194 // after arming blocks until an import returns that pool (or a timeout), 

195 // then until the test opens the gate (or a grace period passes). 

196 // Only the armed path touches the mutex; the gate is never destroyed, so a 

197 // deleter that runs during process exit cannot reach a destroyed mutex. 

198 struct PoolReleaseGate { 

199 std::mutex mutex; 

200 std::condition_variable changed; 

201 CUmemoryPool pool = nullptr; 

202 std::chrono::duration<double> timeout{0}; 

203 std::chrono::duration<double> grace{0}; 

204 bool entered = false; // a release reached the gate since arming 

205 bool held = false; // that release is still blocked in the gate 

206 bool imported = false; 

207 bool opened = false; 

208 bool disarmed = false; 

209 }; 

210 static PoolReleaseGate &pool_release_gate() { 

211 static PoolReleaseGate *gate = new PoolReleaseGate; 

212 return *gate; 

213 } 

214 // Armed until the release enters the gate; watching until disarmed. 

215 static std::atomic<bool> pool_release_gate_armed{false}; 

216 static std::atomic<bool> pool_release_gate_watching{false}; 

217  

218 using MemPoolSetAccessFn = CUresult(CUDAAPI *)(CUmemoryPool, const CUmemAccessDesc *, size_t); 

219 static std::atomic<MemPoolSetAccessFn> real_mempool_set_access{nullptr}; 

220  

221 static CUresult CUDAAPI gated_mempool_set_access( 

222 CUmemoryPool pool, const CUmemAccessDesc *map, size_t count) { 

223 if (pool_release_gate_armed.load()) { 

224 PoolReleaseGate &gate = pool_release_gate(); 

225 std::unique_lock<std::mutex> lock(gate.mutex); 

226 if (pool_release_gate_armed.load() && pool == gate.pool) { 

227 pool_release_gate_armed.store(false); // one-shot: later calls pass through 

228 gate.entered = true; 

229 gate.held = true; 

230 gate.changed.notify_all(); 

231 gate.changed.wait_for(lock, gate.timeout, [&] { return gate.imported || gate.disarmed; }); 

232 if (gate.imported) { 

233 gate.changed.wait_for(lock, gate.grace, [&] { return gate.opened || gate.disarmed; }); 

234 } 

235 // The release proceeds: a later import did not overlap it. 

236 gate.held = false; 

237 } 

238 } 

239 return real_mempool_set_access.load()(pool, map, count); 

240 } 

241 static std::intptr_t wrap_mempool_set_access(std::intptr_t real) { 

242 real_mempool_set_access.store(reinterpret_cast<MemPoolSetAccessFn>(real)); 

243 return reinterpret_cast<std::intptr_t>(&gated_mempool_set_access); 

244 } 

245  

246 using MemPoolImportFn = CUresult(CUDAAPI *)(CUmemoryPool *, void *, CUmemAllocationHandleType, unsigned long long); 

247 static std::atomic<MemPoolImportFn> real_mempool_import{nullptr}; 

248  

249 static CUresult CUDAAPI signaling_mempool_import( 

250 CUmemoryPool *pool, void *handle, CUmemAllocationHandleType type, unsigned long long flags) { 

251 CUresult status = real_mempool_import.load()(pool, handle, type, flags); 

252 if (status == CUDA_SUCCESS && pool_release_gate_watching.load()) { 

253 PoolReleaseGate &gate = pool_release_gate(); 

254 std::lock_guard<std::mutex> lock(gate.mutex); 

255 // Only an import made while the release is held counts. 

256 if (gate.held && !gate.disarmed && *pool == gate.pool) { 

257 gate.imported = true; 

258 gate.changed.notify_all(); 

259 } 

260 } 

261 return status; 

262 } 

263 static std::intptr_t wrap_mempool_import(std::intptr_t real) { 

264 real_mempool_import.store(reinterpret_cast<MemPoolImportFn>(real)); 

265 return reinterpret_cast<std::intptr_t>(&signaling_mempool_import); 

266 } 

267  

268 static void arm_pool_release_gate(CUmemoryPool pool, double timeout_sec, double grace_sec) { 

269 PoolReleaseGate &gate = pool_release_gate(); 

270 std::lock_guard<std::mutex> lock(gate.mutex); 

271 gate.pool = pool; 

272 gate.timeout = std::chrono::duration<double>(timeout_sec); 

273 gate.grace = std::chrono::duration<double>(grace_sec); 

274 gate.entered = false; 

275 gate.held = false; 

276 gate.imported = false; 

277 gate.opened = false; 

278 gate.disarmed = false; 

279 pool_release_gate_watching.store(true); 

280 pool_release_gate_armed.store(true); 

281 } 

282 static bool wait_pool_release_gate_entered(double timeout_sec) { 

283 PoolReleaseGate &gate = pool_release_gate(); 

284 std::unique_lock<std::mutex> lock(gate.mutex); 

285 return gate.changed.wait_for( 

286 lock, std::chrono::duration<double>(timeout_sec), [&] { return gate.entered || gate.disarmed; }) 

287 && gate.entered; 

288 } 

289 static void open_pool_release_gate() { 

290 PoolReleaseGate &gate = pool_release_gate(); 

291 std::lock_guard<std::mutex> lock(gate.mutex); 

292 gate.opened = true; 

293 gate.changed.notify_all(); 

294 } 

295 static bool disarm_pool_release_gate() { 

296 PoolReleaseGate &gate = pool_release_gate(); 

297 std::lock_guard<std::mutex> lock(gate.mutex); 

298 pool_release_gate_armed.store(false); 

299 pool_release_gate_watching.store(false); 

300 const bool overlapped = gate.entered && gate.imported; 

301 gate.disarmed = true; 

302 gate.changed.notify_all(); // release a held release or waiter 

303 return overlapped; 

304 } 

305 } // namespace cuda_core_test 

306 """ 

307 intptr_t _wrap_ctx_set_current "cuda_core_test::wrap_ctx_set_current" (intptr_t real) noexcept 

308 void _set_ctx_set_current_fault "cuda_core_test::set_ctx_set_current_fault" ( 

309 cydriver.CUresult status, cydriver.CUcontext target) noexcept nogil 

310 intptr_t _wrap_mempool_set_access "cuda_core_test::wrap_mempool_set_access" (intptr_t real) noexcept 

311 intptr_t _wrap_mempool_import "cuda_core_test::wrap_mempool_import" (intptr_t real) noexcept 

312 void _arm_pool_release_gate "cuda_core_test::arm_pool_release_gate" ( 

313 cydriver.CUmemoryPool pool, double timeout_sec, double grace_sec) noexcept nogil 

314 bint _wait_pool_release_gate_entered "cuda_core_test::wait_pool_release_gate_entered" ( 

315 double timeout_sec) noexcept nogil 

316 void _open_pool_release_gate "cuda_core_test::open_pool_release_gate" () noexcept nogil 

317 bint _disarm_pool_release_gate "cuda_core_test::disarm_pool_release_gate" () noexcept nogil 

318  

319  

320_inspect_without_wrappers = None 

321_wrappers_installed = False 

322  

323  

324def _inspect_with_wrappers(): 

325 global _wrappers_installed 

326 pointers = dict(_inspect_without_wrappers()) 1kl

327 pointers["__cuCtxSetCurrent"] = _wrap_ctx_set_current(pointers["__cuCtxSetCurrent"]) 1kl

328 pointers["__cuMemPoolSetAccess"] = _wrap_mempool_set_access(pointers["__cuMemPoolSetAccess"]) 1kl

329 pointers["__cuMemPoolImportFromShareableHandle"] = _wrap_mempool_import( 1kl

330 pointers["__cuMemPoolImportFromShareableHandle"]) 1kl

331 _wrappers_installed = True 1kl

332 return pointers 1kl

333  

334  

335def install_driver_fn_wrappers(): 

336 """Make the C++ driver function table use the test wrappers in this process. 

337  

338 Call before ``cuda.core`` makes its first driver call; see the module 

339 docstring. Calling it again has no effect. 

340 """ 

341 global _inspect_without_wrappers 

342 if _inspect_without_wrappers is None: 

343 _inspect_without_wrappers = _driver_loader._inspect_function_pointers 

344 _driver_loader._inspect_function_pointers = _inspect_with_wrappers 

345  

346  

347cdef int _require_driver_fn_wrappers() except -1: 

348 if not _wrappers_installed: 1mnopqrs

349 raise RuntimeError( 

350 "cuda.core's driver function table does not hold the test wrappers yet. " 

351 "Either install_driver_fn_wrappers() was not called before cuda.core's first driver call " 

352 "in this process, or cuda.core has not made a driver call yet; arm the wrapper after one" 

353 ) 

354 return 0 1mnopqrs

355  

356  

357def arm_pool_release_gate(intptr_t pool, double timeout_sec, double grace_sec): 

358 """Hold the next release of ``pool`` while the pool is imported again. 

359  

360 The C++ layer calls ``cuMemPoolSetAccess`` only to revoke access just 

361 before it destroys a pool (or an imported pool's imports), after its last 

362 reference is gone. The first such call on ``pool`` after arming blocks 

363 until a ``cuMemPoolImportFromShareableHandle`` from the C++ layer returns 

364 ``pool``, or until ``timeout_sec`` passes. Once that import has returned, 

365 it stays blocked until :func:`open_pool_release_gate` is called, or until 

366 ``grace_sec`` passes, and then proceeds. Later calls pass through. 

367  

368 Open the gate once the import has finished. An import that correctly waits 

369 for the release cannot finish first, so the grace period ends the hold; an 

370 import that does not wait finishes, opens the gate, and the release then 

371 revokes access after the import was granted it, so the test sees the 

372 damage. Use :func:`wait_pool_release_gate_entered` to start the import once 

373 the release is held, and :func:`disarm_pool_release_gate` to check that the 

374 import overlapped the release. 

375 """ 

376 _require_driver_fn_wrappers() 

377 _arm_pool_release_gate(<cydriver.CUmemoryPool>pool, timeout_sec, grace_sec) 

378  

379  

380def open_pool_release_gate(): 

381 """Let a held release proceed once the import that overlapped it has finished.""" 

382 _open_pool_release_gate() 

383  

384  

385def wait_pool_release_gate_entered(double timeout_sec): 

386 """Wait until a release is held by the gate; return ``False`` on timeout or disarm.""" 

387 cdef bint entered 

388 with nogil: 

389 entered = _wait_pool_release_gate_entered(timeout_sec) 

390 return entered 

391  

392  

393def disarm_pool_release_gate(): 

394 """Disarm the gate and let a held release proceed. 

395  

396 Return ``True`` if a release was held and an import of the pool returned 

397 while it was held, so the import overlapped the release. 

398 """ 

399 return _disarm_pool_release_gate() 

400  

401  

402def set_context_restore_fault(int status): 

403 """Make ``cuda.core``'s next switch back to the current context fail on this thread. 

404  

405 The next ``cuCtxSetCurrent`` that the C++ layer makes on this thread to the 

406 context that is current now returns ``status`` without switching, so the 

407 context it switched to stays current, exactly as a real failure would. The 

408 C++ layer switches contexts only to enter an operation's context and to 

409 restore the caller's afterwards, and it does not switch to a context that 

410 is already current, so only a restoration can fail. 0 disarms the fault. 

411 """ 

412 cdef cydriver.CUcontext current = NULL 1mnopqrs

413 if status: 1mnopqrs

414 _require_driver_fn_wrappers() 1mnopqrs

415 HANDLE_RETURN(cydriver.cuCtxGetCurrent(&current)) 1mnopqrs

416 _set_ctx_set_current_fault(<cydriver.CUresult>status, current) 1mnopqrs