Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions ipykernel/kernelbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -1597,13 +1597,24 @@ 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:
return []

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()
Expand All @@ -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()
Expand Down
35 changes: 35 additions & 0 deletions tests/test_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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().
Expand Down
Loading