Skip to content

fix(cuda-core): quiesce background resource retirement before process exit - #1831

Open
nihalpasham wants to merge 2 commits into
NVIDIA:mainfrom
nihalpasham:fix/cuda-core-retirement-exit-quiesce
Open

nihalpasham wants to merge 2 commits into
NVIDIA:mainfrom
nihalpasham:fix/cuda-core-retirement-exit-quiesce

Conversation

@nihalpasham

Copy link
Copy Markdown
Collaborator

What This PR Does

Quiesces cuda-core's detached "cuda-resource-retirement" worker thread before libcuda and Compute Sanitizer (libsanitizer-public.so) tear down global state during process exit(), resolving NVBug 7090395:

BEFORE (process-exit race in `cuda-core/src/completion.rs`):
  Main thread                               "cuda-resource-retirement" worker
  ────────────────────────────────────────  ────────────────────────────────────────
  drops `DeviceBuffer` -> defer(cuMemFree)  (asleep in 1 ms recv_timeout)
  main() returns -> CRT exit(0) starts
  libsanitizer + libcuda destructors   ◄──► wakes on another core & calls
                                            cuEventQuery / cuMemFree / cuEventDestroy
                                            into tearing-down driver & sanitizer [X]
                                            (dmesg: `cuda-resource-r` segfault in
                                             `libsanitizer-public.so` / `libcuda.so`)

AFTER (LIFO `atexit` quiescence + `Condvar` idle park):
  1. `GLOBAL_QUEUE` registers C `atexit(on_process_exit)` after `cuInit` / sanitizer init.
  2. On `exit(0)`, LIFO runs `on_process_exit` BEFORE `libcuda` / sanitizer destructors:
     - acquires `driver_gate` (waits for any in-flight batch without `thread::join`,
       avoiding Windows DLL loader-lock deadlocks),
     - drains already-completed cleanups and cascading buffer frees (`0` leaked bytes
       under `compute-sanitizer --tool memcheck --leak-check full`),
     - sets `exiting = true` and leaks any unfinished GPU leases so the background
       worker never calls into `libcuda` or `libsanitizer` during exit teardown. [OK]

1. Scoped RetirementQueue Exit Fence & Idle Parking

  • Evidence from DVS-SC (RTX 5080, sm_120a): Under cargo oxide sanitize barrier --tool synccheck (and racecheck), all three barrier checks printed SUCCESS before crashing at exit (segfault at 0xaa48 in libcuda.so.620.70.08 on cuda_13.5, and cuda-resource-r segfaulting in libsanitizer-public.so / glibc fastbins corruption in dmesg.log on cuda_ext).
  • Non-blocking caller path preserved: enqueue locks only Inbox (queue), never waiting on driver_gate or driver calls.
  • Zero idle polling: Replaces the unconditional 1 ms recv_timeout loop when empty with Condvar::wait, polling at 1 ms only while in-flight GPU events remain queued.
File Change
cuda-core/src/completion.rs Add RetirementQueue driver_gate, atexit drain/fence, unit test
cuda-core/tests/shared_allocation.rs Add subprocess + synccheck exit-after-buffer-drop regression test

Verification

  • Host Workspace & Compute Sanitizer (RTX 5090, sm_120a):
    • cargo test -p cuda-core (all unit, integration, trybuild, and doc tests + gpu_fence_tests --ignored): PASS
    • cargo test -p cuda-async -- --test-threads=1: PASS
    • cargo oxide sanitize vecadd --tool memcheck, barrier --tool racecheck, barrier --tool synccheck: PASS (0 errors)
    • compute-sanitizer --tool memcheck --leak-check full .../barrier: PASS (0 bytes leaked in 0 allocations)

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • RUSTDOCFLAGS="-D warnings" cargo doc -p cuda-core --no-deps
  • cargo test -p cuda-core & cargo test -p cuda-core --lib gpu_fence_tests -- --ignored
  • cargo test -p cuda-async -- --test-threads=1
  • just -f cuda-oxide/Justfile check-guards

… exit

`cuda-core::completion` spawns a detached `"cuda-resource-retirement"`
thread backed by a static queue that never closed. When a binary drops a
`DeviceBuffer` right before returning from `main()` (such as `barrier`
under `compute-sanitizer --tool synccheck`), CRT `exit()` runs `atexit`
and `.fini_array` destructors in `libsanitizer-public.so` and `libcuda.so`
concurrently with the worker waking up on another core and calling
`cuEventQuery`, `cuMemFree`, and `cuEventDestroy` against tearing-down
driver and sanitizer state.

Register an ISO C `atexit` handler after `cuInit` and sanitizer startup so
LIFO exit ordering invokes it before `libcuda` and Compute Sanitizer
destructors. Under a worker driver gate, drain already-completed cleanups
(including cascading buffer frees so `--leak-check full` reports zero
leaked allocations), mark the queue exiting, and leak any genuinely
unfinished GPU leases without joining the worker thread (avoiding Windows
DLL loader-lock deadlocks). Also park the idle worker on a `Condvar`
instead of polling every 1 ms when the queue is empty.

Resolves NVBug 7090395.

Signed-off-by: nihalpasham <[email protected]>
@nihalpasham nihalpasham added bug Something isn't working host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) safety Memory safety, soundness, or undefined behavior tests Adds or improves test coverage runtime Shared runtime crates: cuda-bindings, cuda-core, cuda-core-derive, cuda-async; Tile and SIMT co-own NVBugs Issues and PRs linked to NVBugs tickets labels Nov 17, 2026
@elibol

elibol commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

@nihalpasham thanks! The approach looks reasonable. I found two things we ought to fix before merging:

  • Exit during initialization: on_process_exit() can run while GLOBAL_QUEUE is still initializing, see None, and return. Initialization can then start the worker after the exit callback has finished. The shutdown state needs to remain visible throughout initialization.

  • Completed work already held by the worker: shutdown_for_exit() stops draining when the inbox is empty, without checking the existing in_flight list. Events that completed since the worker’s last poll are therefore leaked unnecessarily. That list should get a completion check even when nothing new was enqueued.

I reproduced both locally, using controlled scheduling for the initialization race. Could we address these and add regression tests?

… items

Address two review findings in `cuda-core::completion` exit quiescence:

1. Allocate the shared `RetirementQueue` inside `RetirementRuntime` ahead of
   `atexit` registration and worker creation so `on_process_exit()` observes
   and records shutdown state even if invoked while first-use initialization
   is still in flight, preventing worker startup after exit teardown begins.
2. Poll existing `in_flight` items in `shutdown_for_exit()` even when `inbox`
   is empty so GPU events that completed since the worker's last poll (and
   any cascading buffer frees they enqueue) are drained instead of leaked.

Add unit regression tests for both scenarios.

Signed-off-by: nihalpasham <[email protected]>
@nihalpasham

Copy link
Copy Markdown
Collaborator Author

@elibol addressed both in 0b55a3441 with unit regression tests:

1. Exit-vs-init race:
   BEFORE: OnceLock::get() == None during get_or_init -> exit missed queue, worker spawned
   AFTER:  RetirementRuntime allocates queue ahead of atexit; exit sets shutting_down = true
           without init_lock and aborts worker startup (tested via controlled Barrier pair)

2. Completed in-flight items with empty inbox:
   BEFORE: shutdown_for_exit() broke early on empty inbox, skipping gate.in_flight
   AFTER:  drains gate.in_flight (plus any cascading defer items) before closing inbox

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

bug Something isn't working host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) NVBugs Issues and PRs linked to NVBugs tickets runtime Shared runtime crates: cuda-bindings, cuda-core, cuda-core-derive, cuda-async; Tile and SIMT co-own safety Memory safety, soundness, or undefined behavior tests Adds or improves test coverage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants