Skip to content

BUG: Make legacy user dtype registration thread-safe - #33552

Open
SwayamInSync wants to merge 2 commits into
numpy:mainfrom
SwayamInSync:fix/user-dtype-registration-race
Open

SwayamInSync wants to merge 2 commits into
numpy:mainfrom
SwayamInSync:fix/user-dtype-registration-race

Conversation

@SwayamInSync

@SwayamInSync SwayamInSync commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Closes #33545 at its source (follow-up to #33548).

Legacy user dtype registration (PyArray_RegisterDataType and the NPY_DT_legacy_descriptor_proto path) grew the global userdescrs table with an unlocked realloc and NPY_NUMUSERTYPES++, while readers scanned it without synchronization. Under free-threading this corrupted the heap.

  • userdescrs is now a fixed-size table (NPY_VSTRING - NPY_USERDEF slots, the existing limit), so it is never reallocated.
  • A dtype is published only once fully built: the slot is filled, then the count is incremented with release ordering; readers load it with acquire ordering. Nothing is rolled back, so a failed registration leaves nothing behind.
  • Registrations are serialized by a PyMutex on free-threaded builds and by the GIL otherwise. No user code runs while serialized: validation, the descriptor copy (c_metadata clone) and the scalar type mapping happen outside.
  • A prototype whose scalar type is already mapped to another DType fails before a type number is used.
  • Adds a threaded registration test and removes the thread_unsafe markers that only existed because of this race.

AI Disclosure

Only at testing and regression checking

@ngoldbaum

Copy link
Copy Markdown
Member

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.

@SwayamInSync

Copy link
Copy Markdown
Member Author

@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.

@SwayamInSync
SwayamInSync force-pushed the fix/user-dtype-registration-race branch from 0d8fbdc to b6624e8 Compare December 2, 2026 11:39
@SwayamInSync

Copy link
Copy Markdown
Member Author

Follow-up: #33556 (draft, stacked on this PR; only its last commit is new) makes _PyArray_MapPyTypeToDType check and insert the scalar type in one PyDict_SetDefaultRef call. Without it, two concurrent registrations of the same scalar type with different prototypes can both succeed and one mapping is silently lost (this also happens on main). I kept it separate since it is independent of the registration table itself.

@SwayamInSync
SwayamInSync force-pushed the fix/user-dtype-registration-race branch from 02c0064 to a08402e Compare December 2, 2026 12:45
@SwayamInSync

Copy link
Copy Markdown
Member Author

a08402e: on free-threaded builds, a fork child now resets the registration lock (via pthread_atfork), so registering in the child no longer hangs if another thread held the lock at fork. Also fixes the already-mapped scalar type check (only np.generic subclasses, compared under the lock) and adds a test for it.

@ngoldbaum ngoldbaum left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: one-off failure in laguerre polynomial testing under parallel threads

2 participants