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
Refactor communication between server/kernels to use queues in run mode (#2379)
Akshay Agrawal7dae29754d1d
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex e1a246ebae..111fe05b5e 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -48,6 +48,9 @@ LOGGER = loggers.marimo_logger()def serialize(datacls: Any) -> Dict[str, JSONType]:+ # TODO(akshayka): maybe serialize as bytes (JSON), not objects ...,+ # then `send_bytes` over connection ... to try to avoid pickling+ # issuestry:# Try to serialize as a dataclassreturn cast(diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex a9c15f54e0..2cbf30af39 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -7,7 +7,14 @@ import osimport sysimport threadingfrom collections import deque-from typing import Any, Iterable, Iterator, Optional+from typing import (+ TYPE_CHECKING,+ Any,+ Iterable,+ Iterator,+ Optional,+ Protocol,+)from marimo import _loggersfrom marimo._ast.cell import CellId_t@@ -22,7 +29,9 @@ from marimo._messaging.types import (Stream,)from marimo._server.types import QueueType-from marimo._utils.typed_connection import TypedConnection++if TYPE_CHECKING:+ import queueLOGGER = _loggers.marimo_logger()@@ -52,12 +61,25 @@ OUTPUT_MAX_BYTES = int(os.getenv("MARIMO_OUTPUT_MAX_BYTES", 5_000_000))STD_STREAM_MAX_BYTES = int(os.getenv("MARIMO_STD_STREAM_MAX_BYTES", 1_000_000))+class PipeProtocol(Protocol):+ def send(self, obj: Any) -> None:+ pass+++class QueuePipe:+ def __init__(self, queue: queue.Queue[KernelMessage]):+ self._queue = queue++ def send(self, obj: Any) -> None:+ self._queue.put_nowait(obj)++class ThreadSafeStream(Stream):"""A thread-safe wrapper around a pipe."""def __init__(self,- pipe: TypedConnection[KernelMessage],+ pipe: PipeProtocol,input_queue: QueueType[str],cell_id: Optional[CellId_t] = None,):diff --git a/marimo/_output/formatters/arviz_formatters.py b/marimo/_output/formatters/arviz_formatters.pyindex f5fa56d9cb..5639afbf6e 100644--- a/marimo/_output/formatters/arviz_formatters.py+++ b/marimo/_output/formatters/arviz_formatters.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsfrom typing import TYPE_CHECKING, Anydiff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.pyindex 030874298e..cb20c67470 100644--- a/marimo/_runtime/reload/module_watcher.py+++ b/marimo/_runtime/reload/module_watcher.py@@ -135,15 +135,12 @@ def watch_modules(# Collect the modules used by each cellmodules: dict[str, types.ModuleType] = {}modname_to_cell_id: dict[str, CellId_t] = {}- LOGGER.debug("Acquiring graph lock to find imported modules.")with graph.lock:- LOGGER.debug("Acquired graph lock.")for cell_id, cell in graph.cells.items():for modname in modules_imported_by_cell(cell, sys_modules):if modname in sys_modules:modules[modname] = sys_modules[modname]modname_to_cell_id[modname] = cell_id- LOGGER.debug("Released graph lock and found imported modules.")stale_modules = _check_modules(modules=modules,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 4dd234777f..7bc3cb53f1 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -52,6 +52,7 @@ from marimo._messaging.ops import (VariableValues,)from marimo._messaging.streams import (+ QueuePipe,ThreadSafeStderr,ThreadSafeStdin,ThreadSafeStdout,@@ -133,6 +134,7 @@ from marimo._utils.typed_connection import TypedConnectionfrom marimo._utils.variables import is_localif TYPE_CHECKING:+ import queuefrom collections.abc import Sequencefrom types import ModuleType@@ -1861,7 +1863,8 @@ def launch_kernel(set_ui_element_queue: QueueType[SetUIElementValueRequest],completion_queue: QueueType[CodeCompletionRequest],input_queue: QueueType[str],- socket_addr: tuple[str, int],+ stream_queue: queue.Queue[KernelMessage] | None,+ socket_addr: tuple[str, int] | None,is_edit_mode: bool,configs: dict[CellId_t, CellConfig],app_metadata: AppMetadata,@@ -1885,24 +1888,33 @@ def launch_kernel(profiler = cProfile.Profile()profiler.enable()- n_tries = 0- pipe: Optional[TypedConnection[KernelMessage]] = None- while n_tries < 100:- try:- pipe = TypedConnection[KernelMessage].of(- connection.Client(socket_addr)- )- break- except Exception:- n_tries += 1- time.sleep(0.01)+ # Create communication channels+ if socket_addr is not None:+ n_tries = 0+ pipe: Optional[TypedConnection[KernelMessage]] = None+ while n_tries < 100:+ try:+ pipe = TypedConnection[KernelMessage].of(+ connection.Client(socket_addr)+ )+ break+ except Exception:+ n_tries += 1+ time.sleep(0.01)- if n_tries == 100 or pipe is None:- LOGGER.debug("Failed to connect to socket.")- return+ if n_tries == 100 or pipe is None:+ LOGGER.debug("Failed to connect to socket.")+ return- # Create communication channels- stream = ThreadSafeStream(pipe=pipe, input_queue=input_queue)+ stream = ThreadSafeStream(pipe=pipe, input_queue=input_queue)+ elif stream_queue is not None:+ stream = ThreadSafeStream(+ pipe=QueuePipe(stream_queue), input_queue=input_queue+ )+ else:+ raise RuntimeError(+ "One of queue_pipe and socket_addr must be non None"+ )# Console output is hidden in run mode, so no need to redirect# (redirection of console outputs is not thread-safe anyway)stdout = (diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 5eb2d7bb44..32b9c6cb92 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -27,7 +27,7 @@ import timefrom multiprocessing import connectionfrom multiprocessing.queues import Queue as MPQueuefrom pathlib import Path-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, Unionfrom uuid import uuid4from marimo import _loggers@@ -67,7 +67,10 @@ from marimo._server.types import QueueTypefrom marimo._server.utils import print_tabbedfrom marimo._tracer import server_tracerfrom marimo._utils.disposable import Disposable-from marimo._utils.distributor import Distributor+from marimo._utils.distributor import (+ ConnectionDistributor,+ QueueDistributor,+)from marimo._utils.file_watcher import FileWatcherfrom marimo._utils.paths import import_filesfrom marimo._utils.repr import format_repr@@ -116,6 +119,11 @@ class QueueManager:if context is not Noneelse queue.Queue(maxsize=1))+ self.stream_queue: (+ "queue.Queue[Union[KernelMessage , None]]" | None+ ) = None+ if not use_multiprocessing:+ self.stream_queue = queue.Queue()def close_queues(self) -> None:if isinstance(self.control_queue, MPQueue):@@ -165,18 +173,20 @@ class KernelManager:self.app_metadata = app_metadataself.user_config_manager = user_config_managerself.redirect_console_to_browser = redirect_console_to_browser++ # Only used in edit modeself._read_conn: Optional[TypedConnection[KernelMessage]] = Noneself._virtual_files_supported = virtual_files_supporteddef start_kernel(self) -> None:- # Need to use a socket for windows compatibility- listener = connection.Listener(family="AF_INET")-# We use a process in edit mode so that we can interrupt the app# with a SIGINT; we don't mind the additional memory consumption,# since there's only one client sessis_edit_mode = self.mode == SessionMode.EDIT+ listener = Noneif is_edit_mode:+ # Need to use a socket for windows compatibility+ listener = connection.Listener(family="AF_INET")self.kernel_task = mp.Process(target=runtime.launch_kernel,args=(@@ -184,6 +194,8 @@ class KernelManager:self.queue_manager.set_ui_element_queue,self.queue_manager.completion_queue,self.queue_manager.input_queue,+ # stream queue unused+ None,listener.address,is_edit_mode,self.configs,@@ -209,8 +221,6 @@ class KernelManager:# naturally exit before cleaning up resourcesdef launch_kernel_with_cleanup(*args: Any) -> None:runtime.launch_kernel(*args)- if not self.kernel_connection.closed:- self.kernel_connection.close()# install formatter import hooks, which will be shared by all# threads (in edit mode, the single kernel process installs@@ -219,6 +229,7 @@ class KernelManager:theme=self.user_config_manager.config["display"]["theme"])+ assert self.queue_manager.stream_queue is not None# Make threads daemons so killing the server immediately brings# down all client sessionsself.kernel_task = threading.Thread(@@ -228,7 +239,9 @@ class KernelManager:self.queue_manager.set_ui_element_queue,self.queue_manager.completion_queue,self.queue_manager.input_queue,- listener.address,+ self.queue_manager.stream_queue,+ # IPC not used in run mode+ None,is_edit_mode,self.configs,self.app_metadata,@@ -248,9 +261,12 @@ class KernelManager:)self.kernel_task.start() # type: ignore- # First thing kernel does is connect to the socket, so it's safe to- # call accept- self._read_conn = TypedConnection[KernelMessage].of(listener.accept())+ if listener is not None:+ # First thing kernel does is connect to the socket, so it's safe to+ # call accept+ self._read_conn = TypedConnection[KernelMessage].of(+ listener.accept()+ )@propertydef profile_path(self) -> str | None:@@ -309,7 +325,8 @@ class KernelManager:self.queue_manager.close_queues()if self.kernel_task.is_alive():self.kernel_task.terminate()- self.kernel_connection.close()+ if self._read_conn is not None:+ self._read_conn.close()elif self.kernel_task.is_alive():# We don't join the kernel thread because we don't want to server# to block on it finishing@@ -433,10 +450,9 @@ class Session:) -> None:"""Initialize kernel and client connection to it."""# This is some unique ID that we can use to identify the session- # We don't use the session_id because this can change if the- # session is resumed+ # in edit mode. We don't use the session_id because this can change if+ # the session is resumedself.initialization_id = initialization_id- self._queue_manager: QueueManagerself.app_file_manager = app_file_managerself.room = Room()self._queue_manager = queue_manager@@ -446,15 +462,25 @@ class Session:self.kernel_manager.start_kernel()# Reads from the kernel connection and distributes the# messages to each subscriber.- self.message_distributor = Distributor[KernelMessage](- self.kernel_manager.kernel_connection+ self.message_distributor: (+ ConnectionDistributor[KernelMessage]+ | QueueDistributor[KernelMessage])+ if self.kernel_manager.mode == SessionMode.EDIT:+ self.message_distributor = ConnectionDistributor[KernelMessage](+ self.kernel_manager.kernel_connection+ )+ else:+ q = self._queue_manager.stream_queue+ assert q is not None+ self.message_distributor = QueueDistributor[KernelMessage](queue=q)+self.message_distributor.add_consumer(lambda msg: self.session_view.add_raw_operation(msg[1]))self.connect_consumer(session_consumer, main=True)-self.message_distributor.start()+self.heartbeat_task: Optional[asyncio.Task[Any]] = Noneself._start_heartbeat()self._closed = Falsediff --git a/marimo/_utils/distributor.py b/marimo/_utils/distributor.pyindex 7f77ba689e..a1471c3330 100644--- a/marimo/_utils/distributor.py+++ b/marimo/_utils/distributor.py@@ -2,22 +2,26 @@from __future__ import annotationsimport asyncio+import threadingimport time-from typing import TYPE_CHECKING, Callable, Generic, TypeVar+from typing import TYPE_CHECKING, Callable, Generic, TypeVar, Unionfrom marimo import _loggersfrom marimo._utils.disposable import Disposablefrom marimo._utils.typed_connection import TypedConnectionif TYPE_CHECKING:- from threading import Thread+ import queueLOGGER = _loggers.marimo_logger()T = TypeVar("T")-class Distributor(Generic[T]):+Consumer = Callable[[T], None]+++class ConnectionDistributor(Generic[T]):"""Used to distribute the response of a multiprocessing Connection to multipleconsumers.@@ -34,11 +38,10 @@ class Distributor(Generic[T]):"""def __init__(self, input_connection: TypedConnection[T]) -> None:- self.consumers: list[Callable[[T], None]] = []+ self.consumers: list[Consumer[T]] = []self.input_connection = input_connection- self.thread: Thread | None = None- def add_consumer(self, consumer: Callable[[T], None]) -> Disposable:+ def add_consumer(self, consumer: Consumer[T]) -> Disposable:"""Add a consumer to the distributor."""self.consumers.append(consumer)@@ -53,6 +56,8 @@ class Distributor(Generic[T]):retry_sleep_seconds = 0.001while self.input_connection.poll():try:+ # TODO: just recv_bytes (and change stream to send_bytes)+ # to eliminate pickling overhead/bugsresponse = self.input_connection.recv()except BlockingIOError as e:# recv() sporadically fails with EAGAIN, EDEADLK ...@@ -87,3 +92,48 @@ class Distributor(Generic[T]):self.input_connection.recv()except EOFError:break+++class QueueDistributor(Generic[T]):+ def __init__(self, queue: queue.Queue[Union[T, None]]) -> None:+ self.consumers: list[Consumer[T]] = []+ # distributor uses None as a signal to stop+ self.queue = queue+ self.thread: threading.Thread | None = None+ self._stop = False+ # protects the consumers list+ self._lock = threading.Lock()++ def add_consumer(self, consumer: Consumer[T]) -> Disposable:+ """Add a consumer to the distributor."""+ with self._lock:+ self.consumers.append(consumer)++ def _remove() -> None:+ with self._lock:+ if consumer in self.consumers:+ self.consumers.remove(consumer)++ return Disposable(_remove)++ def _loop(self) -> None:+ while not self._stop:+ msg = self.queue.get()+ if msg is None:+ break++ with self._lock:+ for consumer in self.consumers:+ consumer(msg)++ def start(self) -> threading.Thread:+ self.thread = threading.Thread(target=self._loop, daemon=True)+ self.thread.start()+ return self.thread++ def stop(self) -> None:+ self.queue.put_nowait(None)++ def flush(self) -> None:+ """Flush the distributor."""+ passdiff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex a5deeb764f..e2523a7f96 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -63,7 +63,7 @@ def test_queue_manager() -> None:@save_and_restore_main-def test_kernel_manager() -> None:+def test_kernel_manager_run_mode() -> None:# Mock objects and data for testingqueue_manager = QueueManager(use_multiprocessing=False)mode = SessionMode.RUN@@ -82,7 +82,7 @@ def test_kernel_manager() -> None:# Assert startupassert kernel_manager.kernel_task is not None- assert kernel_manager._read_conn is not None+ assert kernel_manager._read_conn is Noneassert kernel_manager.is_alive()kernel_manager.close_kernel()@@ -94,6 +94,39 @@ def test_kernel_manager() -> None:assert queue_manager.control_queue.empty()+@save_and_restore_main+def test_kernel_manager_edit_mode() -> None:+ # Mock objects and data for testing+ queue_manager = QueueManager(use_multiprocessing=True)+ mode = SessionMode.EDIT++ # Instantiate a KernelManager+ kernel_manager = KernelManager(+ queue_manager,+ mode,+ {},+ app_metadata,+ UserConfigManager(),+ virtual_files_supported=True,+ )++ kernel_manager.start_kernel()++ # Assert startup+ assert kernel_manager.kernel_task is not None+ assert kernel_manager._read_conn is not None+ assert kernel_manager.is_alive()++ kernel_manager.close_kernel()++ # Assert shutdown+ kernel_manager.kernel_task.join()+ assert not kernel_manager.is_alive()+ # these are known to be mp.Queue+ queue_manager.input_queue.join_thread() # type: ignore+ queue_manager.control_queue.join_thread() # type: ignore++@save_and_restore_maindef test_kernel_manager_interrupt(tmp_path) -> None:queue_manager = QueueManager(use_multiprocessing=True)diff --git a/tests/_utils/test_distributor.py b/tests/_utils/test_distributor.pyindex 374c267f1c..3bf4925350 100644--- a/tests/_utils/test_distributor.py+++ b/tests/_utils/test_distributor.py@@ -1,7 +1,14 @@+from __future__ import annotations++import queue+import timefrom typing import Anyfrom unittest.mock import MagicMock, patch-from marimo._utils.distributor import Distributor+from marimo._utils.distributor import (+ ConnectionDistributor,+ QueueDistributor,+)@patch("asyncio.get_event_loop")@@ -9,7 +16,7 @@ def test_start(mock_get_event_loop: Any) -> None:mock_get_event_loop.return_value = MagicMock()mock_connection = MagicMock()- distributor = Distributor[str](mock_connection)+ distributor = ConnectionDistributor[str](mock_connection)# Define two mock consumer functionsmock_consumer1 = MagicMock()@@ -49,3 +56,55 @@ def test_start(mock_get_event_loop: Any) -> None:# Assert the event loop had the reader removeddistributor.stop()assert mock_connection.closed+++def test_queued_distributor() -> None:+ q = queue.Queue()+ distributor = QueueDistributor[str](q)++ # Define two mock consumer functions+ l1 = []+ l2 = []+ consumer1 = lambda msg: l1.append(msg) # noqa: E731+ consumer2 = lambda msg: l2.append(msg) # noqa: E731++ # Add the consumers to the distributor+ dispose = distributor.add_consumer(consumer1)+ distributor.add_consumer(consumer2)++ thread = distributor.start()++ q.put("msg1")+ q.put("msg2")++ waited_s = 0+ while not q.empty and waited_s < 2.0:+ time.sleep(0.1)+ waited_s += 0.1+ assert q.empty+ time.sleep(0.1)+ assert q.empty+ assert l1 == ["msg1", "msg2"]+ assert l2 == ["msg1", "msg2"]++ # Remove one of the consumers+ dispose()+ time.sleep(0.1)+ assert distributor.consumers == [consumer2]++ # Send+ q.put_nowait("msg3")++ waited_s = 0+ while not q.empty and waited_s < 2.0:+ time.sleep(0.1)+ waited_s += 0.1+ assert q.empty+ time.sleep(0.1)+ # l1 should not have gotten another message, it was removed+ assert l1 == ["msg1", "msg2"]+ assert l2 == ["msg1", "msg2", "msg3"]++ distributor.stop()+ thread.join(timeout=1.0)+ assert not thread.is_alive()