Skip to content

[BUG]: Closing a memory pool resource while another thread uses it crashes the process under free-threaded Python #3554

Backlog

Description

@juenglin

Is this a duplicate?

Type of Bug

Crash

Component

cuda.core

Describe the bug

On a free-threaded build, calling close() on a memory pool resource (DeviceMemoryResource, PinnedMemoryResource) while another thread uses the same object crashes the process. With the GIL, the other thread gets RuntimeError("... has been closed").

Goal of this issue. A thread that uses a resource closed by another thread must not crash the process. It either completes its call or raises. This issue does not ask for more: the ordering and outcome of the racing calls stay undefined, as concurrency.rst says, and the application remains responsible for synchronizing them if it needs a defined result.

Cause. _MP_close resets the pool handle and clears the IPC data without synchronization (_memory_pool.pyx L590-L598):

self._h_pool.reset()
...
self._ipc_data = None

Other threads read both fields without a lock:

  • _h_pool is a std::shared_ptr stored in the object. allocate copies it and trim dereferences it after MP_check_open (_memory_pool.pxd L49-L50) has passed. A reset() in between frees the control block and destroys the pool, so the reader increments a freed reference count and passes a destroyed pool to the driver.
  • _ipc_data is a cdef object field. Cython reads it with a plain load followed by an increment of the reference count. If close() drops the last reference in between, the reader increments the count of a freed object. MP_register also reads self._ipc_data._alloc_handle after its checks (_ipc.pyx L672-L680).

With the GIL, these reads and writes do not interleave. Builtin CPython objects do not have this problem under free-threading: a list read that races clear() returns an item or raises, because the interpreter locks the object and keeps the item alive for the reader. Fields of extension types get no such protection unless the extension adds it.

The IPC registry shares resources implicitly. The registry returns the same resource object to every thread that imports the pool's allocation handle, calls from_registry, or unpickles a buffer from that pool. Threads can therefore share a resource without having passed it to each other, and a close() in one of them races with use in the others.

Out of scope.

  • Other classes whose close() resets a handle without a lock (Buffer, Stream, Event, Program, Linker, the graph builder, IPCAllocationHandle, and others). They have the same defect and can follow once the approach is agreed here. [BUG]: Context.close() on another thread destroys a green context that is still current #3534 is the driver-level case for Context.
  • GPU work that is still queued when a resource is closed, and raw values obtained from .handle. Both are the caller's responsibility today, with or without threads.

Related: #1389 (thread-safety in cuda.core), #3534 (Context.close() from another thread), #3524 (IPC registry under free-threading, where this came up in review).

How to Reproduce

Worker threads only use a DeviceMemoryResource; the main thread creates and closes resources in a loop. The IPC registry is not needed.

# python3.14t -X faulthandler repro_3554.py [ipc|alloc|trim] [seconds]
import sys
import sysconfig
import threading
import time

from cuda.core import Device, DeviceMemoryResource, DeviceMemoryResourceOptions
from cuda.core._utils.cuda_utils import CUDAError

mode = sys.argv[1] if len(sys.argv) > 1 else "ipc"
seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 60.0
NTHREADS = 4

assert sysconfig.get_config_var("Py_GIL_DISABLED"), "needs a free-threaded build"
print("GIL enabled:", sys._is_gil_enabled(), flush=True)

dev = Device(0)
dev.set_current()
current = [None]  # the resource the workers use
stop = threading.Event()
errors = {}


def use(mr, stream):
    if mode == "ipc":
        # Python-object field (_ipc_data) cleared by close().
        mr.uuid
        mr.is_mapped
        mr.allocation_handle
    elif mode == "alloc":
        # shared_ptr field (_h_pool) reset by close().
        mr.allocate(4096, stream=stream).close(stream)
    elif mode == "trim":
        mr.trim()


def worker():
    dev.set_current()
    stream = dev.create_stream()
    while not stop.is_set():
        mr = current[0]
        if mr is None:
            continue
        try:
            use(mr, stream)
        except (RuntimeError, CUDAError, TypeError, AttributeError) as e:
            key = f"{type(e).__name__}: {str(e)[:80]}"
            errors[key] = errors.get(key, 0) + 1


threads = [threading.Thread(target=worker) for _ in range(NTHREADS)]
for t in threads:
    t.start()

options = DeviceMemoryResourceOptions(max_size=1 << 24, ipc_enabled=(mode == "ipc"))
deadline = time.monotonic() + seconds
n = 0
while time.monotonic() < deadline:
    mr = DeviceMemoryResource(dev, options=options)
    current[0] = mr
    for _ in range(200):  # let the workers get going on this resource
        pass
    mr.close()
    n += 1

stop.set()
for t in threads:
    t.join()
print(f"no crash after {n} close() calls in {seconds:.0f}s; worker errors:")
for k, v in sorted(errors.items(), key=lambda kv: -kv[1]):
    print(f"  {v:8d}  {k}")

Results with cuda-core built from main at e195f81, cuda-bindings 13.5.0 and CPython 3.14.9 (free-threaded build):

Mode Worker calls Field PYTHON_GIL=0 PYTHON_GIL=1, 30 s
ipc uuid, is_mapped, allocation_handle _ipc_data SIGSEGV in mr.uuid no crash in 1,678 close() calls
alloc allocate, then Buffer.close _h_pool SIGSEGV in deviceptr_alloc_from_pool no crash in 9,710 close() calls
trim trim _h_pool SIGFPE in cuMemPoolTrimTo (libcuda.so) no crash in 10,126 close() calls

Without the GIL, each mode crashes less than half a second after the process starts. With the GIL, the workers only see RuntimeError: DeviceMemoryResource has been closed.

Expected behavior

No crash. A call that races close() on the same resource either completes or raises an exception, for example RuntimeError("DeviceMemoryResource has been closed").

Operating System

Linux, NVIDIA driver 595.99.02, RTX 6000 Ada. The race needs a free-threaded CPython build.

Activity

  1. added
    bug
    on Nov 24, 2026
  2. changed the title [-][BUG]: Closing a memory pool resource races with its use on other threads under free-threaded Python[/-] [+][BUG]: Closing a memory pool resource while another thread uses it crashes the process under free-threaded Python[/+] on Nov 25, 2026
  3. juenglin commented on Nov 25, 2026

    @juenglin
    ContributorAuthor

    Proposed fix: copy the handle under a per-object lock

    This is the pattern free-threaded CPython uses for its builtin objects, in two parts:

    1. A per-object critical section makes each access to the field atomic.
    2. Reference counting keeps what a reader obtained alive until the reader is done.

    cuda.core already has the second part. A handle is a std::shared_ptr, and each allocation holds its own copy of the pool handle, which is how close() defers the destruction of a pool that still has allocations. Only the first part is missing: the copy out of the object's field and the reset() in close() are not atomic with respect to each other.

    Sketch for _MemPool

    Not compiled.

    # Reader side: replaces MP_check_open followed by reads of self._h_pool.
    cdef inline int MP_acquire(_MemPool self, MemoryPoolHandle& h) except -1:
        with cython.critical_section(self):
            h = self._h_pool          # copy: this call now co-owns the pool
        if not h:
            raise RuntimeError(f"{self.__class__.__name__} has been closed")
        return 0
    
    
    # Writer side.
    cdef inline _MP_close(_MemPool self):
        cdef MemoryPoolHandle h
        cdef object ipc_data, attributes
        with cython.critical_section(self):
            h.swap(self._h_pool)      # the field is empty from here on
            self._mempool_owned = False
            ipc_data, self._ipc_data = self._ipc_data, None
            attributes, self._attributes = self._attributes, None
        # h, ipc_data and attributes are dropped here, outside the lock. The pool is
        # destroyed now, or when the last call or allocation that holds a copy ends.

    A method then takes its copy once and never reads the field again:

    def trim(self, size_t min_bytes_to_keep=0) -> None:
        cdef MemoryPoolHandle h
        MP_acquire(self, h)
        ...
        with nogil:
            ...
            err = cydriver.cuMemPoolTrimTo(as_cu(h), min_bytes_to_keep)

    Accessors of the Python-object fields (uuid, is_mapped, is_ipc_enabled, allocation_handle, attributes, and MP_register) read the field under the same critical section, into a local, and work on the local.

    Resulting behavior

    • A call that races close() either raises RuntimeError("... has been closed") or runs to completion on a live pool.
    • If a call is in flight, the destruction of the pool is deferred until that call returns. close() already documents deferred destruction for outstanding allocations, so this adds no new semantics.
    • Which of the two outcomes a racing call gets remains undefined.

    Why not hold the lock for the whole operation

    A critical section is suspended when the thread detaches from the interpreter, which every with nogil block around a driver call does. It cannot serialize a driver call against close(). It can protect the short copy and the swap, and that is all this approach needs.

    Scope and cost

    • _MemPool has one handle field and three Python-object fields, with about 100 references in 16 files, about 40 of them in _memory_pool.pyx. I estimate a few days including a stress test based on the reproducer.
    • The cost per call is one uncontended critical section and one shared_ptr copy.
    • The same pattern applies to the other classes listed as out of scope in the description. For Buffer, the accessor also returns _size, so that a caller gets a consistent pointer and size. The kernel argument path is the one to benchmark before extending the pattern to Buffer and Stream.

    Policy

    cuda_core/AGENTS.md says that close() racing another call is the caller's responsibility and "do not add locks to make it safe". This proposal keeps the first half, since the outcome stays undefined, and changes the second: the library adds the lock needed to keep the process alive. That section and concurrency.rst need an update along with the fix. concurrency.rst should also say that the IPC registry hands the same resource object to every importer in the process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions