GeezerVison is showing github.com — BUG: Numpy crashing when concurrent threads change the dtype of an array · Issue #28727 · numpy/numpy
BUG: Numpy crashing when concurrent threads change the dtype of an array #28727DescriptionDescribe the issue:
Found then investigating #28710.
@ngoldbaum
Reproduce the code example:
import unittest
from threading import Thread, Barrier
from test.support import threading_helper
import numpy as np
threading_helper.requires_working_threading(module=True)
class ItertoolsThreading(unittest.TestCase):
@threading_helper.reap_threads
def test_result_type(self):
number_of_threads = 6
number_of_iterations = 25
number_of_cycles = 800
barrier = Barrier(number_of_threads)
x = np.array([1., 2., 3., 4.], np.dtype([('f1', [('f1', '<i2')])]))
y = np.array([1, 2,], np.dtype([('f1', [('f1', '<i2')])]))
def work(it):
barrier.wait()
for _ in range(number_of_cycles):
#print(f'{it=} {_}')
x.dtype = np.dtype([('f1', [('f1', '<i2')])]) # single reference
y.dtype = np.dtype([('f1', [('f1', '<i2')])]) # single reference
np.result_type(x, y)
for it in range(number_of_iterations):
print(f'iteration {it}')
worker_threads = []
for ii in range(number_of_threads):
worker_threads.append(
Thread(target=work, args=[ii]))
with threading_helper.start_threads(worker_threads):
pass
barrier.reset()
print('done')
if __name__ == "__main__":
unittest.main()
Error message:
Python and NumPy Versions:
Tested on Linux with a virtual environment created with uv with python 3.13t.
Runtime Environment:
No response
Context for the issue:
No response Activityngoldbaum commented on Apr 16, 2025 When I try running the script, I get ModuleNotFoundError: No module named 'test.support'; 'test' is not a package - am I doing something wrong? I don't have much experience with unittest. ngoldbaum commented on Apr 16, 2025 Oh never mind, it's because I named my test script test.py 🙃 ngoldbaum commented on Apr 16, 2025 Argh, this reveals other places we create borrowed references to array descriptors :( ngoldbaum commented on Apr 16, 2025 If I run under TSAN, the first race that gets reported is here:
WARNING: ThreadSanitizer: data race (pid=20567)
Read of size 8 at 0x00010b94f5f8 by thread T1:
#0 PyArray_ITEMSIZE ndarrayobject.h:251 (_multiarray_umath.cpython-313td-darwin.so:arm64+0x2c5580)
#1 array_descr_set getset.c:421 (_multiarray_umath.cpython-313td-darwin.so:arm64+0x2c1e50)
#2 getset_set descrobject.c:249 (libpython3.13td.dylib:arm64+0x1b56f0)
#3 _PyObject_GenericSetAttrWithDict object.c:1782 (libpython3.13td.dylib:arm64+0x2723f0)
#4 PyObject_GenericSetAttr object.c:1853 (libpython3.13td.dylib:arm64+0x2727b4)
#5 PyObject_SetAttr object.c:1415 (libpython3.13td.dylib:arm64+0x270848)
#6 _PyEval_EvalFrameDefault generated_cases.c.h:5492 (libpython3.13td.dylib:arm64+0x485f48)
#7 _PyEval_EvalFrame pycore_ceval.h:119 (libpython3.13td.dylib:arm64+0x44f03c)
#8 _PyEval_Vector ceval.c:1816 (libpython3.13td.dylib:arm64+0x44ef14)
#9 _PyFunction_Vectorcall call.c:413 (libpython3.13td.dylib:arm64+0x197598)
#10 _PyObject_VectorcallTstate pycore_call.h:168 (libpython3.13td.dylib:arm64+0x19eca0)
#11 method_vectorcall classobject.c:70 (libpython3.13td.dylib:arm64+0x19cf44)
#12 _PyVectorcall_Call call.c:273 (libpython3.13td.dylib:arm64+0x196e34)
#13 _PyObject_Call call.c:348 (libpython3.13td.dylib:arm64+0x197158)
#14 PyObject_Call call.c:373 (libpython3.13td.dylib:arm64+0x197278)
#15 thread_run _threadmodule.c:337 (libpython3.13td.dylib:arm64+0x6dc8f4)
#16 pythread_wrapper thread_pthread.h:243 (libpython3.13td.dylib:arm64+0x5cfb1c)
Previous write of size 8 at 0x00010b94f5f8 by thread T6:
#0 array_descr_set getset.c:508 (_multiarray_umath.cpython-313td-darwin.so:arm64+0x2c253c)
#1 getset_set descrobject.c:249 (libpython3.13td.dylib:arm64+0x1b56f0)
#2 _PyObject_GenericSetAttrWithDict object.c:1782 (libpython3.13td.dylib:arm64+0x2723f0)
#3 PyObject_GenericSetAttr object.c:1853 (libpython3.13td.dylib:arm64+0x2727b4)
#4 PyObject_SetAttr object.c:1415 (libpython3.13td.dylib:arm64+0x270848)
#5 _PyEval_EvalFrameDefault generated_cases.c.h:5492 (libpython3.13td.dylib:arm64+0x485f48)
#6 _PyEval_EvalFrame pycore_ceval.h:119 (libpython3.13td.dylib:arm64+0x44f03c)
#7 _PyEval_Vector ceval.c:1816 (libpython3.13td.dylib:arm64+0x44ef14)
#8 _PyFunction_Vectorcall call.c:413 (libpython3.13td.dylib:arm64+0x197598)
#9 _PyObject_VectorcallTstate pycore_call.h:168 (libpython3.13td.dylib:arm64+0x19eca0)
#10 method_vectorcall classobject.c:70 (libpython3.13td.dylib:arm64+0x19cf44)
#11 _PyVectorcall_Call call.c:273 (libpython3.13td.dylib:arm64+0x196e34)
#12 _PyObject_Call call.c:348 (libpython3.13td.dylib:arm64+0x197158)
#13 PyObject_Call call.c:373 (libpython3.13td.dylib:arm64+0x197278)
#14 thread_run _threadmodule.c:337 (libpython3.13td.dylib:arm64+0x6dc8f4)
#15 pythread_wrapper thread_pthread.h:243 (libpython3.13td.dylib:arm64+0x5cfb1c)
If you take a look at getset.c at the lines in the race report, you'll see that the getters and setters for the dtype property are also not safe for multithreaded use. I think this may fall under "mutating numpy arrays in a multithreaded context isn't safe".
I'm not sure how hard it might be to add per-object locking to at least make the Python interface safe without introducing multithreaded scaling bottlenecks on existing workflows. You could imagine hiding all array state behind an RWLock, for example. Things get tricky quick!
IMO a better path is to think about an immutable alternative to ndarray that doesn't support modifying any properties after creating the immutable array. mhvk commented on Apr 16, 2025
IMO a better path is to think about an immutable alternative to ndarray that doesn't support modifying any properties after creating the immutable array.
Might a simpler solution be to have a new flag, perhaps NPY_ARRAY_MUTABLE, which if not set indicates the array is immutable? (Here, I chose a negative definition following NPY_ARRAY_WRITEABLE - probably an array should never be writeable if it is immutable.) ngoldbaum commented on Apr 16, 2025 Making the guarantees around read-only ndarrays stronger would also work. I’m definitely not volunteering to write an immutable ndarray-like thing! Either way it’s a big (NEP-worthy) project. seberg commented on Apr 22, 2025 We never deprecated dtype setting from Python? :)
While having an immutable array may well be worthwhile (i.e. a flag as mentioned), .data, .strides, .dtype, and .shape have no real business being mutable even for normal, mutable, arrays.
I would be happy to deprecate all of them (slowly!), we did remove .data. I think .shape was the oddest ones, but since we have np.reshape(..., copy=False) now, the use-case is less bad, unfortunately, still quite noisy.
(And I am not sure we can do refcount(arr) == 1 checks, to allow safe uses anymore.)
I.e. this is similar to np.resize(), it's just unsafe API... And maybe we should just start putting on a big warning in the docs that tells you to use the alternative (that creates a new view). eendebakpt commented on Apr 22, 2025 ContributorAuthor More actions Deprecating mutable strides, dtype etc. sounds like a good thing. Maybe starting just in the FT build? Not sure what slowly means here.
In cpython the equivalent of refcount(arr) == 1 in the FT build is _PyObject_IsUniquelyReferenced. But we would have to check the usage in numpy. seberg commented on Apr 22, 2025
In cpython the equivalent of refcount(arr) == 1 in the FT build is _PyObject_IsUniquelyReferenced. But we would have to check the usage in numpy.
Maybe worth looking at, also because np.resize already needs that. If we can (relatively reliably) detect that, then that might be nice:
- Document that these are discouraged and only safe for fresh (uniquely references) arrays.
- Deprecate for non nuniquely referenced arrays.
.shape is for example used a lot in masked arrays, if the deprecation is bearable there, I suspect we are OK.
.dtype and .strides seem both a lot more niche to me and I would be more happy to just deprecate them (unless some massive user shows up).
EDIT: I don't really see much reason to limit this to the FT build. If it is an extremely noisy deprecation otherwise, maybe there is a point though. mhvk commented on Apr 22, 2025 Agree with deprecating! And at least dtype and strides should be possible relatively quickly. ngoldbaum commented on Apr 23, 2025 I'll go ahead and open up followup issues about deprecating setting dtype and strides to see how noisy those are. We can followup latter with shape if it turns out not to be too terrible to deal with downstream. eendebakpt commented on Aug 11, 2026 ContributorAuthor More actions Setting the dtype has been deprecated. Closing the issue
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|