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
Stop terminal Ctrl-C from killing the kernel on Windows (#10370)
Trevor Manzd6f601470c9c
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 8435a0b8e2..bbaf3e89c6 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -512,29 +512,30 @@ def run_in_sandbox(atexit.register(cleanup_constraint_file)- # 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":+ # The console already delivers Ctrl-C to uv and the inner server;+ # forwarding CTRL_C_EVENT would rebroadcast to the whole console,+ # including ourselves (#4842). Let the inner server drive shutdown.+ signal.signal(signal.SIGINT, signal.SIG_IGN)process = subprocess.Popen(uv_cmd, env=env)else:+ # 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.process = subprocess.Popen(uv_cmd, env=env, start_new_session=True)- def handler(sig: int, frame: object) -> None:- del frame- try:- if sys.platform == "win32":- os.kill(process.pid, signal.CTRL_C_EVENT)- else:+ def handler(sig: int, frame: object) -> None:+ del frame+ try:os.killpg(process.pid, sig)- except ProcessLookupError:- # Process may have already been terminated.- pass+ except ProcessLookupError:+ # Process may have already been terminated.+ pass- signal.signal(signal.SIGINT, handler)- if sys.platform != "win32":+ signal.signal(signal.SIGINT, handler)signal.signal(signal.SIGTERM, handler)signal.signal(signal.SIGHUP, handler)diff --git a/marimo/_runtime/kernel_lifecycle.py b/marimo/_runtime/kernel_lifecycle.pyindex d452678dc8..3ea8b5665a 100644--- a/marimo/_runtime/kernel_lifecycle.py+++ b/marimo/_runtime/kernel_lifecycle.py@@ -239,8 +239,12 @@ async def listen_messages(while True:try:request = await get_request(control_queue)+ except InterruptedError:+ # Windows: SIGINT can abort a blocking queue read with EINTR;+ # the interrupt is handled by the signal handler, keep reading.+ continueexcept Exception as e:- # triggered on Windows when quit with Ctrl+C+ # e.g. the queue's pipe was torn down by server shutdownLOGGER.debug("kernel queue.get() failed %s", e)returndiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 9b8cec8d33..5cb0d1c23d 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -142,7 +142,10 @@ from marimo._runtime.runner.hooks import ()from marimo._runtime.scratch import SCRATCH_CELL_IDfrom marimo._runtime.state import State-from marimo._runtime.win32_interrupt_handler import Win32InterruptHandler+from marimo._runtime.win32_interrupt_handler import (+ Win32InterruptHandler,+ ignore_console_ctrl_c,+)from marimo._secrets.load_dotenv import (load_dotenv_with_fallback,)@@ -2503,6 +2506,8 @@ def _bootstrap_subprocess(if sys.platform != "win32":os.setsid()start_parent_poller(parent_pid)+ else:+ ignore_console_ctrl_c()# The runtime process inherits the server's loop policy. On Windows, we# restore the event loop policy to the default ProactorEventLoop, sodiff --git a/marimo/_runtime/win32_interrupt_handler.py b/marimo/_runtime/win32_interrupt_handler.pyindex af12dc0ffe..540adb82d0 100644--- a/marimo/_runtime/win32_interrupt_handler.py+++ b/marimo/_runtime/win32_interrupt_handler.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport queueimport signal+import sysimport threadingfrom _thread import interrupt_mainfrom typing import TYPE_CHECKING@@ -11,6 +12,22 @@ if TYPE_CHECKING:from marimo._session.queue import QueueType+def ignore_console_ctrl_c() -> None:+ """Stop the Windows console from delivering Ctrl-C to this process.++ Terminal Ctrl-C belongs to the server; the kernel is interrupted via+ `Win32InterruptHandler` -> `interrupt_main()`, which still works after+ this (unlike `SIG_IGN`). See+ https://github.com/marimo-team/marimo/issues/4842.+ """+ if sys.platform != "win32":+ return+ import ctypes++ # Fails only if no console is attached, which is fine.+ ctypes.windll.kernel32.SetConsoleCtrlHandler(None, True)++class Win32InterruptHandler(threading.Thread):def __init__(self, interrupt_queue: QueueType[bool]) -> None:super().__init__()diff --git a/tests/_runtime/test_interrupt_handlers.py b/tests/_runtime/test_interrupt_handlers.pyindex 2f9436c4db..6e4bfee3e7 100644--- a/tests/_runtime/test_interrupt_handlers.py+++ b/tests/_runtime/test_interrupt_handlers.py@@ -156,3 +156,32 @@ def test_sigint_with_no_scheduler_and_no_cell_is_noop() -> None:interrupt_handler = construct_interrupt_handler()# No exception raised.interrupt_handler(signal.SIGINT, None)+++def test_ignore_console_ctrl_c_keeps_interrupt_main_working() -> None:+ """`interrupt_main()` (the deliberate interrupt path) must still fire+ the SIGINT handler after `ignore_console_ctrl_c()`. Runs in a+ subprocess to leave the test runner's console handling untouched."""+ import subprocess+ import sys+ import textwrap++ script = textwrap.dedent(+ """+ import signal, sys, threading, _thread+ from marimo._runtime.win32_interrupt_handler import (+ ignore_console_ctrl_c,+ )++ fired = threading.Event()+ signal.signal(signal.SIGINT, lambda *args: fired.set())+ ignore_console_ctrl_c()+ threading.Timer(0.1, _thread.interrupt_main).start()+ fired.wait(5)+ sys.exit(0 if fired.is_set() else 1)+ """+ )+ completed = subprocess.run(+ [sys.executable, "-c", script], timeout=30, capture_output=True+ )+ assert completed.returncode == 0, completed.stderr.decode()diff --git a/tests/_runtime/test_kernel_lifecycle.py b/tests/_runtime/test_kernel_lifecycle.pyindex 9b488f4c93..4a1a4082ba 100644--- a/tests/_runtime/test_kernel_lifecycle.py+++ b/tests/_runtime/test_kernel_lifecycle.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport asyncioimport queue as _queueimport threading-from typing import Any+from typing import TYPE_CHECKING, Anyfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -28,6 +28,9 @@ from marimo._runtime.kernel_lifecycle import ()from marimo._types.ids import CellId_t, UIElementId, WidgetModelId+if TYPE_CHECKING:+ from collections.abc import Iterator+@pytest.fixturedef kernel() -> Any:@@ -162,6 +165,35 @@ async def test_listen_messages_exits_when_reader_raises(kernel.handle_message.assert_not_called()+async def test_listen_messages_survives_interrupted_read(+ kernel: Any,+ control: asyncio.Queue[Any],+ ui: asyncio.Queue[Any],+) -> None:+ """A SIGINT-aborted queue read (EINTR) must not stop the control+ loop."""+ cmd = _execute()+ reads: Iterator[CommandMessage | BaseException] = iter(+ [+ InterruptedError(4, "Interrupted function call"),+ cmd,+ StopKernelCommand(),+ ]+ )++ async def interrupted_reader(_queue: object) -> CommandMessage:+ result = next(reads)+ if isinstance(result, BaseException):+ raise result+ return result++ await listen_messages(kernel, control, ui, interrupted_reader)++ # The dispatch after the EINTR proves the loop kept reading.+ assert kernel.handle_message.await_count == 1+ assert kernel.handle_message.await_args.args == (cmd,)++async def test_listen_messages_merges_ui_updates(kernel: Any,control: asyncio.Queue[Any],