loky: fix ShutdownExecutorError race in concurrent submissions to reusable executor#632
Open
mvanhorn wants to merge 1 commit into
Open
Conversation
…sable executor Fixes joblib#458
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The fix has two parts. Both stay inside
loky/reusable_executor.py; no changes toprocess_executor.pyare needed.Part 1 - hold a stable reference under the singleton lock.
get_reusable_executor(and the underlying_ReusablePoolExecutor.get_reusable_executorclassmethod) returns the executor instance after releasing_executor_lock. Callers then invoke.submit()unprotected. We do not want to hold_executor_lockacross user submissions (that would serialize all submits across threads), but we can guarantee that the returned executor reference is one that has not yet been shut down by ensuring two invariants:executorvariable still bound in the outer scope. Audit the existing branches to confirm the recursive return value is propagated correctly. The current code already doesreturn cls.get_reusable_executor(...), so this is correct; add a comment marking the invariant.Part 2 - make
_ReusablePoolExecutor.submitshutdown-resilient.Even with Part 1, two threads can each receive what was the live executor at lock-release time, after which Thread A's shutdown-and-replace happens between Thread B's resolve and Thread B's submit. The robust fix is to detect a shutdown executor inside
_ReusablePoolExecutor.submitand retry against the current singleton:Caveats to handle in the patch:
_executor_kwargsis module-global and may itself be racing. Snapshot it under_executor_lockat the top of the retry path._global_shutdown), let the underlyingShutdownExecutorErrorpropagate so behavior at interpreter exit is unchanged._executor_kwargsisNone(post-shutdown). In that case, raise the original error.Part 3 - regression test.
Add
test_reusable_executor_submit_during_shutdown_racetotests/test_reusable_executor.py. Port the reproducer from the issue, parameterize the outer iteration count to keep CI runtime under a few seconds, and assert no future raisesShutdownExecutorError. To make the test deterministic on CI, drive the race directly: use athreading.Barrierto synchronize a "submit from thread" call with a "get_reusable_executor with different env from main thread" call so the shutdown-and-replace lands between resolve and submit. The test fails onmasterand passes after the fix.PR title:
FIX avoid ShutdownExecutorError when reusable executor is rotated concurrentlyPR body sketch:
Why this matters
Issue #458, filed by maintainer @ogrisel, reports that submitting to
get_reusable_executorconcurrently from multiple threads (e.g. via a stdlibThreadPoolExecutormap) intermittently raisesShutdownExecutorError: cannot schedule new futures after shutdown. The supplied reproducer creates a fresh reusable executor with a differentenvargument from the main thread, then immediately fans out 100 submissions across 10 threads. Because each thread'senv={"a": str(i)}differs from the cached executor kwargs, every other submission's call toget_reusable_executortriggers a shutdown-and-recreate of the singleton executor. The race is between:get_reusable_executorhaving just resolved the executor to the current singleton, then yielding before calling.submit().get_reusable_executorunder_executor_lock, deciding the kwargs differ, callingexecutor.shutdown(wait=True), replacing_executor = None, and releasing the lock..submit()on the shutdown executor, which raisesShutdownExecutorError.The traceback confirms the failing call site is
_ReusablePoolExecutor.submit->ProcessPoolExecutor.submit-> theself._flags.shutdownbranch atloky/process_executor.py:1258.Testing
New test
test_reusable_executor_submit_during_shutdown_raceintests/test_reusable_executor.py:threading.Barrier(2)shared by a worker thread (callingexecutor.submit(...)on a resolved executor) and the main thread (callingget_reusable_executor(env={"a": "X"})with kwargs differing from the resolved executor's kwargs to force shutdown-and-replace).executor = get_reusable_executor(env={"a": "1"}), waits at the barrier, then callsexecutor.submit(lambda: 1)and asserts the result is1.env={"a": "2"}, waits at the barrier (which forces the resolve-then-shutdown to happen just before the worker thread's.submit), and asserts no exception.ShutdownExecutorError(verified by reverting just thesubmitpatch and running the test in a loop).Original reproducer from the issue runs cleanly through 10 outer iterations: copy the reproducer into the test file, gated by a slow marker if needed (
@pytest.mark.skipif(os.environ.get("CI"))is not appropriate since maintainers want CI to catch regressions; if runtime is a concern, scalerange(10)torange(2)).Existing
tests/test_reusable_executor.pysuite still passes (pytest tests/test_reusable_executor.py -v). Pay particular attention totest_reusable_executor_thread_safety(added in PR [MRG] add a new test: test_reusable_executor_thread_safety #116) to confirm no regression.pytest tests/ -v -k "not (slow or psutil)"passes on Python 3.11, 3.12, 3.13. (Local matrix; CI covers the rest.)Manual smoke: run the issue's exact reproducer in an
ipythonsession; expect no exception across 10 outer iterations, where pre-fix it triggers within 1-3 iterations on the maintainer's machine.Fixes #458
AI was used for assistance.