From 3be54383f54f6facdde68f22592702e1f50bb512 Mon Sep 17 00:00:00 2001 From: mokashang Date: Sat, 28 Nov 2026 09:57:26 -0800 Subject: [PATCH] Shut down promptly when the kernel has a multiprocessing resource tracker The multiprocessing resource tracker is a child process spawned the first time a synchronization primitive (Lock, Semaphore, Event, ...) is created under the ``forkserver`` or ``spawn`` start methods. Python 3.14 makes ``forkserver`` the default on Linux, so creating one of these primitives is ordinary code; ``tqdm`` builds a ``multiprocessing.RLock`` on every progress bar, for example. The tracker ignores SIGINT and SIGTERM by design and only exits when its control pipe is closed. In ``_progressively_terminate_all_children`` the SIGTERM schedule therefore runs to completion (~14 s) even though every other child has exited, and the tracker is still reported as a child by ``psutil`` after we fall through to SIGKILL (as a zombie, until the parent waitpid-s it), which stalls the SIGKILL schedule for another ~14 s. A graceful shutdown of a kernel that touched a lock then takes ~29 s, which is longer than ``jupyter_client``'s default ``shutdown_wait_time`` of 5 s, so the kernel is SIGTERM-ed mid-shutdown and ``atexit`` handlers (for example coverage.py subprocess data flush) never run. Fix both halves: * ``_progressively_terminate_all_children`` now calls ``multiprocessing.resource_tracker._resource_tracker._stop()`` before signalling children. That is the same stop that multiprocessing runs at interpreter exit; it closes the pipe and waitpid-s the tracker, so the SIGTERM round no longer waits for a process that will never react to SIGTERM. The call is guarded to be a no-op when no tracker was ever started. * ``_process_children`` filters out zombie children. Nothing in this class calls waitpid, so a zombie would otherwise keep the loop running out its schedule after the signal that killed it has already landed; init reaps them once the kernel exits. Fixes #1601 --- ipykernel/kernelbase.py | 38 ++++++++++++++++++++++++++++++++++++++ tests/test_kernel.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/ipykernel/kernelbase.py b/ipykernel/kernelbase.py index e6705cfc8..d1474be5f 100644 --- a/ipykernel/kernelbase.py +++ b/ipykernel/kernelbase.py @@ -1597,6 +1597,8 @@ def _process_children(self): Avoids: - including parents and self with killpg - including all children that may have forked-off a new group + - counting zombies as live, since they will not react to signals + and no one in this class calls waitpid on them """ psutil = _get_psutil() if psutil is None: @@ -1604,6 +1606,15 @@ def _process_children(self): kernel_process = psutil.Process() all_children = kernel_process.children(recursive=True) + alive_children = [] + for child in all_children: + try: + if child.status() == psutil.STATUS_ZOMBIE: + continue + except _NO_SUCH_PROCESS: + continue + alive_children.append(child) + all_children = alive_children if os.name == "nt": return all_children kernel_pgid = os.getpgrp() @@ -1618,12 +1629,39 @@ def _process_children(self): process_group_children.append(child) return process_group_children + def _stop_multiprocessing_resource_tracker(self): + """Stop the multiprocessing resource tracker child, if one is running. + + The tracker is spawned the first time a synchronization primitive is + created under the ``forkserver`` or ``spawn`` start methods (the + default on Linux from Python 3.14). It installs handlers that ignore + SIGINT and SIGTERM and only exits when its control pipe is closed, + so sending it signals from the shutdown loop does nothing until the + full SIGTERM schedule times out. multiprocessing itself stops the + tracker on interpreter exit by closing that pipe; doing the same thing + explicitly before we signal children lets the kernel shut down + promptly instead of waiting out the schedule. + """ + try: + from multiprocessing.resource_tracker import _resource_tracker + except ImportError: + return + try: + _resource_tracker._stop() + except Exception: + self.log.debug("Could not stop multiprocessing resource tracker", exc_info=True) + async def _progressively_terminate_all_children(self): sleeps = (0.01, 0.03, 0.1, 0.3, 1, 3, 10) if not self._process_children(): self.log.debug("Kernel has no children.") return + # The multiprocessing resource tracker ignores SIGTERM, so unless we + # stop it explicitly the SIGTERM schedule below runs to the end before + # we fall through to SIGKILL. + self._stop_multiprocessing_resource_tracker() + for signum in (SIGTERM, SIGKILL): for delay in sleeps: children = self._process_children() diff --git a/tests/test_kernel.py b/tests/test_kernel.py index 270165b1a..387c30e74 100644 --- a/tests/test_kernel.py +++ b/tests/test_kernel.py @@ -661,6 +661,41 @@ def test_shutdown(): assert not km.is_alive() +@pytest.mark.skipif( + platform.python_implementation() == "PyPy", + reason="does not work on PyPy", +) +@pytest.mark.skipif( + os.name == "nt", + reason="multiprocessing resource tracker is POSIX-only", +) +def test_shutdown_fast_with_multiprocessing_resource_tracker(): + """Graceful shutdown returns promptly after a kernel creates a multiprocessing primitive. + + Regression test for https://github.com/ipython/ipykernel/issues/1601. + Creating a synchronization primitive under the ``forkserver`` or ``spawn`` + start method spawns a resource tracker child that ignores SIGTERM. Before + the fix, the SIGTERM schedule in ``_progressively_terminate_all_children`` + would run to completion (~14s) before the shutdown could proceed, and a + zombie tracker after SIGKILL would stall the SIGKILL schedule for another + ~14s. + """ + with new_kernel() as kc: + km = kc.parent + execute( + "import multiprocessing; " + "ctx = multiprocessing.get_context('forkserver'); " + "lock = ctx.Lock()", + kc=kc, + ) + wait_for_idle(kc) + km.shutdown_wait_time = 60 + t0 = time.monotonic() + km.shutdown_kernel(now=False) + # 10s cap is a generous ceiling; without the fix shutdown takes >=14s. + assert time.monotonic() - t0 < 10 + + def test_interrupt_during_input(): """ The kernel exits after being interrupted while waiting in input().