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
improve: run mode performance for streams (#3648)
Akshay Agrawal94c6664e3f8d
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex 999300e2df..bd83d9ab9e 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -81,22 +81,25 @@ class ThreadSafeStream(Stream):self,pipe: PipeProtocol,input_queue: QueueType[str],+ redirect_console: bool,cell_id: Optional[CellId_t] = None,):self.pipe = pipeself.cell_id = cell_id+ self.redirect_console = redirect_console# A single stream is shared by the kernel and the code completion# worker. The lock should almost always be uncontended.self.stream_lock = threading.Lock()- # Console outputs are buffered- self.console_msg_cv = threading.Condition(threading.Lock())- self.console_msg_queue: deque[ConsoleMsg | None] = deque()- self.buffered_console_thread = threading.Thread(- target=buffered_writer,- args=(self.console_msg_queue, self, self.console_msg_cv),- )- self.buffered_console_thread.start()+ if self.redirect_console:+ # Console outputs are buffered+ self.console_msg_cv = threading.Condition(threading.Lock())+ self.console_msg_queue: deque[ConsoleMsg | None] = deque()+ self.buffered_console_thread = threading.Thread(+ target=buffered_writer,+ args=(self.console_msg_queue, self, self.console_msg_cv),+ )+ self.buffered_console_thread.start()# stdin messages are pulled from this queueself.input_queue = input_queue@@ -115,9 +118,10 @@ class ThreadSafeStream(Stream):# Sending `None` through the queue signals the console thread to exit.# We don't join the thread in case its processing outputs still; don't# want to block the entire program.- self.console_msg_queue.append(None)- with self.console_msg_cv:- self.console_msg_cv.notify()+ if self.redirect_console:+ self.console_msg_queue.append(None)+ with self.console_msg_cv:+ self.console_msg_cv.notify()def _forward_os_stream(standard_stream: Stdout | Stderr, fd: int) -> None:diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 0226eb01b8..673b31f63d 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -2138,6 +2138,8 @@ def launch_kernel(profiler = cProfile.Profile()profiler.enable()+ should_redirect_stdio = is_edit_mode or redirect_console_to_browser+# Create communication channelsif socket_addr is not None:n_tries = 0@@ -2156,10 +2158,16 @@ def launch_kernel(LOGGER.debug("Failed to connect to socket.")return- stream = ThreadSafeStream(pipe=pipe, input_queue=input_queue)+ stream = ThreadSafeStream(+ pipe=pipe,+ input_queue=input_queue,+ redirect_console=should_redirect_stdio,+ )elif stream_queue is not None:stream = ThreadSafeStream(- pipe=QueuePipe(stream_queue), input_queue=input_queue+ pipe=QueuePipe(stream_queue),+ input_queue=input_queue,+ redirect_console=should_redirect_stdio,)else:raise RuntimeError(@@ -2167,16 +2175,8 @@ def launch_kernel()# Console output is hidden in run mode, so no need to redirect# (redirection of console outputs is not thread-safe anyway)- stdout = (- ThreadSafeStdout(stream)- if is_edit_mode or redirect_console_to_browser- else None- )- stderr = (- ThreadSafeStderr(stream)- if is_edit_mode or redirect_console_to_browser- else None- )+ stdout = ThreadSafeStdout(stream) if should_redirect_stdio else None+ stderr = ThreadSafeStderr(stream) if should_redirect_stdio else None# TODO(akshayka): stdin in run mode? input(prompt) uses stdout, which# isn't currently available in run mode.stdin = ThreadSafeStdin(stream) if is_edit_mode else Nonediff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.pyindex 8c5962924f..f57adda8a6 100644--- a/marimo/_runtime/threads.py+++ b/marimo/_runtime/threads.py@@ -5,7 +5,6 @@ import threadingfrom typing import Anyfrom marimo._messaging.streams import ThreadSafeStream-from marimo._pyodide.streams import PyodideStreamfrom marimo._runtime.context.kernel_context import KernelRuntimeContextfrom marimo._runtime.context.script_context import ScriptRuntimeContextfrom marimo._runtime.context.types import (@@ -56,13 +55,7 @@ class Thread(threading.Thread):# TODO(akshayka): stdin is not threadsafeinput_queue=ctx.stream.input_queue,cell_id=ctx.stream.cell_id,- )- elif isinstance(ctx.stream, PyodideStream):- self._marimo_ctx.stream = type(ctx.stream)(- pipe=ctx.stream.pipe,- # TODO(akshayka): stdin is not threadsafe- input_queue=ctx.stream.input_queue,- cell_id=ctx.stream.cell_id,+ redirect_console=False,)else:raise RuntimeError(@@ -77,6 +70,7 @@ class Thread(threading.Thread):pipe=ctx.stream.pipe,input_queue=ctx.stream.input_queue,cell_id=ctx.stream.cell_id,+ redirect_console=False,)else:raise RuntimeError(diff --git a/tests/conftest.py b/tests/conftest.pyindex 38e014a26d..91c5cdbba7 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -50,6 +50,7 @@ class _MockStream(ThreadSafeStream):cell_id: int | None = Noneinput_queue: None = Nonepipe: None = None+ redirect_console: bool = Falsemessages: list[tuple[str, dict[Any, Any]]] = dataclasses.field(default_factory=list