Skip to content

Fix concurrent execution of compiled NumExpr objects - #570

Open
xuu33030 wants to merge 2 commits into
pydata:masterfrom
xuu33030:fix/compiled-expression-thread-safety
Open

xuu33030 wants to merge 2 commits into
pydata:masterfrom
xuu33030:fix/compiled-expression-thread-safety

Conversation

@xuu33030

Copy link
Copy Markdown

Summary

  • serialize calls to the same compiled NumExpr object with a per-object lock
  • release the GIL while waiting for that lock
  • add a synchronized regression test that forces NumExpr's single-threaded execution path

Problem

A compiled NumExpr object stores mutable execution buffers on the object. When the same object is called concurrently while NUMEXPR_NUM_THREADS=1, multiple Python threads can enter the serial interpreter path at once and overwrite that shared state, causing incorrect results or heap corruption.

The existing global parallel_mutex only protects the multi-threaded interpreter path and therefore does not cover this case.

Verification

  • Before the fix, the new regression test aborts with SIGABRT on macOS arm64 / Python 3.13 / NumPy 2.5.3.
  • python -m pytest numexpr/tests/test_numexpr.py::test_threading::test_shared_compiled_expression -q — 1 passed
  • python -m pytest -q — 6043 passed
  • issue reproducer with NUMEXPR_NUM_THREADS=1 — prints OK
  • git diff --check — clean

Closes #569

@kif

kif commented Sep 20, 2026

Copy link
Copy Markdown

I confirm this PR addresses the bug.

@FrancescAlted

Copy link
Copy Markdown
Contributor

It looks like some test is stalled with this PR. Any hint?

@kif

kif commented Sep 20, 2026

Copy link
Copy Markdown

All stall processes are when testing 3.14t, i.e. the free-threaded version.

@xuu33030

Copy link
Copy Markdown
Author

I reproduced the stall locally on Python 3.14t with the CI test command. The new regression test passed on its own, but under pytest --parallel-threads=4 multiple copies of that test ran concurrently; the thread dump showed one copy waiting in set_num_threads() while others were joining workers. That test changes NumExpr’s global worker-pool size, so I marked it thread_unsafe (the suite’s existing convention) while retaining its own concurrent-expression workers. With that one-line change, the full --parallel-threads=4 --pyargs numexpr suite passed locally on 3.14t (6043 tests), as did repeated focused runs. The previous CI hang is consistent with this interaction; it does not establish a deadlock in the per-object lock. The new Build workflow currently requires maintainer approval to run on this fork PR.

@kif

kif commented Sep 23, 2026

Copy link
Copy Markdown

Apparently the fact the tests dead-lock in thread-free version of python is a different issue related to the set_num_threads() function which is not properly protected in this flavor of python. It is only by chance (or thanks to the GIL) that it did not show off earlier.

I can propose some locking to protect this function if needed, but maybe @xuu33030 prefers doing it on his own.

@xuu33030

Copy link
Copy Markdown
Author

Thanks for offering, @kif. Would you like to take the set_num_threads() investigation? The current 3.14t CI is green after isolating the regression test, but that does not establish that concurrent set_num_threads() calls are safe. Would the maintainers prefer to track this separately in a new issue/PR, or keep it within #570?

@kif

kif commented Sep 26, 2026

Copy link
Copy Markdown

I think I will submit a separated PR ... maybe even open another issue since what we see here is just highlighting an issue already pre-existing.

@kif

kif commented Nov 19, 2026

Copy link
Copy Markdown

I did that on #572

I reviewed this diff against the interpreter code, and the approach looks correct to me. In the serial path, get_temps_space() writes the temporaries' pointers into self->mem, and free_temps_space() frees them later. When two threads share one compiled object, each overwrites the other's pointers, so the same blocks get freed twice. That matches the double free / corrupted size aborts reported in #569. A per-object lock is the simplest way to fix it.

Some remarks, none of them blocking:

  1. The bug is not limited to NUMEXPR_NUM_THREADS=1 (an argument for this PR). run_interpreter() also takes the serial path when gs.force_serial is set. NumExpr_run() sets it:
  • for small operands (NpyIter_GetIterSize(iter) < 2*BLOCK_SIZE1, i.e. fewer than 2048 elements);
  • for every reduction (is_reduction).

So a shared compiled expression running a sum()/prod(), or working on small arrays, can corrupt the heap even with several numexpr threads. Setting NUMEXPR_NUM_THREADS>=2, the workaround suggested in #569, is therefore not a complete fix. Since this PR takes the lock at the top of NumExpr_run(), it covers all of these cases. It may be worth saying so in the PR description, and possibly adding a reduction variant to the regression test (e.g. NumExpr("sum(a*b)")).

  1. Avoid dropping the GIL when the lock is not contended. At the moment, every call goes through Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS, even when no other thread uses the object. That gives the GIL away on every call. A non-blocking attempt first would keep the common case cheap:
explicit NumExprRunLock(PyThread_type_lock lock) : lock(lock) {
    if (!PyThread_acquire_lock(lock, NOWAIT_LOCK)) {
        Py_BEGIN_ALLOW_THREADS;
        PyThread_acquire_lock(lock, WAIT_LOCK);
        Py_END_ALLOW_THREADS;
    }
}
  1. Re-entrancy (corner case). The lock is taken before the arguments are converted, and that conversion can run arbitrary Python code (e.g. a user-defined array). If that code calls the same NumExpr object, the thread deadlocks on itself, because PyThread locks are not re-entrant. This is very unlikely in practice. A short comment would do, or the lock could be taken just before the code that first writes self->memsizes / self->mem.

  2. A related issue to follow up separately. gs.force_serial is a process-global flag. Each call writes it and run_interpreter() reads it later, with no lock. With the GIL this is safe, because nothing releases the GIL between the write and the read. On free-threaded builds, though, a concurrent call on another object can reset it in between. A reduction could then end up in the parallel path, which does not support reductions. This falls outside this PR's scope; it belongs to the same family as the set_num_threads() race (Lock the set_num_threads() to prevent dead-locks in parallel environments #572). Making it a local variable passed down to run_interpreter() would fix it.

Apart from point 2, which I'd suggest addressing here, I think this is ready to merge once the CI on the fork has been approved and runs green, including 3.14t.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Heap corruption when a compiled NumExpr object is called from several threads with NUMEXPR_NUM_THREADS=1

3 participants