Skip to content

Graceful shutdown takes ~29 s when the kernel has a multiprocessing resource tracker child (default on Python 3.14) #1601

Backlog

Description

@mdealencar

Description

A kernel that has created any multiprocessing synchronization primitive while using the forkserver or spawn
start method takes ~29 s to exit after a graceful shutdown request. A multiprocessing.Lock() is enough. Python 3.14 made
forkserver the default start method on Linux, so this now happens in ordinary code. For example, tqdm creates a
multiprocessing.RLock for every progress bar, even disabled ones.

With jupyter_client's default shutdown_wait_time=5, the kernel doesn't finish exiting in time. It is sent SIGTERM
after 2.5 s (exit code -15), so atexit handlers in the kernel don't run. For example, coverage data from a kernel
measured with coverage.py's subprocess support is lost.

Reproducer

import time

from jupyter_client.manager import start_new_kernel

CASES = [
    ("x = 1", 60),
    ("import multiprocessing; lock = multiprocessing.Lock()", 60),
    ("import multiprocessing; lock = multiprocessing.Lock()", 5),  # jupyter_client's default shutdown_wait_time
]

for code, wait in CASES:
    km, kc = start_new_kernel(kernel_name="python3")
    kc.execute_interactive(code, timeout=30)
    kc.stop_channels()
    process = km.provisioner.process
    km.shutdown_wait_time = wait
    t0 = time.monotonic()
    km.shutdown_kernel(now=False)
    print(f"{code!r} (shutdown_wait_time={wait}): shutdown took {time.monotonic() - t0:.1f} s, "
          f"kernel exit code {process.returncode}", flush=True)

Output (Python 3.14.10, ipykernel 7.4.0, jupyter_client 8.10.0, psutil 7.2.2, Linux):

'x = 1' (shutdown_wait_time=60): shutdown took 0.1 s, kernel exit code 0
'import multiprocessing; lock = multiprocessing.Lock()' (shutdown_wait_time=60): shutdown took 29.3 s, kernel exit code 0
'import multiprocessing; lock = multiprocessing.Lock()' (shutdown_wait_time=5): shutdown took 2.6 s, kernel exit code -15

The same happens on Python 3.13.12 with ipykernel 7.2.0 when the start method is forkserver. There the default
fork start method creates no resource tracker for a lock:

'import multiprocessing; lock = multiprocessing.Lock()' (shutdown_wait_time=60): shutdown took 0.1 s, kernel exit code 0
"import multiprocessing; lock = multiprocessing.get_context('forkserver').Lock()" (shutdown_wait_time=60): shutdown took 29.4 s, kernel exit code 0

The same happens with from tqdm import tqdm; list(tqdm(range(3))) on Python 3.14 (29.4 s).

Cause

With the forkserver/spawn start methods, creating a SemLock registers it with multiprocessing's resource tracker. The
tracker is started as a child of the kernel (python -c "from multiprocessing.resource_tracker import main;main(fd)"),
in the kernel's process group. It ignores SIGINT and SIGTERM by design (multiprocessing/resource_tracker.py, main()).
It exits when its pipe is closed, and its parent reaps it in ResourceTracker._stop(), which runs at interpreter exit.

On a shutdown request, Kernel._at_shutdown() awaits _progressively_terminate_all_children()
(ipykernel/kernelbase.py in 7.4.0):

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

    for signum in (SIGTERM, SIGKILL):
        for delay in sleeps:
            children = self._process_children()
            if not children:
                self.log.debug("No more children, continuing shutdown routine.")
                return
            # signals only children, not current process
            self._signal_children(signum)
            ...
            await asyncio.sleep(delay)

The ~29 s are spent in this loop, in two rounds:

  1. SIGTERM round (14.44 s). The resource tracker ignores SIGTERM, so it is still listed after every sleep, and the
    whole SIGTERM schedule (sum of sleeps = 14.44 s) runs out.
  2. SIGKILL round (another 14.44 s). SIGKILL ends the tracker at once, but nothing calls waitpid on it. It
    stays a zombie, and _process_children() keeps returning it, because psutil.Process().children() includes zombies.
    So the SIGKILL schedule runs out as well. The kernel's --debug log shows the child with status='zombie' from the
    second SIGKILL onward.

Suggested fix

Two independent changes in _progressively_terminate_all_children; both are needed to get back to ~0.1 s:

  1. Stop waiting for zombies. Either filter them out of _process_children()
    (child.status() != psutil.STATUS_ZOMBIE), or wait with psutil.wait_procs(children, timeout=delay), which reaps
    direct children and returns as soon as they're gone. Dropping zombies alone (patched into the kernel) cut the
    shutdown of the tqdm example from 29.4 s to 14.8 s: only the SIGTERM round remains.
  2. Don't wait for the resource tracker to react to SIGTERM. For example, stop it the way multiprocessing does at exit,
    before signalling the remaining children. multiprocessing.resource_tracker._resource_tracker._stop() closes its
    pipe and reaps it; it's a private API, so a guarded call or an equivalent may be preferable. Calling _stop() in a
    last cell before the shutdown request brought the tqdm example down to 0.1 s. It prints a harmless "There appear to
    be N leaked semaphore objects" warning when a lock is still alive.

Workarounds for users

  • Call multiprocessing.resource_tracker._resource_tracker._stop() before shutting the kernel down (private API).
  • For tqdm specifically: tqdm.tqdm.set_lock(threading.RLock()) before the first progress bar, so that no
    multiprocessing lock and no tracker is created. This gives up tqdm's cross-process locking.
  • Give the kernel more than 30 s to exit (shutdown_wait_time). That's slow, but it lets atexit handlers run.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions