[BUG]: Closing a memory pool resource while another thread uses it crashes the process under free-threaded Python
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 5/5
- Thời gian dự kiến
- Hơn một tuần
- Mức phù hợp với người mới
- 22/100
Hướng nghiên cứu
Start by reading _memory_pool.pyx around L590-L598 (_MP_close), the _h_pool accessors in _memory_pool.pxd L49-L50, and the _ipc_data reads in _ipc.pyx L672-L680. Then read the discussion on #3524 and #3534, since the fix hinges on a policy decision: synchronize close against readers, or document that concurrent close is unsupported. A reproducer under CPython 3.14t with PYTHON_GIL=0 closing an IPC-enabled resource while another thread calls from_registry/uuid is the first concrete step; done means either that reproducer passes or the restriction is documented and tested.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
Is this a duplicate?
- I confirmed there appear to be no duplicate issues for this bug and that I agree to the Code of Conduct
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_poolis astd::shared_ptrstored in the object.allocatecopies it andtrimdereferences it afterMP_check_open(_memory_pool.pxdL49-L50) has passed. Areset()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_datais acdef objectfield. Cython reads it with a plain load followed by an increment of the reference count. Ifclose()drops the last reference in between, the reader increments the count of a freed object.MP_registeralso readsself._ipc_data._alloc_handleafter its checks (_ipc.pyxL672-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. #3534 is the driver-level case forContext. - 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 e195f81b6, 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.
- Ngôn ngữ chính
- Cython
- Star
- 3.4k
- Fork
- 353
- Merge trung bình
- 2 ngày 3 giờ
- Pull request đã merge (30 ngày)
- 163
Chuẩn bị môi trường
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của NVIDIA/cuda-python
-
[BUG]: the `__cuda_stream__` deprecation warning points to `Stream(obj)`, which always raisesCó thể đã có người làm @Iamsohungrynow đã nhận 5 ngày trước. Đang mởbug cuda.core P1
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 86/100
NVIDIA/cuda-python#3505 · 3 bình luận · 1 reaction · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG]: ProcessInfo.used_gpu_memory returns the NVML_VALUE_NOT_AVAILABLE sentinel as a byte countĐang mởtriage
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 80/100
NVIDIA/cuda-python#3468 · 3 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
triage
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
NVIDIA/cuda-python#3409 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG]: cleanup-pr-previews never removes previews of deleted PRsCó thể làm lại được @rwgk đã nhận 48 ngày trước và không có pull request nào đang mở. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 84/100
NVIDIA/cuda-python#2952 · 1 người được giao ·
Maintainer thường phản hồi trong vòng 1 ngày
-
[BUG]: LocatedHeaderDir is mutable, so callers can poison the cached header-directory lookupCó thể đã có người làm @rwgk đã nhận 62 ngày trước. Đang mởtriage
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 82/100
NVIDIA/cuda-python#2646 · 1 reaction ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của NVIDIA/cuda-python
Issue tương tự
-
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 68/100
E3SM-Project/mam4xx#650 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
area:dmrg bug P2
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 2 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 66/100
NCAR/ccpp-physics#1256 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 70/100
vortexgpgpu/vortex#501 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Issues about WW3 couplingĐang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 62/100