A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: kill kernel's process group on shutdown (#9257)
Akshay Agrawal2c8e548bd872
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex c34da87249..cb2d6dd5b1 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -444,24 +444,37 @@ def run_in_sandbox(env = os.environ.copy()env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"+ # Let the inner marimo server poll for our PID so it can shut down if we+ # get SIGKILLed (signal handlers below can't catch uncatchable signals).+ env["MARIMO_ANCESTOR_PID"] = str(os.getpid())if extra_env:env.update(extra_env)- process = subprocess.Popen(uv_cmd, env=env)+ # On Unix, run `uv` in its own session so that (a) the tty no longer+ # delivers SIGINT/SIGTERM to it directly and (b) we can signal the whole+ # subtree with a single killpg. The signal handlers below are then the+ # sole path for forwarding signals from the CLI down to uv, the inner+ # marimo server, and the kernel.+ if sys.platform == "win32":+ process = subprocess.Popen(uv_cmd, env=env)+ else:+ process = subprocess.Popen(uv_cmd, env=env, start_new_session=True)def handler(sig: int, frame: object) -> None:- del sigdel frametry:if sys.platform == "win32":os.kill(process.pid, signal.CTRL_C_EVENT)else:- os.kill(process.pid, signal.SIGINT)+ os.killpg(process.pid, sig)except ProcessLookupError:# Process may have already been terminated.passsignal.signal(signal.SIGINT, handler)+ if sys.platform != "win32":+ signal.signal(signal.SIGTERM, handler)+ signal.signal(signal.SIGHUP, handler)return process.wait()diff --git a/marimo/_ipc/launch_kernel.py b/marimo/_ipc/launch_kernel.pyindex 1746106a71..67bac4aaac 100644--- a/marimo/_ipc/launch_kernel.py+++ b/marimo/_ipc/launch_kernel.py@@ -52,6 +52,7 @@ def main() -> None:is_edit_mode=not args.is_run_mode,is_ipc=True,redirect_console_to_browser=args.redirect_console_to_browser,+ parent_pid=args.parent_pid,)diff --git a/marimo/_ipc/types.py b/marimo/_ipc/types.pyindex 742620a1a3..cfb5b609ce 100644--- a/marimo/_ipc/types.py+++ b/marimo/_ipc/types.py@@ -38,6 +38,7 @@ class KernelArgs(msgspec.Struct):# virtual_files_supported is ignored, but kept for backward compatibilityvirtual_files_supported: bool = Trueredirect_console_to_browser: bool = True+ parent_pid: int | None = Nonedef encode_json(self) -> bytes:return encode_json_bytes(self)diff --git a/marimo/_runtime/parent_poller.py b/marimo/_runtime/parent_poller.pynew file mode 100644index 0000000000..04e30ce801--- /dev/null+++ b/marimo/_runtime/parent_poller.py@@ -0,0 +1,112 @@+# Copyright 2026 Marimo. All rights reserved.+"""Poll another process and exit when that process exits.++Ported from ipykernel.parentpoller (BSD-licensed) to avoid orphaned kernel+processes when the marimo server is killed ungracefully (e.g. SIGKILL, OOM).+Without this, a crashed server can leave the kernel and its children running+forever.+"""++from __future__ import annotations++import os+import signal+import sys+import time+from threading import Thread++from marimo import _loggers++LOGGER = _loggers.marimo_logger()+++class ParentPollerUnix(Thread):+ """Daemon thread that kills the process group when the parent has died.++ Two independent death-detection mechanisms:++ - `parent_pid`: watches the *direct* parent. When the direct parent exits,+ the OS reparents us (getppid becomes 1 or some other PID), which we can+ observe.++ - `ancestor_pid`: watches a non-parent PID.+ """++ def __init__(+ self,+ parent_pid: int,+ ancestor_pid: int | None = None,+ ) -> None:+ super().__init__(daemon=True)+ self.parent_pid = parent_pid+ self.ancestor_pid = ancestor_pid++ def _handle_parent_death(self) -> None:+ LOGGER.warning("Parent server appears to have exited, shutting down.")++ try:+ os.killpg(os.getpgrp(), signal.SIGKILL)+ except ProcessLookupError:+ pass+ except OSError:+ LOGGER.debug(+ "Failed to kill kernel process group; exiting current process.",+ exc_info=True,+ )+ os._exit(1)++ def _ancestor_is_gone(self) -> bool:+ if self.ancestor_pid is None or self.ancestor_pid <= 1:+ return False+ try:+ os.kill(self.ancestor_pid, 0)+ except ProcessLookupError:+ return True+ except PermissionError:+ # Ancestor exists but we no longer have permission to signal it+ # (e.g. PID reused by an unrelated user's process). Treat as gone.+ return True+ return False++ def run(self) -> None:+ from errno import EINTR++ # If the passed-in parent pid doesn't match our actual ppid,+ # fall back to detecting reparenting to init (ppid == 1).+ if os.getppid() != self.parent_pid:+ self.parent_pid = 0++ while True:+ try:+ ppid = os.getppid()+ parent_is_init = not self.parent_pid and ppid == 1+ parent_has_changed = (+ self.parent_pid and ppid != self.parent_pid+ )+ if (+ parent_is_init+ or parent_has_changed+ or self._ancestor_is_gone()+ ):+ self._handle_parent_death()+ return+ time.sleep(1.0)+ except OSError as e:+ if e.errno == EINTR:+ continue+ raise+++def start_parent_poller(+ parent_pid: int | None,+ ancestor_pid: int | None = None,+) -> None:+ """Start a parent poller when the current Unix subprocess has a parent.++ Returns `None` when parent polling is not applicable, such as when+ running on Windows or when reparenting to PID 1 is expected.+ """+ if sys.platform == "win32" or parent_pid is None or parent_pid == 1:+ return++ ParentPollerUnix(parent_pid=parent_pid, ancestor_pid=ancestor_pid).start()diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 37416f2dc8..163c3e4719 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -182,6 +182,9 @@ from marimo._runtime.packages.utils import (is_python_isolated,)from marimo._runtime.params import CLIArgs, QueryParams+from marimo._runtime.parent_poller import (+ start_parent_poller,+)from marimo._runtime.redirect_streams import redirect_streamsfrom marimo._runtime.reload.autoreload import ModuleReloaderfrom marimo._runtime.reload.module_watcher import ModuleWatcher@@ -3554,21 +3557,25 @@ def launch_kernel(profile_path: str | None = None,log_level: int | None = None,is_ipc: bool = False,+ parent_pid: int | None = None,) -> None:if log_level is not None:_loggers.set_level(log_level)LOGGER.debug("Launching kernel")- # Determine behavior:- # - is_subprocess: edit mode uses Process, IPC uses subprocess - both can receive signals- # - Run mode (not edit) uses autorun config regardless of IPCis_subprocess = is_edit_mode or is_ipc-loop_factory: Callable[[], asyncio.AbstractEventLoop] | None = Noneif is_subprocess:restore_signals()- # The runtime process inherits the server's loop policy, on Windows, we+ # Become the leader of a new session/process group before connecting+ # back to the parent, to avoid race conditions with the parent+ # process (which assumes its child is in another process group).+ if sys.platform != "win32":+ os.setsid()+ start_parent_poller(parent_pid)++ # The runtime process inherits the server's loop policy. On Windows, we# restore the event loop policy to the default ProactorEventLoop, so# user code can use asyncio.create_subprocess_exec and other APIs that# the SelectorEventLoop does not implement.@@ -3720,17 +3727,10 @@ def launch_kernel(# Subprocess kernels (EDIT and IPC_RUN) can receive signals and need# their own formatter registration since they don't share state with# the host process.+ #+ # Each subprocess kernel needs to install the formatter import hooksfrom marimo._output.formatters.formatters import register_formatters- # TODO: Windows workaround -- find a way to make the process- # its group leader- if sys.platform != "win32":- # Make this process group leader to prevent it from receiving- # signals intended for the parent (server) process,- # Ctrl+C in particular.- os.setsid()-- # Each subprocess kernel needs to install the formatter import hooksregister_formatters(theme=user_config["display"]["theme"])signal.signal(signal.SIGINT, handlers.construct_interrupt_handler(ctx))diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex a7d2370d4c..16b30a66dc 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -27,6 +27,7 @@ from marimo._server.tokens import AuthTokenfrom marimo._server.utils import initialize_mimetypesfrom marimo._server.uvicorn_utils import close_uvicornfrom marimo._session.model import SessionMode+from marimo._utils.subprocess import cancel_pending_reapsif TYPE_CHECKING:from collections.abc import AsyncIterator@@ -259,6 +260,13 @@ async def etc(app: Starlette) -> AsyncIterator[None]:yield+async def reap_subprocesses(app: Starlette) -> AsyncIterator[None]:+ del app+ yield+ await cancel_pending_reaps()++def _pretty_host(host: str, port: int) -> str:"""Replace loopback addresses with 'localhost' for display.diff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex 80e43b958a..96129f1103 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -17,6 +17,7 @@ from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._mcp.setup import McpType, setup_mcp_serverfrom marimo._messaging.notification import StartupLogsNotificationfrom marimo._runtime.commands import SerializedCLIArgs+from marimo._runtime.parent_poller import start_parent_pollerfrom marimo._server.api import lifespansfrom marimo._server.config import (StarletteServerStateInit,@@ -212,6 +213,20 @@ def start("""import packaging.version+ # In single-file sandbox mode, uv becomes our direct parent. So we+ # watch the outer CLI's PID, terminating if the CLI terminates.+ ancestor_pid_env = os.environ.get("MARIMO_ANCESTOR_PID")+ if ancestor_pid_env:+ try:+ start_parent_poller(+ parent_pid=os.getppid(),+ ancestor_pid=int(ancestor_pid_env),+ )+ except ValueError:+ LOGGER.warning(+ "Ignoring invalid MARIMO_ANCESTOR_PID=%r", ancestor_pid_env+ )+# Defaults when mcp is enabledif mcp:# Turn on watch mode@@ -313,6 +328,7 @@ def start(lifespans.open_browser,lifespans.tool_manager,lifespans.server_registry,+ lifespans.reap_subprocesses,*LIFESPAN_REGISTRY.get_all(),]diff --git a/marimo/_session/app_host/commands.py b/marimo/_session/app_host/commands.pyindex 2f0f338de0..cf64fcfc54 100644--- a/marimo/_session/app_host/commands.py+++ b/marimo/_session/app_host/commands.py@@ -93,6 +93,7 @@ class AppHostArgs(msgspec.Struct):# Notebook file path, for debug logsfile_path: strlog_level: int+ parent_pid: int | Nonedef encode_json(self) -> bytes:return msgspec.json.encode(self)diff --git a/marimo/_session/app_host/connection.py b/marimo/_session/app_host/connection.pyindex 599900fde2..93eac8ae22 100644--- a/marimo/_session/app_host/connection.py+++ b/marimo/_session/app_host/connection.py@@ -4,6 +4,7 @@from __future__ import annotationsimport dataclasses+import osfrom typing import TYPE_CHECKINGfrom marimo._config.settings import GLOBAL_SETTINGS@@ -74,6 +75,7 @@ class AppHostConnection:stream_addr=f"{_BIND_ADDR}:{stream_port}",file_path=file_path,log_level=log_level,+ parent_pid=os.getpid(),)return conn, argsdiff --git a/marimo/_session/app_host/host.py b/marimo/_session/app_host/host.pyindex af29e88f3d..6190a4031c 100644--- a/marimo/_session/app_host/host.py+++ b/marimo/_session/app_host/host.py@@ -7,7 +7,7 @@ import pickleimport subprocessimport sysimport threading-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, castfrom marimo import _loggersfrom marimo._messaging.types import KernelMessage@@ -23,6 +23,8 @@ from marimo._session.app_host.commands import (encode_mgmt_command,)from marimo._session.app_host.connection import AppHostConnection+from marimo._session.queue import ProcessLike+from marimo._utils.subprocess import try_kill_process_and_groupif TYPE_CHECKING:import queue@@ -358,13 +360,11 @@ class AppHost:if self._process is not None:try:- self._process.wait(timeout=5)- except subprocess.TimeoutExpired:- self._process.terminate()- try:- self._process.wait(timeout=2)- except subprocess.TimeoutExpired:- self._process.kill()+ try_kill_process_and_group(cast(ProcessLike, self._process))+ except ProcessLookupError:+ pass+ except Exception as e:+ LOGGER.warning(e)# Close all sockets (with linger=0). This interrupts any# pending poll()/recv() in _stream_receiver_loop with ETERM,diff --git a/marimo/_session/app_host/main.py b/marimo/_session/app_host/main.pyindex 17cfee0640..4a4a721da4 100644--- a/marimo/_session/app_host/main.py+++ b/marimo/_session/app_host/main.py@@ -21,6 +21,7 @@ from marimo._messaging.thread_local_streams import install_thread_local_proxiesfrom marimo._output.formatters.formatters import register_formattersfrom marimo._runtime import runtimefrom marimo._runtime.commands import StopKernelCommand+from marimo._runtime.parent_poller import start_parent_pollerfrom marimo._session.app_host.commands import (AppHostArgs,AppHostReadyResponse,@@ -247,6 +248,10 @@ def app_host_main(args: AppHostArgs) -> None:# and sends ShutdownAppHostCmd via the management channel.signal.signal(signal.SIGINT, signal.SIG_IGN)+ if sys.platform != "win32":+ os.setsid()+ start_parent_poller(args.parent_pid)+_loggers.set_level(args.log_level)LOGGER.debug("App host started for %s (pid=%d)", args.file_path, os.getpid()diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.pyindex fbad9089f9..69c8d0d664 100644--- a/marimo/_session/managers/ipc.py+++ b/marimo/_session/managers/ipc.py@@ -35,6 +35,7 @@ from marimo._session._venv import (from marimo._session.model import SessionModefrom marimo._session.queue import ProcessLike, QueueType, route_control_requestfrom marimo._session.types import KernelManager, QueueManager+from marimo._utils.subprocess import try_kill_process_and_groupfrom marimo._utils.typed_connection import TypedConnectionif TYPE_CHECKING:@@ -216,6 +217,7 @@ class IPCKernelManagerImpl(KernelManager):connection_info=self.connection_info,is_run_mode=self.mode == SessionMode.RUN,redirect_console_to_browser=self.redirect_console_to_browser,+ parent_pid=os.getpid(),)venv_config = _get_venv_config(self.config_manager)@@ -395,14 +397,13 @@ class IPCKernelManagerImpl(KernelManager):commands.StopKernelCommand())self.queue_manager.close_queues()-- # Terminate process if still alive- if self._process.poll() is None:- self._process.terminate()+ if self._process.poll() is None and self.kernel_task is not None:try:- self._process.wait(timeout=5)- except subprocess.TimeoutExpired:- self._process.kill()+ try_kill_process_and_group(self.kernel_task)+ except ProcessLookupError:+ pass+ except Exception as e:+ LOGGER.warning(e)# Always attempt cleanup, even if _process is Nonecleanup_sandbox_dir(self._sandbox_dir)diff --git a/marimo/_session/managers/kernel.py b/marimo/_session/managers/kernel.pyindex cdc8beb744..7da4397c3f 100644--- a/marimo/_session/managers/kernel.py+++ b/marimo/_session/managers/kernel.py@@ -21,6 +21,7 @@ from marimo._session.model import SessionModefrom marimo._session.queue import ProcessLikefrom marimo._session.types import KernelManager, QueueManagerfrom marimo._utils.print import print_+from marimo._utils.subprocess import try_kill_process_and_groupfrom marimo._utils.typed_connection import TypedConnectionif TYPE_CHECKING:@@ -91,6 +92,10 @@ class KernelManagerImpl(KernelManager):self.queue_manager.win32_interrupt_queue,self.profile_path,GLOBAL_SETTINGS.LOG_LEVEL,+ # is_ipc+ False,+ # PID+ os.getpid(),),# The process can't be a daemon, because daemonic processes# can't create children@@ -249,28 +254,33 @@ class KernelManagerImpl(KernelManager):self.queue_manager.put_control_request(commands.StopKernelCommand())- else:- # otherwise we have something that is `ProcessLike`- if self.profile_path is not None and self.kernel_task.is_alive():- self.queue_manager.put_control_request(- commands.StopKernelCommand()- )- # Hack: Wait for kernel to exit and write out profile;- # joining the process hangs, but not sure why.- print_(- "\tWriting profile statistics to",- self.profile_path,- " ...",- )- while not os.path.exists(self.profile_path):- time.sleep(0.1)- time.sleep(1)+ return- self.queue_manager.close_queues()- if self.kernel_task.is_alive():- self.kernel_task.terminate()- if self._read_conn is not None:- self._read_conn.close()+ # Otherwise, we have something that is `ProcessLike`+ if self.profile_path is not None and self.kernel_task.is_alive():+ self.queue_manager.put_control_request(+ commands.StopKernelCommand()+ )+ # Hack: Wait for kernel to exit and write out profile;+ # joining the process hangs, but not sure why.+ print_(+ "\tWriting profile statistics to",+ self.profile_path,+ " ...",+ )+ while not os.path.exists(self.profile_path):+ time.sleep(0.1)+ time.sleep(1)++ self.queue_manager.close_queues()+ try:+ try_kill_process_and_group(self.kernel_task)+ except ProcessLookupError:+ pass+ except Exception as e:+ LOGGER.warning(e)+ if self._read_conn is not None:+ self._read_conn.close()@propertydef kernel_connection(self) -> TypedConnection[KernelMessage]:diff --git a/marimo/_smoke_tests/process_group.py b/marimo/_smoke_tests/process_group.pynew file mode 100644index 0000000000..4bf94559a3--- /dev/null+++ b/marimo/_smoke_tests/process_group.py@@ -0,0 +1,24 @@+import marimo++__generated_with = "0.23.1"+app = marimo.App()+++def _():+ import subprocess++ subprocess.Popen(["sleep", "1000"])+ return+++def _():+ import os++ os.system('ps -ef | grep sleep')+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_utils/subprocess.py b/marimo/_utils/subprocess.pyindex 0384207d1e..8bd47dec88 100644--- a/marimo/_utils/subprocess.py+++ b/marimo/_utils/subprocess.py@@ -1,6 +1,9 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import asyncio+import os+import signalimport subprocessfrom collections.abc import Callable, Mapping, Sequencefrom typing import (@@ -11,6 +14,8 @@ from typing import ()from marimo import _loggers+from marimo._session.queue import ProcessLike+from marimo._utils.platform import is_windowsLOGGER = _loggers.marimo_logger()@@ -271,3 +276,108 @@ def safe_popen(except Exception as e:LOGGER.error("Failed to create subprocess for command %s: %s", args, e)return None+++_REAP_TASKS: set[asyncio.Task[None]] = set()+++def _process_finished(process: ProcessLike) -> bool:+ """Return whether the process has finished without blocking."""+ # NB: It is not safe to call os.waitpid() directly because+ # apparently Popen.poll() and multiprcoessing.Process.is_alive()+ # assume that they are the ones that reap zombie processes.+ poll = getattr(process, "poll", None)+ if poll is not None:+ return poll() is not None+ return not process.is_alive()+++async def cancel_pending_reaps() -> None:+ """Cancel and await any in-flight reap tasks.++ Call from a server shutdown hook so asyncio doesn't emit+ "Task was destroyed but it is pending" when the loop closes.+ """+ tasks = list(_REAP_TASKS)+ for t in tasks:+ t.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+++async def _reap_process_unix(process: ProcessLike, pgid: int | None) -> None:+ pid = process.pid+ await asyncio.sleep(5.0)+ if _process_finished(process):+ return++ LOGGER.warning(+ "Process %s did not respond to SIGTERM. Force killing.", pid+ )+ try:+ if pgid is not None:+ os.killpg(pgid, signal.SIGKILL)+ elif pid is not None:+ os.kill(pid, signal.SIGKILL)+ except ProcessLookupError:+ return++ wait_for_s = 10+ waited_s = 0+ while (+ not (process_finished := _process_finished(process))+ and waited_s < wait_for_s+ ):+ await asyncio.sleep(1.0)+ waited_s += 1++ if not process_finished:+ LOGGER.warning(+ "Waited for 10s, but process %s has still not quit ...", pid+ )+ return+++def try_kill_process_and_group(process: ProcessLike) -> None:+ """Attempt to kill the process group to which process belongs.++ Refuses to kill the group if it the current process belongs to it.++ Regardless, tries to kill the process.++ If running in an event loop, starts a task to reap the process on Unix-like+ systems. If not running in an event loop, it is the caller's responsibility+ to reap the process.+ """+ pid = process.pid+ if pid is None:+ return++ if is_windows():+ # TODO(akshayka): Investigate whether we need to kill an entire+ # process group on Windows, and if so how ...+ process.terminate()+ return++ pgid = os.getpgid(pid)+ target_pgid: int | None+ if pgid == os.getpgrp():+ # This should never happen ... the kernel process makes sure to+ # call setsid and become the group leader+ LOGGER.warning("The target's pgid matches the server's (%d)", pgid)+ target_pgid = None+ process.terminate()+ else:+ target_pgid = pgid+ os.killpg(pgid, signal.SIGTERM)++ if _process_finished(process):+ return++ try:+ loop = asyncio.get_running_loop()+ task = loop.create_task(_reap_process_unix(process, target_pgid))+ _REAP_TASKS.add(task)+ task.add_done_callback(_REAP_TASKS.discard)+ except RuntimeError:+ passdiff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex 3ab8b1d3d5..4a1ed1aed9 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -868,6 +868,105 @@ def test_cli_new() -> None:_check_contents(p, b'"serverToken": ', contents)+ _is_win32(),+ reason="Parent polling is Unix-only (relies on getppid/killpg)",+)+def test_cli_kernel_killed_when_server_killed() -> None:+ """Orphaned kernels should self-terminate via the parent poller."""+ import psutil+ from websockets.sync.client import connect++ port = _get_port()+ p = subprocess.Popen(+ ["marimo", "new", "-p", str(port), "--headless", "--no-token"]+ )+ try:+ assert _try_fetch(port) is not None+ # Opening a WebSocket causes the server to spawn a kernel process.+ with connect(f"ws://localhost:{port}/ws?session_id=s1"):+ server = psutil.Process(p.pid)+ deadline = time.time() + 10+ kernel_pids: list[int] = []+ while time.time() < deadline:+ kernel_pids = [c.pid for c in server.children()]+ if kernel_pids:+ break+ time.sleep(0.2)+ assert kernel_pids, "expected kernel child process to be spawned"++ # Kill only the server; the kernel's parent poller should notice.+ p.kill()+ p.wait(timeout=5)++ deadline = time.time() + 10+ while time.time() < deadline and any(+ psutil.pid_exists(pid) for pid in kernel_pids+ ):+ time.sleep(0.2)++ still_alive = [pid for pid in kernel_pids if psutil.pid_exists(pid)]+ assert not still_alive, (+ f"kernel pids {still_alive} still alive after server killed"+ )+ finally:+ with contextlib.suppress(Exception):+ p.kill()+++ _is_win32(),+ reason="Parent polling is Unix-only (relies on getppid/killpg)",+)+def test_cli_server_exits_when_ancestor_pid_dies(+ temp_marimo_file: str,+) -> None:+ """When MARIMO_ANCESTOR_PID points at a process that dies, the server's+ ancestor poller should shut the server down.++ This is the mechanism the single-file sandbox relies on to clean up the+ inner marimo (and its kernel) when the outer CLI is SIGKILLed — we can't+ exercise that end-to-end here because the sandbox's inner marimo is+ installed fresh by uv from PyPI (not the PR's source), so any changes+ under test wouldn't be present in the inner process. Testing the+ mechanism directly avoids that."""+ fake_ancestor = subprocess.Popen(["sleep", "60"])+ env = os.environ.copy()+ env["MARIMO_ANCESTOR_PID"] = str(fake_ancestor.pid)++ port = _get_port()+ # start_new_session so the poller's killpg doesn't touch pytest.+ p = subprocess.Popen(+ [+ "marimo",+ "edit",+ temp_marimo_file,+ "-p",+ str(port),+ "--headless",+ "--no-token",+ ],+ env=env,+ start_new_session=True,+ )+ try:+ assert _try_fetch(port) is not None++ fake_ancestor.kill()+ fake_ancestor.wait(timeout=5)++ # Poller ticks every 1s; give it a generous window.+ try:+ p.wait(timeout=10)+ except subprocess.TimeoutExpired:+ pytest.fail("server did not exit after ancestor died")+ finally:+ with contextlib.suppress(Exception):+ fake_ancestor.kill()+ with contextlib.suppress(Exception):+ os.killpg(os.getpgid(p.pid), signal.SIGKILL)++def test_cli_run(temp_marimo_file: str) -> None:port = _get_port()p = subprocess.Popen(diff --git a/tests/_runtime/test_parent_poller.py b/tests/_runtime/test_parent_poller.pynew file mode 100644index 0000000000..ce1aaa038e--- /dev/null+++ b/tests/_runtime/test_parent_poller.py@@ -0,0 +1,64 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import os+from unittest import mock++import pytest++from marimo._runtime.parent_poller import ParentPollerUnix++[email protected](os.name == "nt", reason="only works on posix")+def test_parent_poller_unix_reparent_to_pid1():+ poller = ParentPollerUnix(parent_pid=221)++ with (+ mock.patch("os.getppid", return_value=1),+ mock.patch("os.killpg"),+ mock.patch("os._exit", side_effect=SystemExit(1)),+ pytest.raises(SystemExit),+ ):+ poller.run()++[email protected](os.name == "nt", reason="only works on posix")+def test_parent_poller_unix_reparent_not_pid1():+ parent_pid = 221+ poller = ParentPollerUnix(parent_pid=parent_pid)++ with (+ mock.patch("os.getppid", side_effect=[parent_pid, parent_pid - 1]),+ mock.patch("os.killpg"),+ mock.patch("os._exit", side_effect=SystemExit(1)),+ pytest.raises(SystemExit),+ ):+ poller.run()++[email protected](os.name == "nt", reason="only works on posix")+def test_parent_poller_unix_propagates_getppid_error():+ poller = ParentPollerUnix(parent_pid=221)++ with (+ mock.patch("os.getppid", side_effect=ValueError("boom")),+ pytest.raises(ValueError, match="boom"),+ ):+ poller.run()++[email protected](os.name == "nt", reason="only works on posix")+def test_parent_poller_unix_ancestor_gone():+ # Direct parent alive, but ancestor is gone: ppid-based check can't+ # detect this, so the ancestor_pid probe must trigger shutdown.+ ppid = os.getppid()+ poller = ParentPollerUnix(parent_pid=ppid, ancestor_pid=4242)++ with (+ mock.patch("os.getppid", return_value=ppid),+ mock.patch("os.kill", side_effect=ProcessLookupError),+ mock.patch("os.killpg"),+ mock.patch("os._exit", side_effect=SystemExit(1)),+ pytest.raises(SystemExit),+ ):+ poller.run()diff --git a/tests/_session/app_host/test_app_host.py b/tests/_session/app_host/test_app_host.pyindex a4de6df52d..345385878b 100644--- a/tests/_session/app_host/test_app_host.py+++ b/tests/_session/app_host/test_app_host.py@@ -214,6 +214,8 @@ class TestAppHostPool:class TestAppHost:def test_start_and_shutdown(self) -> None:"""App host starts and shuts down cleanly."""+ import time+from marimo._session.app_host.host import AppHostapp_host = AppHost("/tmp/test_app.py")@@ -222,6 +224,11 @@ class TestAppHost:assert app_host.pid is not Noneapp_host.shutdown()+ # shutdown() signals the subprocess but doesn't synchronously+ # wait for it to exit, so poll briefly for the process to die.+ deadline = time.monotonic() + 5.0+ while app_host.is_alive() and time.monotonic() < deadline:+ time.sleep(0.05)assert not app_host.is_alive()diff --git a/tests/_session/managers/test_kernel.py b/tests/_session/managers/test_kernel.pynew file mode 100644index 0000000000..4dc03ef914--- /dev/null+++ b/tests/_session/managers/test_kernel.py@@ -0,0 +1,104 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import inspect+import os+import sys+import time+from typing import TYPE_CHECKING++import pytest++if TYPE_CHECKING:+ from pathlib import Path++from marimo._ast.app_config import _AppConfig+from marimo._config.manager import get_default_config_manager+from marimo._runtime.commands import (+ AppMetadata,+ CreateNotebookCommand,+ ExecuteCellCommand,+ UpdateUIElementCommand,+)+from marimo._session.managers import KernelManagerImpl, QueueManagerImpl+from marimo._session.model import SessionMode+++def _is_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ return True++[email protected](sys.platform == "win32", reason="POSIX only")+def test_close_kernel_kills_user_spawned_subprocess(tmp_path: Path) -> None:+ """A subprocess spawned by kernel-executed user code must be killed when+ the kernel is closed."""+ pid_file = tmp_path / "child.pid"++ queue_manager = QueueManagerImpl(use_multiprocessing=True)+ kernel_manager = KernelManagerImpl(+ queue_manager=queue_manager,+ mode=SessionMode.EDIT,+ configs={},+ app_metadata=AppMetadata(+ query_params={},+ filename="test.py",+ cli_args={},+ argv=None,+ app_config=_AppConfig(),+ ),+ config_manager=get_default_config_manager(current_path=None),+ virtual_file_storage="shared_memory",+ redirect_console_to_browser=False,+ )++ kernel_manager.start_kernel()+ try:+ assert kernel_manager.is_alive()++ queue_manager.control_queue.put(+ CreateNotebookCommand(+ execution_requests=(+ ExecuteCellCommand(+ cell_id="1",+ code=inspect.cleandoc(+ f"""+ import subprocess+ _proc = subprocess.Popen(["sleep", "60"])+ with open("{pid_file}", "w") as _f:+ _f.write(str(_proc.pid))+ """+ ),+ ),+ ),+ cell_ids=("1",),+ set_ui_element_value_request=UpdateUIElementCommand(+ object_ids=[], values=[]+ ),+ auto_run=True,+ )+ )++ deadline = time.monotonic() + 2+ while time.monotonic() < deadline and not pid_file.exists():+ time.sleep(0.05)+ assert pid_file.exists(), "kernel never spawned the subprocess"+ child_pid = int(pid_file.read_text())+ assert _is_alive(child_pid)+ finally:+ kernel_manager.close_kernel()++ deadline = time.monotonic() + 2.0+ while time.monotonic() < deadline and _is_alive(child_pid):+ time.sleep(0.05)+ try:+ assert not _is_alive(child_pid)+ finally:+ if _is_alive(child_pid):+ try:+ os.kill(child_pid, 9)+ except ProcessLookupError:+ passdiff --git a/tests/_utils/test_subprocess.py b/tests/_utils/test_subprocess.pyindex ae8bf5cf69..489e3173bf 100644--- a/tests/_utils/test_subprocess.py+++ b/tests/_utils/test_subprocess.py@@ -1,10 +1,24 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import asyncio+import contextlib+import os+import signalimport subprocess+import sys+import time+from typing import castfrom unittest.mock import patch-from marimo._utils.subprocess import safe_popen+import pytest++from marimo._session.queue import ProcessLike+from marimo._utils.subprocess import (+ _REAP_TASKS,+ safe_popen,+ try_kill_process_and_group,+)class TestSafePopen:@@ -64,3 +78,103 @@ class TestSafePopen:cwd="/nonexistent/directory/abc123",)assert result is None+++# Script mimics a marimo kernel / app host: calls setsid (like+# runtime.launch_kernel and app_host_main) to become its own process group+# leader, spawns two children — one in the same process group, one in a new+# session — prints their PIDs, then sleeps.+_PGROUP_LEADER_SCRIPT = """+import os, subprocess, sys, time+os.setsid()+child_pg = subprocess.Popen(+ [sys.executable, '-c', 'import time; time.sleep(15)']+)+child_newpg = subprocess.Popen(+ [sys.executable, '-c', 'import time; time.sleep(15)'],+ start_new_session=True,+)+print(child_pg.pid, child_newpg.pid, flush=True)+time.sleep(15)+"""+++def _is_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ return True++[email protected](sys.platform == "win32", reason="POSIX only")+def test_try_kill_process_and_group_kills_pgroup_spares_new_session() -> None:+ """Covers the shutdown path used by KernelManagerImpl, IPCKernelManagerImpl,+ and AppHost — all three delegate to try_kill_process_and_group.+ """+ leader = subprocess.Popen(+ [sys.executable, "-c", _PGROUP_LEADER_SCRIPT],+ stdout=subprocess.PIPE,+ text=True,+ )+ child_pg_pid = child_newpg_pid = 0+ try:+ assert leader.stdout is not None+ child_pg_pid, child_newpg_pid = (+ int(x) for x in leader.stdout.readline().split()+ )++ try_kill_process_and_group(cast(ProcessLike, leader))++ # wait() reaps the child so it doesn't linger as a zombie.+ assert leader.wait(timeout=5) is not None++ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline and _is_alive(child_pg_pid):+ time.sleep(0.05)++ assert not _is_alive(child_pg_pid)+ assert _is_alive(child_newpg_pid)+ finally:+ for pid in (leader.pid, child_pg_pid, child_newpg_pid):+ if pid:+ try:+ os.kill(pid, 9)+ except ProcessLookupError:+ pass+ leader.wait(timeout=5)++[email protected](sys.platform == "win32", reason="POSIX only")+async def test_try_kill_process_and_group_sigkills_stubborn_child(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """try_kill_process_and_group schedules a reap task that escalates to+ SIGKILL when the child ignores SIGTERM.+ """+ # Skip the reaper's real 5s/1s waits so the test is fast.+ real_sleep = asyncio.sleep++ async def no_wait(_delay: float) -> None:+ await real_sleep(0)++ monkeypatch.setattr(asyncio, "sleep", no_wait)++ script = (+ "import signal, time\n"+ "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n"+ "while True: time.sleep(1)\n"+ )+ proc = subprocess.Popen( # noqa: ASYNC220+ [sys.executable, "-c", script], start_new_session=True+ )+ pgid = os.getpgid(proc.pid)+ try:+ try_kill_process_and_group(cast(ProcessLike, proc))+ # Drain the reap task(s) scheduled on the current loop.+ await asyncio.gather(*list(_REAP_TASKS), return_exceptions=True)+ assert not _is_alive(proc.pid)+ finally:+ with contextlib.suppress(ProcessLookupError):+ os.killpg(pgid, signal.SIGKILL)