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
perf: resource cleanup, don't start module reloader in run mode (#3656)
Akshay Agrawal50710bbdd6fd
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex bd83d9ab9e..5da2fb4f51 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -75,7 +75,10 @@ class QueuePipe:class ThreadSafeStream(Stream):- """A thread-safe wrapper around a pipe."""+ """A thread-safe wrapper around a pipe.++ Does not own the pipe or queue.+ """def __init__(self,@@ -124,7 +127,9 @@ class ThreadSafeStream(Stream):self.console_msg_cv.notify()-def _forward_os_stream(standard_stream: Stdout | Stderr, fd: int) -> None:+def _forward_os_stream(+ standard_stream: Stdout | Stderr, fd: int, should_exit: threading.Event+) -> None:"""Watch a file descriptor and forward it to a stream object."""# This coarse try/except block silences exceptions; a raised exception@@ -135,7 +140,7 @@ def _forward_os_stream(standard_stream: Stdout | Stderr, fd: int) -> None:# exceptions we actually want to pay attention to; then store the exception# and print it to the terminal later (outside an execution context).try:- while True:+ while not should_exit.is_set():data = os.read(fd, 1024)if not data:break@@ -153,9 +158,10 @@ class Watcher:self.standard_stream = standard_streamself.fd = self.standard_stream._original_fdself.read_fd, self.write_fd = os.pipe()+ self._should_exit = threading.Event()self.thread = threading.Thread(target=_forward_os_stream,- args=(self.standard_stream, self.read_fd),+ args=(self.standard_stream, self.read_fd, self._should_exit),daemon=True,)self.thread.start()@@ -179,6 +185,7 @@ class Watcher:def stop(self) -> None:os.close(self.write_fd)os.close(self.read_fd)+ self._should_exit.set()# NB: Python doesn't provide a standard out class to inherit from, so@@ -193,6 +200,9 @@ class ThreadSafeStdout(Stdout):self._original_fd = sys.stdout.fileno()self._watcher = Watcher(self)+ def stop(self) -> None:+ self._watcher.stop()+def fileno(self) -> int:if self._fileno is not None:return self._fileno@@ -253,6 +263,9 @@ class ThreadSafeStderr(Stderr):self._original_fd = sys.stderr.fileno()self._watcher = Watcher(self)+ def stop(self) -> None:+ self._watcher.stop()+def fileno(self) -> int:if self._fileno is not None:return self._filenodiff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex 2758d32a5f..11d48ca08b 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -24,6 +24,10 @@ class Stream(abc.ABC):def write(self, op: str, data: Dict[Any, Any]) -> None:pass+ def stop(self) -> None:+ """Tear down resources, if any."""+ return+class NoopStream(Stream):def write(self, op: str, data: Dict[Any, Any]) -> None:@@ -40,6 +44,10 @@ class Stdout(io.TextIOBase):def write(self, __s: str) -> int:return self._write_with_mimetype(__s, mimetype="text/plain")+ def stop(self) -> None:+ """Tear down resources, if any."""+ pass+class Stderr(io.TextIOBase):name = "stderr"@@ -51,8 +59,14 @@ class Stderr(io.TextIOBase):def write(self, __s: str) -> int:return self._write_with_mimetype(__s, mimetype="text/plain")+ def stop(self) -> None:+ """Tear down resources, if any."""+ pass+class Stdin(io.TextIOBase):name = "stdin"- pass+ def stop(self) -> None:+ """Tear down resources, if any."""+ passdiff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex eb0dba1f2b..e291c144c0 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -31,6 +31,7 @@ if TYPE_CHECKING:class KernelRuntimeContext(RuntimeContext):"""Encapsulates runtime state for a session."""+ # The kernel is _not_ owned by the context; don't teardown._kernel: Kernel_session_mode: SessionMode# app that owns this context; None for top-level contextsdiff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.pyindex 827a017e4d..217da534f5 100644--- a/marimo/_runtime/context/types.py+++ b/marimo/_runtime/context/types.py@@ -71,6 +71,7 @@ class RuntimeContext(abc.ABC):cell_lifecycle_registry: CellLifecycleRegistryvirtual_file_registry: VirtualFileRegistryvirtual_files_supported: bool+ # stream, stdout, stderr are _not_ owned by the contextstream: Streamstdout: Stdout | Nonestderr: Stderr | Nonediff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 673b31f63d..0a8249a186 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -536,6 +536,25 @@ class Kernel:patches.patch_micropip(self.globals)exec("import marimo as __marimo__", self.globals)+ def teardown(self) -> None:+ """Teardown resources owned by the kernel."""+ if self.stdout is not None:+ self.stdout.stop()+ if self.stderr is not None:+ self.stderr.stop()+ if self.stdin is not None:+ self.stdin.stop()+ self.stream.stop()++ if self.module_watcher is not None:+ self.module_watcher.stop()++ # TODO(akshayka): There's a memory leak in run mode, with memory+ # usage increasing with each session creation. Somehow the kernel+ # globals appear to leak, even though the thread exits. As a hack we+ # manually clear kernel memory.+ self._module.__dict__.clear()+def lazy(self) -> bool:return self.reactive_execution_mode == "lazy"@@ -572,9 +591,10 @@ class Kernel:self._update_script_metadata(["marimo"])if (- autoreload_mode == "lazy" or autoreload_mode == "autorun"+ (autoreload_mode == "lazy" or autoreload_mode == "autorun")# Pyodide doesn't support hot module reloading- ) and not is_pyodide():+ and not is_pyodide()+ ):if self.module_reloader is None:self.module_reloader = ModuleReloader()@@ -2141,9 +2161,9 @@ def launch_kernel(should_redirect_stdio = is_edit_mode or redirect_console_to_browser# Create communication channels+ pipe: Optional[TypedConnection[KernelMessage]] = Noneif socket_addr is not None:n_tries = 0- pipe: Optional[TypedConnection[KernelMessage]] = Nonewhile n_tries < 100:try:pipe = TypedConnection[KernelMessage].of(@@ -2173,6 +2193,7 @@ def launch_kernel(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 = ThreadSafeStdout(stream) if should_redirect_stdio else None@@ -2186,10 +2207,12 @@ def launch_kernel(else None)- # In run mode, the kernel should always be in autorun+ # In run mode, the kernel should always be in autorun, and the module+ # autoreloader is disabledif not is_edit_mode:user_config = user_config.copy()user_config["runtime"]["on_cell_change"] = "autorun"+ user_config["runtime"]["auto_reload"] = "off"def _enqueue_control_request(req: ControlRequest) -> None:control_queue.put_nowait(req)@@ -2279,20 +2302,12 @@ def launch_kernel(# reason; prefer using threads (for performance and clarity).asyncio.run(control_loop(kernel))- if stdout is not None:- stdout._watcher.stop()- if stderr is not None:- stderr._watcher.stop()- get_context().virtual_file_registry.shutdown()- stream.stop()-if profiler is not None and profile_path is not None:profiler.disable()profiler.dump_stats(profile_path)- # TODO(akshayka): There's a memory leak in run mode, with memory- # usage increasing with each session creation. Somehow the kernel- # appears to leak, even though the thread exits. As a hack we manually- # clear various data structures.+ get_context().virtual_file_registry.shutdown()teardown_context()- kernel._module.__dict__.clear()+ kernel.teardown()+ if isinstance(pipe, connection.Connection):+ pipe.close()diff --git a/marimo/_sql/utils.py b/marimo/_sql/utils.pyindex 5193544ae9..ae9dc1a9d1 100644--- a/marimo/_sql/utils.py+++ b/marimo/_sql/utils.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.from __future__ import annotationsfrom typing import TYPE_CHECKING, Optional, cast