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
Prevent SIGINT deadlock during kernel output writes (#10972)
Trevor Manzb2b7816b6dd7
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 639b56e801..96fa20373e 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -29,6 +29,7 @@ from marimo._messaging.types import ()from marimo._session.queue import QueueTypefrom marimo._types.ids import CellId_t+from marimo._utils.signals import SigintHandlerif TYPE_CHECKING:from collections.abc import Iterable, Iterator@@ -129,7 +130,9 @@ class ThreadSafeStream(Stream):self.input_queue = input_queuedef write(self, data: KernelMessage) -> None:- with self.stream_lock:+ # The interrupt handler also writes to this stream. Finish the send+ # and release the lock before allowing it to run.+ with SigintHandler.defer(), self.stream_lock:try:self.pipe.send(data)except OSError as e:diff --git a/marimo/_runtime/handlers.py b/marimo/_runtime/handlers.pyindex 72a33cc565..c471317a82 100644--- a/marimo/_runtime/handlers.py+++ b/marimo/_runtime/handlers.py@@ -12,6 +12,7 @@ from marimo._runtime.context import get_contextfrom marimo._runtime.context.kernel_context import KernelRuntimeContextfrom marimo._runtime.context.types import safe_get_contextfrom marimo._runtime.control_flow import MarimoInterrupt+from marimo._utils.signals import SigintHandlerLOGGER = _loggers.marimo_logger()@@ -21,7 +22,7 @@ if TYPE_CHECKING:from marimo._runtime.runtime import Kernel-def construct_interrupt_handler() -> Callable[[int, Any], None]:+def construct_interrupt_handler() -> SigintHandler:def interrupt_handler(signum: int, frame: Any) -> None:"""Tries to interrupt the kernel."""del signum@@ -71,7 +72,7 @@ def construct_interrupt_handler() -> Callable[[int, Any], None]:sched.cancel_all()raise MarimoInterrupt- return interrupt_handler+ return SigintHandler(interrupt_handler)def construct_sigterm_handler(kernel: Kernel) -> Callable[[int, Any], None]:diff --git a/marimo/_utils/signals.py b/marimo/_utils/signals.pyindex d3c6727e64..ff40306e50 100644--- a/marimo/_utils/signals.py+++ b/marimo/_utils/signals.py@@ -1,8 +1,57 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import contextlibimport signal-from typing import Any+import threading+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from collections.abc import Callable, Iterator+ from types import FrameType+ from typing import ClassVar+++class SigintHandler:+ """Defer and coalesce SIGINT callbacks without changing OS signal state."""++ # Shared so handlers forwarding to marimo's handler also respect deferral.+ _pending: ClassVar[+ list[tuple[SigintHandler, int, FrameType | None]] | None+ ] = None++ def __init__(+ self, handler: Callable[[int, FrameType | None], None]+ ) -> None:+ self._handler = handler++ def __call__(self, signum: int, frame: FrameType | None) -> None:+ pending = self._pending+ if pending is not None:+ pending[:] = [(self, signum, frame)]+ else:+ self._handler(signum, frame)++ @classmethod+ @contextlib.contextmanager+ def defer(cls) -> Iterator[None]:+ """Replay a pending signal after the outermost main-thread scope."""+ # Signal handlers run on the main thread; worker writes cannot reenter.+ if threading.current_thread() is not threading.main_thread():+ yield+ return++ previous = cls._pending+ pending: list[tuple[SigintHandler, int, FrameType | None]] = []+ try:+ cls._pending = pending+ yield+ finally:+ # Restore before replay: the handler can raise or write again.+ cls._pending = previous+ if pending:+ handler, signum, frame = pending[0]+ handler(signum, frame)def restore_signals() -> None:diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.pyindex 86f4fdeae7..c2753f322e 100644--- a/tests/_messaging/test_streams.py+++ b/tests/_messaging/test_streams.py@@ -1,14 +1,75 @@+import signalimport sysimport threadingfrom queue import Queuefrom typing import Any+from unittest.mock import Mock+import pytest++from marimo._messaging.notification import InterruptedNotification+from marimo._messaging.serde import serialize_kernel_messagefrom marimo._messaging.streams import ThreadSafeStreamfrom marimo._messaging.types import KernelMessage+from marimo._runtime.handlers import construct_interrupt_handlerfrom marimo._runtime.runtime import Kernel+from marimo._utils.signals import SigintHandlerfrom tests.conftest import ExecReqProvider, MockedKernel[email protected]("custom_handler", [False, True])[email protected]("broken_pipe", [False, True])+def test_stream_write_preserves_signal_configuration(+ monkeypatch: pytest.MonkeyPatch,+ custom_handler: bool,+ broken_pipe: bool,+) -> None:+ handler = Mock() if custom_handler else construct_interrupt_handler()++ # Installing even the same handler resets POSIX syscall-restart behavior.+ def forbid_signal_change(*_args: Any) -> None:+ pytest.fail("Stream writes must not change OS signal configuration")++ pipe = Mock()+ if broken_pipe:+ pipe.send.side_effect = BrokenPipeError+ stream = ThreadSafeStream(+ pipe=pipe, input_queue=Queue[str](), redirect_console=False+ )+ message = serialize_kernel_message(InterruptedNotification())+ with monkeypatch.context() as patch:+ patch.setattr(signal, "getsignal", lambda _signum: handler)+ patch.setattr(signal, "signal", forbid_signal_change)+ if hasattr(signal, "siginterrupt"):+ patch.setattr(signal, "siginterrupt", forbid_signal_change)+ stream.write(message)+ pipe.send.assert_called_once_with(message)+++def test_stream_write_defers_forwarded_interrupt(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ lock_states: list[bool] = []+ pipe = Mock()+ stream = ThreadSafeStream(+ pipe=pipe, input_queue=Queue[str](), redirect_console=False+ )+ handler = SigintHandler(+ lambda *_args: lock_states.append(stream.stream_lock.locked())+ )++ def forward_interrupt(signum: int, frame: Any) -> None:+ handler(signum, frame)++ # A user-installed handler can forward SIGINT to marimo's saved handler.+ monkeypatch.setattr(signal, "getsignal", lambda _signum: forward_interrupt)+ pipe.send.side_effect = lambda _message: forward_interrupt(+ signal.SIGINT, None+ )+ stream.write(KernelMessage(b"output"))+ assert lock_states == [False]++class _SerializedPipe:def __init__(self) -> None:self.messages: list[KernelMessage] = []diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex bb642f5705..3ba13775e6 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -37,6 +37,7 @@ from marimo._runtime.commands import (AppMetadata,CreateNotebookCommand,ExecuteCellCommand,+ ExecuteCellsCommand,SyncGraphCommand,UpdateUIElementCommand,)@@ -176,7 +177,10 @@ async def test_kernel_manager_edit_mode() -> None:queue_manager.control_queue.join_thread() # type: ignore-async def test_kernel_manager_interrupt() -> None:[email protected]("interrupt_during_write", [False, True])+async def test_kernel_manager_interrupt(+ interrupt_during_write: bool,+) -> None:queue_manager = QueueManagerImpl(use_multiprocessing=True)kernel_manager = KernelManagerImpl(queue_manager=queue_manager,@@ -203,7 +207,11 @@ async def test_kernel_manager_interrupt() -> None:):continueoutput = message.output.data- if isinstance(output, str) and "ready-to-interrupt" in output:+ if (+ not interrupt_during_write+ and isinstance(output, str)+ and "ready-to-interrupt" in output+ ):kernel_manager.interrupt_kernel()elif isinstance(output, list):interrupted |= any(@@ -211,18 +219,39 @@ async def test_kernel_manager_interrupt() -> None:for error in output)+ code = inspect.cleandoc("""+ import marimo as mo+ mo.output.append("ready-to-interrupt")+ while True:+ pass+ """)+ if interrupt_during_write:+ # Deliver SIGINT while write() still owns the transport lock.+ code = inspect.cleandoc("""+ import _thread+ import marimo as mo+ from marimo._runtime.context import get_context++ _pipe = get_context().stream.pipe+ _send = _pipe.send++ def _send_and_interrupt(message):+ _send(message)+ if b"ready-to-interrupt" in message:+ _pipe.send = _send+ _thread.interrupt_main()++ _pipe.send = _send_and_interrupt+ mo.output.append("ready-to-interrupt")+ """)+try:queue_manager.put_control_request(CreateNotebookCommand(execution_requests=(ExecuteCellCommand(cell_id="1",- code=inspect.cleandoc("""- import marimo as mo- mo.output.append("ready-to-interrupt")- while True:- pass- """),+ code=code,),),cell_ids=("1",),@@ -235,6 +264,16 @@ async def test_kernel_manager_interrupt() -> None:assert await asyncio.wait_for(asyncio.to_thread(interrupt_running_cell), timeout=5)+ # A later interrupt must still work after the first handler raised.+ queue_manager.put_control_request(+ ExecuteCellsCommand(+ cell_ids=["1"],+ codes=["import _thread; _thread.interrupt_main()"],+ )+ )+ assert await asyncio.wait_for(+ asyncio.to_thread(interrupt_running_cell), timeout=5+ )finally:kernel_manager.close_kernel()diff --git a/tests/_utils/test_signals.py b/tests/_utils/test_signals.pynew file mode 100644index 0000000000..34e22778a6--- /dev/null+++ b/tests/_utils/test_signals.py@@ -0,0 +1,53 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import signal+from unittest.mock import Mock++import pytest++from marimo._utils.signals import SigintHandler+++def test_nested_deferral_replays_after_outermost_scope() -> None:+ callback = Mock()+ handler = SigintHandler(callback)++ with handler.defer():+ handler(signal.SIGINT, None)+ with handler.defer():+ handler(signal.SIGINT, None)+ callback.assert_not_called()++ callback.assert_called_once_with(signal.SIGINT, None)+++def test_deferral_ends_before_raising_handler_runs() -> None:+ callback = Mock(side_effect=KeyboardInterrupt)+ handler = SigintHandler(callback)++ with pytest.raises(KeyboardInterrupt), handler.defer():+ handler(signal.SIGINT, None)++ # The old pending interrupt must not leak into a later write.+ with handler.defer():+ pass+ callback.assert_called_once_with(signal.SIGINT, None)++ with pytest.raises(KeyboardInterrupt):+ handler(signal.SIGINT, None)+ assert callback.call_count == 2+++def test_deferral_replays_when_scope_raises() -> None:+ callback = Mock()+ handler = SigintHandler(callback)++ def fail_after_interrupt() -> None:+ handler(signal.SIGINT, None)+ raise RuntimeError("send failed")++ with pytest.raises(RuntimeError), handler.defer():+ fail_after_interrupt()++ callback.assert_called_once_with(signal.SIGINT, None)