Repository navigation
BUG: Make legacy user dtype registration thread-safe - #33552
SwayamInSync wants to merge 2 commits into
Conversation
|
In the test, it was registering a dtype repeatedly in multiple threads. Do we want to allow that? We definitely want to allow registering distinct dtypes safely. |
|
@ngoldbaum Each thread registers a distinct dtype (a fresh scalar class per call), so the same one is never registered twice. Re-registering the same prototype still returns the existing type number. While reviewing this further I found that the current version isn't right yet: a failed registration can be observed by other threads (a segfault on free-threaded builds), and the GIL alone isn't enough since registration can run Python code. I'm reworking it so a dtype is only made visible once it is fully built, and will ping when it's updated. |
0d8fbdc to
b6624e8
Compare
|
Follow-up: #33556 (draft, stacked on this PR; only its last commit is new) makes |
b6624e8 to
02c0064
Compare
…alar types under it
02c0064 to
a08402e
Compare
|
a08402e: on free-threaded builds, a fork child now resets the registration lock (via |
ngoldbaum
left a comment
There was a problem hiding this comment.
This PR is not correct (see below) and it's extremely tricky to get multithreaded C code like this correct. You say in your AI disclosure that you only used it for regression checking and testing. Getting this sort of thing correct is so incredibly difficult I wouldn't limit myself like that, but I would be extremely critical of any design and go through a lot of possible failure modes before being confident. It's OK, even encouraged to use the AI models, just try to think about what it's writing critically.
The fork reset problem is a non-issue, IMO. Combining fork with threads is a known bad idea (see https://numpy.org/devdocs/user/basics.performant_code.html#reduce-creation-overhead and the note on the fork method here https://docs.python.org/3/library/multiprocessing.html#multiprocessing-start-methods).
We also have process-global import and argument-parser mutexes without child resets. Adding fork protection for a new mutex leaves those unprotected so it's putting the cart before the horse to add that here.
|
|
||
| npy_lock_usertypes(); | ||
| int typenum = register_data_type( | ||
| descr_proto, descr, scalar_mapped, &published); |
There was a problem hiding this comment.
I would be very surprised if this is not somehow re-entrant, leading to a deadlock because PyMutex isn't a reentrant mutex.
In fact, with the help of an AI model, here is an example that deadlocks on this PR:
import concurrent.futures
import random
import threading
import numpy as np
from numpy._core._multiarray_tests import create_custom_field_dtype as register
blueprint = np.dtype([("field", object)])
active = threading.local()
outer_lock = threading.Lock()
class Finalizer:
def __del__(self):
if getattr(active, "registering", False):
active.registering = False
register(blueprint, type("Nested", (), {}), 0)
class Holder:
pass
def worker(index):
rng = random.Random(index)
holder = Holder()
for number in range(340):
for _ in range(rng.randrange(8, 128)):
holder.__dict__ = {"item": Finalizer()}
scalar = type(f"Scalar{index}_{number}", (np.generic,), {})
with outer_lock:
active.registering = True
try:
register(blueprint, scalar, 0)
finally:
active.registering = False
with concurrent.futures.ThreadPoolExecutor(4) as pool:
list(pool.map(worker, range(4)))I wouldn't focus too hard on fixing this one particular deadlock. Instead, you want to come up with a design that lets you hold the lock for as small a time as possible and, while holding the lock, that you don't make any calls that could possibly be reentrant. It should be obvious to the reviewer that the design is safe. Holding a lock around a complicated function like this is not that.
Note that avoiding re-entrancy means avoiding more or less anything in the CPython C API. It's better to somehow figure out a way to separate out "C state" from "python state" and only lock around mutating the C state. Critical sections are better for python state because they can't deadlock but they also have severe safety caveats because they can be suspended instead of causing a deadlock.
If we do actually want to make this thread-safe (which we should decide on before writing any more code), here is the outline of a simpler design:
Build the descriptor, DType class, and within-dtype cast first. Then take the lock, recheck for duplicate registration and capacity, assign the type number, fill the slot, and publish the count. That makes the locked section just pointer and integer operations. Type creation, error reporting, and cleanup can all run outside it.
Closes #33545 at its source (follow-up to #33548).
Legacy user dtype registration (
PyArray_RegisterDataTypeand theNPY_DT_legacy_descriptor_protopath) grew the globaluserdescrstable with an unlockedreallocandNPY_NUMUSERTYPES++, while readers scanned it without synchronization. Under free-threading this corrupted the heap.userdescrsis now a fixed-size table (NPY_VSTRING - NPY_USERDEFslots, the existing limit), so it is never reallocated.PyMutexon free-threaded builds and by the GIL otherwise. No user code runs while serialized: validation, the descriptor copy (c_metadataclone) and the scalar type mapping happen outside.thread_unsafemarkers that only existed because of this race.AI Disclosure
Only at testing and regression checking