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(terminal): close pty master before reaping to avoid event-loop deadlock (#10031)
Konstantin Taletskiyaee81a867385
diff --git a/marimo/_server/api/endpoints/terminal.py b/marimo/_server/api/endpoints/terminal.pyindex 377b39e807..903845d11e 100644--- a/marimo/_server/api/endpoints/terminal.py+++ b/marimo/_server/api/endpoints/terminal.py@@ -114,6 +114,21 @@ def _create_process_cleanup_handler("""Create a cleanup handler for the child process and file descriptor."""def cleanup() -> None:+ # Close the pty master *first*.+ #+ # child_pid is the session leader of the pty. If it is killed while the+ # server still holds the master fd open -- and a foreground child (e.g.+ # a coding agent or REPL) still holds the slave -- the kernel cannot+ # finish revoking the shell's controlling terminal, so the shell never+ # becomes a reapable zombie. The blocking os.waitpid() below would then+ # hang the asyncio event loop forever (frozen server, Ctrl-C ignored).+ # Closing the master is the hangup that lets the teardown complete, so+ # the child reaps promptly.+ try:+ os.close(fd)+ except OSError:+ pass+try:# Try graceful termination firstos.kill(child_pid, signal.SIGTERM)@@ -131,12 +146,6 @@ def _create_process_cleanup_handler(except Exception as e:LOGGER.debug(f"Error during cleanup: {e}")- # Close the pty file descriptor- try:- os.close(fd)- except OSError:- pass-return cleanupdiff --git a/tests/_server/api/endpoints/test_terminal.py b/tests/_server/api/endpoints/test_terminal.pyindex 6847197c3d..4a21ed0d62 100644--- a/tests/_server/api/endpoints/test_terminal.py+++ b/tests/_server/api/endpoints/test_terminal.py@@ -325,6 +325,50 @@ class TestCreateProcessCleanupHandler:mock_close.assert_any_call(mock_fd)+ def test_cleanup_closes_master_before_blocking_waitpid(self) -> None:+ """Regression: the pty master fd must be closed BEFORE the blocking+ `os.waitpid(pid, 0)`.++ The child shell is the pty's session leader. If it is killed while the+ server still holds the master open and a foreground child keeps the+ slave open (e.g. a long-lived REPL or coding agent), the kernel cannot+ revoke the controlling terminal, the shell never becomes a reapable+ zombie, and the blocking `os.waitpid` deadlocks the asyncio event+ loop forever (frozen server, `Ctrl-C` ignored, recoverable only with+ `kill -9`). Closing the master first lets the shell be reaped, so this+ call ordering is load-bearing.+ """+ child_pid, fd = 4321, 7+ calls: list = []++ cleanup = _create_process_cleanup_handler(child_pid, fd)+ with (+ patch(+ "os.kill",+ side_effect=lambda p, s: calls.append(("kill", p, s)),+ ),+ patch(+ "os.waitpid",+ side_effect=lambda p, f: (+ calls.append(("waitpid", p, f)) or (0, 0)+ ),+ ),+ patch(+ "os.close",+ side_effect=lambda d: calls.append(("close", d)),+ ),+ ):+ cleanup()++ close_idx = next(i for i, c in enumerate(calls) if c == ("close", fd))+ blocking_wait_idx = next(+ i for i, c in enumerate(calls) if c == ("waitpid", child_pid, 0)+ )+ assert close_idx < blocking_wait_idx, (+ "os.close(fd) must run before the blocking os.waitpid(pid, 0) to "+ f"avoid the terminal-cleanup deadlock; call order was {calls}"+ )+class TestSetupChildProcess:@patch("os.chdir")