Skip to content

Fixes #220: Change worker exception to BaseException - #221

Open
dxdc wants to merge 1 commit into
uqfoundation:masterfrom
dxdc:patch-1
Open

dxdc wants to merge 1 commit into
uqfoundation:masterfrom
dxdc:patch-1

Conversation

@dxdc

@dxdc dxdc commented May 5, 2025 •

Copy link
Copy Markdown

Summary

Fixes #220

A task that raises SystemExit or KeyboardInterrupt (for example from a SIGTERM handler, as in #220) kills its pool worker before any result is sent back, so the caller waits forever on the lost task.

The worker now catches BaseException and sends it back like any other exception. In a worker process, SystemExit/KeyboardInterrupt is then re-raised, so the worker still exits as before and the pool replaces it. Keeping the worker alive instead (as ProcessPoolExecutor does) would make Pool.terminate() hang on a busy worker that turns SIGTERM into SystemExit. ThreadPool threads just report the exception, since the pool doesn't notice a worker thread exiting.

Applied to py3.10-3.15 and pypy3.10-3.12, with tests in each version's _TestPoolWorkerErrors. The full suite passes on 3.11, 3.12 and 3.13 with fork, spawn and forkserver.

Checklist

Documentation and Tests

  • Added relevant tests that run with python tests/__main__.py, and pass.
  • Artifacts produced with the main branch work as expected under this PR.

Release Management

  • Added "Fixes #NNN" in the PR body, referencing the issue (#NNN) it closes.
  • Added a comment to issue #NNN, linking back to this PR.
  • Requested a review.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_015WHEYyvQhEKEYvBtjyfiNr

Checklist

Documentation and Tests

  • Added relevant tests that run with python tests/__main__.py, and pass.
  • Added relevant documentation that builds in sphinx without error.
  • Added new features that are documented with examples.
  • Artifacts produced with the main branch work as expected under this PR.

Release Management

  • Added "Fixes #NNN" in the PR body, referencing the issue (#NNN) it closes.
  • Added a comment to issue #NNN, linking back to this PR.
  • Added rationale for any breakage of backwards compatibility.
  • Requested a review.

@mmckerns

mmckerns commented May 7, 2025

Copy link
Copy Markdown
Member

The code mirrors the stdlib multiprocessing, so there's a "directory" for each major version of python (and also pypy), with a fork of multiprocessing in each from the corresponding version. You edited py3.11, which is the fork for python 3.11. So, often an edit needs to be duplicated across a few versions of python (i.e. directories). Since the code is forked, the tests are also forked... so for python 3.11, the tests are at py3.11/multiprocess/tests

@dxdc

dxdc commented May 7, 2025

Copy link
Copy Markdown
Author

@mmckerns ok thanks. I'm not sure how to get the tests to pass, as I'm not very familiar with this library. but these tests definitely seem to hang.

    def test_map_sigterm_base_exception(self):
        def _sigterm_worker(x):
            def _handler(signum, frame):
                raise SystemExit(f"worker received SIGTERM on input={x}")
        
            signal.signal(signal.SIGTERM, _handler)
            os.kill(os.getpid(), signal.SIGTERM)

        try:
            self.pool.map_async(_sigterm_worker, list(range(3))).get(timeout=SHUTDOWN_TIMEOUT)
        except multiprocessing.TimeoutError:
            self.fail("pool.map_async with sigterm stalled on base exception")

    def test_imap_sigterm_base_exception(self):
        def _sigterm_worker(x):
            def _handler(signum, frame):
                raise SystemExit(f"worker received SIGTERM on input={x}")
        
            signal.signal(signal.SIGTERM, _handler)
            os.kill(os.getpid(), signal.SIGTERM)

        try:
            for _ in self.pool.imap(_sigterm_worker, list(range(3))):
                pass
        except multiprocessing.TimeoutError:
            self.fail("pool.map_async with sigterm stalled on base exception")


@dxdc

dxdc commented Aug 15, 2025 •

Copy link
Copy Markdown
Author

@mmckerns any chance you could review this again? I made the other changes

@dxdc

dxdc commented Dec 21, 2025

Copy link
Copy Markdown
Author

@mmckerns just bumping this in case it got buried — whenever you have a chance, I’d appreciate another look. Thanks!

@mmckerns

Copy link
Copy Markdown
Member

@dxdc: If you look at the current version of multiprocess for python 3.13 (for example), and grep the main directory for Exception and BaseException, you'll find Exception used about 35 times and BaseException used only twice (in managers.py). The same code is found in multiprocessing (e.g. the bug/feature is also in multiprocessing). I'm not seeing any of the tests passing in your PR, and you comment that "I'm not sure how to get the tests to pass". Are you saying that your changes now cause some of the tests to fail, and you are not sure how to modify the tests so they pass?

…n#220)

A task that raised SystemExit or KeyboardInterrupt (e.g. from a SIGTERM
handler) killed its worker before any result was sent back, so the
caller waited forever on the lost task.

The worker now catches BaseException and sends it back like any other
exception. In a worker process, SystemExit/KeyboardInterrupt is then
re-raised so the worker still exits as before and the pool replaces it.
Keeping the worker alive instead (as ProcessPoolExecutor does) would
leave a busy worker that turns SIGTERM into SystemExit unable to be
stopped by Pool.terminate(). ThreadPool threads just report the
exception, since the pool does not notice a worker thread exiting.

Applied to py3.10-3.15 and pypy3.10-3.12, with tests added to each
version's _TestPoolWorkerErrors.

Fixes uqfoundation#220
@dxdc

dxdc commented Oct 13, 2026

Copy link
Copy Markdown
Author

@mmckerns thanks, that makes sense. I've rebased onto current master and applied the change to every version directory there now (py3.10-3.15 and pypy3.10-3.12, py3.9 dropped since master no longer has it), with tests added to each version's _TestPoolWorkerErrors.

I also changed the fix itself.

Just catching BaseException and carrying on (which is what ProcessPoolExecutor does) fixes the lost result, but the worker then swallows SystemExit, and that causes a new hang: if a worker has a SIGTERM handler that raises SystemExit (the pattern from #220) and is busy when pool.terminate() runs, it catches the exit, goes back for more work and blocks on the queue lock that terminate is holding, so terminate never returns.

So now the worker sends the exception back and then re-raises it, i.e. it exits exactly as it did before and the pool replaces it, the only difference being that the caller gets the error instead of waiting forever. ThreadPool threads just report it and keep going, since the pool doesn't notice a worker thread exiting.

I ran the full suite on 3.11, 3.12 and 3.13 with fork, spawn and forkserver, and ran the new tests several hundred times under load to make sure they aren't flaky. If you'd rather keep this as close to the stdlib as possible I'm happy to trim it back to the one-line change, though the terminate() hang above is the tradeoff.

@mmckerns

mmckerns commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

@dxdc thanks for the follow-up. I think, as this is really a python stdlib bug, that you should probably also submit a PR there. That way, both libraries stay in sync as much as possible -- although it would get applied in multiprocess in versions where it doesn't in the stdlib. Also, I'd prefer the tests you added be as close to the bottom of tests/__init__.py as possible (that makes it easier to merge in new changes from the stdlib).

@dxdc

dxdc commented Oct 19, 2026

Copy link
Copy Markdown
Author

Makes sense, I'll open an issue on CPython and put up a PR there with the same change, and link both back here. I checked and the stdlib hangs the same way on 3.11-3.13 with both fork and spawn, so it's definitely upstream too.

One thought: Pool robustness fixes have historically moved pretty slowly in CPython (python/cpython#66587 has been open since 2014), so if it's ok with you I'd suggest not blocking this one on it. If CPython ends up wanting a different shape for the fix, I'll update this PR to match so the two stay in sync.

@mmckerns

Copy link
Copy Markdown
Member

I wasn't suggesting waiting to merge here until after upstream merges. However, I definitely think you should report upstream -- and we can wait a slight bit to see of there's some comments about rationale and/or preferred fixes and/or tag classification.

@dxdc

dxdc commented Oct 21, 2026

Copy link
Copy Markdown
Author

posted here: python/cpython#160029

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.

Worker process hangs when SystemExit Exception is raised

2 participants