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
fix: pickle-ability of functions/classes (#811)
Akshay Agrawalefdbcedb581a
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 574284892a..4b965daf9e 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -33,6 +33,7 @@ from marimo._ast.errors import ()from marimo._output.rich_help import mddocfrom marimo._runtime.dataflow import DirectedGraph, topological_sort+from marimo._runtime.patches import patch_main_module_contextLOGGER = _loggers.marimo_logger()@@ -200,28 +201,36 @@ class App:)self._maybe_initialize()- glbls: dict[Any, Any] = {}-- # Execute cells and collect outputs- outputs: dict[CellId_t, Any] = {}- for cid in self._execution_order:- cell_function = self._cell_manager.cell_data_at(cid).cell_function- if cell_function is not None:- outputs[cid] = execute_cell(cell_function.cell, glbls)-- # Return- # - the outputs, sorted in the order that cells were added to the- # graph- # - dict of defs -> values- return (- tuple(outputs[cid] for cid in self._cell_manager.valid_cell_ids()),- # omit defs that were never defined at runtime, eg due to- # conditional definitions like- #- # if cond:- # x = 0- {name: glbls[name] for name in self._defs if name in glbls},- )++ # No need to provide `file`, `input_override` here, since this+ # function is only called when running as a script+ with patch_main_module_context() as module:+ glbls = module.__dict__++ # Execute cells and collect outputs+ outputs: dict[CellId_t, Any] = {}+ for cid in self._execution_order:+ cell_function = self._cell_manager.cell_data_at(+ cid+ ).cell_function+ if cell_function is not None:+ outputs[cid] = execute_cell(cell_function.cell, glbls)++ # Return+ # - the outputs, sorted in the order that cells were added to the+ # graph+ # - dict of defs -> values+ return (+ tuple(+ outputs[cid] for cid in self._cell_manager.valid_cell_ids()+ ),+ # omit defs that were never defined at runtime, eg due to+ # conditional definitions like+ #+ # if cond:+ # x = 0+ {name: glbls[name] for name in self._defs if name in glbls},+ )class CellManager:diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pynew file mode 100644index 0000000000..2bf07a3614--- /dev/null+++ b/marimo/_runtime/patches.py@@ -0,0 +1,71 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import contextlib+import functools+import sys+import types+from typing import Any, Callable, Iterator++from marimo._runtime import marimo_pdb+++def patch_pdb(debugger: marimo_pdb.MarimoPdb) -> None:+ import pdb++ # Patch Pdb so manually instantiated debuggers create our debugger+ pdb.Pdb = marimo_pdb.MarimoPdb # type: ignore[misc, assignment]+ pdb.set_trace = functools.partial(marimo_pdb.set_trace, debugger=debugger)+++def patch_sys_module(module: types.ModuleType) -> None:+ sys.modules[module.__name__] = module+++def patch_main_module(+ file: str | None, input_override: Callable[[Any], str] | None+) -> types.ModuleType:+ """Patches __main__ so that functions are pickleable."""++ # Every kernel gets its own main module, whose __dict__ attribute+ # serves as the global namespace+ _module = types.ModuleType(+ "__main__", doc="Created for the marimo kernel."+ )+ _module.__dict__.setdefault("__builtin__", globals()["__builtins__"])+ _module.__dict__.setdefault("__builtins__", globals()["__builtins__"])++ if input_override is not None:+ _module.__dict__.setdefault("input", input_override)++ if file is not None:+ _module.__dict__.setdefault("__file__", file)+ else:+ _module.__dict__.setdefault(+ "__file__", sys.modules["__main__"].__file__+ )++ # TODO(akshayka): In run mode, this can introduce races between different+ # kernel threads, since they each share sys.modules. Unfortunately, Python+ # doesn't provide a way for different threads to have their own sys.modules+ # (replacing the dict with a new one isn't guaranteed to have the intended+ # effect, since CPython C code has a reference to the original dict).+ # In practice, as far as I can tell, this only causes problems when using+ # Python pickle, but there may be other subtle issues.+ #+ # As a workaround, the runtime can re-patch sys.modules() on each run,+ # but the issue will still persist as a race condition. Streamlit suffers+ # from the same issue.+ patch_sys_module(_module)+ return _module+++def patch_main_module_context(+ file: str | None = None, input_override: Callable[[Any], str] | None = None+) -> Iterator[types.ModuleType]:+ main = sys.modules["__main__"]+ try:+ yield patch_main_module(file, input_override)+ finally:+ sys.modules["__main__"] = maindiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 16886a514c..d7921b32f6 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport builtinsimport contextlibimport dataclasses-import functoolsimport ioimport itertoolsimport os@@ -60,7 +59,7 @@ from marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import MarimoConvertValueException-from marimo._runtime import cell_runner, dataflow, marimo_pdb+from marimo._runtime import cell_runner, dataflow, marimo_pdb, patchesfrom marimo._runtime.complete import completefrom marimo._runtime.context import (ContextNotInitializedError,@@ -179,15 +178,6 @@ class Kernel:- input_override: a function that overrides the builtin input() function"""- def patch_pdb(self, debugger: marimo_pdb.MarimoPdb) -> None:- import pdb-- # Patch Pdb so manually instantiated debuggers create our debugger- pdb.Pdb = marimo_pdb.MarimoPdb # type: ignore[misc, assignment]- pdb.set_trace = functools.partial(- marimo_pdb.set_trace, debugger=debugger- )-def __init__(self,cell_configs: dict[CellId_t, CellConfig],@@ -206,14 +196,11 @@ class Kernel:self.debugger = marimo_pdb.MarimoPdb(stdout=self.stdout, stdin=self.stdin)- self.patch_pdb(self.debugger)+ patches.patch_pdb(self.debugger)+ self._module = patches.patch_main_module(+ file=self.app_metadata.filename, input_override=input_override+ )- self.globals: dict[Any, Any] = {- "__name__": "__main__",- "__builtins__": globals()["__builtins__"],- "input": input_override,- "__file__": self.app_metadata.filename,- }self.graph = dataflow.DirectedGraph()self.cell_metadata: dict[CellId_t, CellMetadata] = {cell_id: CellMetadata(config=config)@@ -233,6 +220,10 @@ class Kernel:exec("import sys; sys.path.append('')", self.globals)exec("import marimo as __marimo__", self.globals)+ @property+ def globals(self) -> dict[Any, Any]:+ return self._module.__dict__+def start_completion_worker(self, completion_queue: QueueType[CompletionRequest]) -> None:@@ -612,6 +603,12 @@ class Kernel:def _run_cells(self, cell_ids: set[CellId_t]) -> None:"""Run cells and any state updates they trigger"""+ # This patch is an attempt to mitigate problems caused by the fact+ # that in run mode, kernels run in threads and share the same+ # sys.modules. Races can still happen, but this should help in most+ # common cases. We could also be more aggressive and run this before+ # every cell, or even before pickle.dump/pickle.dumps()+ patches.patch_sys_module(self._module)while cells_with_stale_state := self._run_cells_internal(cell_ids):LOGGER.debug("Running state updates ...")cell_ids = dataflow.transitive_closure(diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex 56054810a5..5c1aa1a08a 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+from typing import Any+import pytestfrom marimo._ast.app import App@@ -327,3 +329,29 @@ class TestApp:# obj should not be in the defs dictionaryassert "obj" not in defs++ @staticmethod+ def test_run_pickle() -> None:+ app = App()++ @app.cell+ def __() -> tuple[Any]:+ import pickle++ return (pickle,)++ @app.cell+ def __() -> tuple[Any]:+ def foo():+ ...++ return (foo,)++ @app.cell+ def __(pickle, foo) -> tuple[Any]:+ out = pickle.dumps(foo)+ return (out,)++ _, defs = app.run()++ assert defs["out"] is not Nonediff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex f37268ea75..8c0ab4fbc0 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -777,7 +777,7 @@ def test_file_path(k: Kernel, exec_req: ExecReqProvider) -> None:])- assert k.globals["x"] == "/app/test.py"+ assert "pytest" in k.globals["x"]def test_cell_state_invalidated(k: Kernel, exec_req: ExecReqProvider) -> None:@@ -793,3 +793,21 @@ def test_cell_state_invalidated(k: Kernel, exec_req: ExecReqProvider) -> None:# invalidatedk.run([ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")])assert "y" not in k.globals+++def test_pickle(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run(+ [+ exec_req.get("import pickle"),+ exec_req.get(+ """+ def foo():+ ...++ pickle_output = None+ pickle_output = pickle.dumps(foo)+ """+ ),+ ]+ )+ assert k.globals["pickle_output"] is not Nonediff --git a/tests/_server/conftest.py b/tests/_server/conftest.pyindex ece5448c04..dffd64ccd0 100644--- a/tests/_server/conftest.py+++ b/tests/_server/conftest.py@@ -1,5 +1,6 @@# Copyright 2024 Marimo. All rights reserved.-from typing import Generator+import sys+from typing import Generator, Iteratorimport pytestimport uvicorn@@ -26,7 +27,8 @@ def client_with_lifespans() -> Generator[TestClient, None, None]:@pytest.fixture(scope="function")-def client() -> TestClient:+def client() -> Iterator[TestClient]:+ main = sys.modules["__main__"]app.state.session_manager = get_mock_session_manager()app.state.config_manager = UserConfigManager()client = TestClient(app)@@ -39,7 +41,8 @@ def client() -> TestClient:app.state.host = "localhost"app.state.port = 1234app.state.base_url = ""- return client+ yield client+ sys.modules["__main__"] = maindef get_session_manager(client: TestClient) -> SessionManager:diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 6fb71bda14..6d7eecd66e 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -1,5 +1,6 @@# Copyright 2024 Marimo. All rights reserved.import queue+import sysfrom multiprocessing.queues import Queue as MPQueuefrom typing import Anyfrom unittest.mock import MagicMock@@ -17,6 +18,21 @@ initialize_asyncio()app_metadata = AppMetadata(filename="test.py")+# TODO(akshayka): automatically do this for every test in our test suite+def save_and_restore_main(f):+ """Kernels swap out the main module; restore it after running tests"""++ def wrapper():+ main = sys.modules["__main__"]+ try:+ f()+ finally:+ sys.modules["__main__"] = main++ return wrapper+++@save_and_restore_maindef test_queue_manager() -> None:# Test with multiprocessing queuesqueue_manager_mp = QueueManager(use_multiprocessing=True)@@ -31,6 +47,7 @@ def test_queue_manager() -> None:assert isinstance(queue_manager_thread.input_queue, queue.Queue)+@save_and_restore_maindef test_kernel_manager() -> None:# Mock objects and data for testingqueue_manager = QueueManager(use_multiprocessing=False)@@ -55,6 +72,7 @@ def test_kernel_manager() -> None:assert queue_manager.control_queue.empty()+@save_and_restore_maindef test_session() -> None:session_consumer: Any = MagicMock()session_consumer.connection_state.return_value = ConnectionState.OPEN@@ -93,6 +111,7 @@ def test_session() -> None:assert session.connection_state() == ConnectionState.CLOSED+@save_and_restore_maindef test_session_disconnect_reconnect() -> None:session_consumer: Any = MagicMock()session_consumer.connection_state.return_value = ConnectionState.OPENdiff --git a/tests/conftest.py b/tests/conftest.pyindex 89e9cda28b..8f2d4aac9c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -2,6 +2,7 @@from __future__ import annotationsimport dataclasses+import sysimport textwrapfrom typing import Any, Generator@@ -82,6 +83,7 @@ class MockedKernel:self.stdout = MockStdout(self.stream)self.stderr = MockStderr(self.stream)self.stdin = MockStdin(self.stream)+ self._main = sys.modules["__main__"]self.k = Kernel(stream=self.stream,@@ -90,7 +92,7 @@ class MockedKernel:stdin=self.stdin,cell_configs={},app_metadata=AppMetadata(- filename="/app/test.py",+ filename=None,),)@@ -104,6 +106,7 @@ class MockedKernel:teardown_context()self.stdout._watcher.stop()self.stderr._watcher.stop()+ sys.modules["__main__"] = self._main# fixture that provides a kernel (and tears it down)