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: check for module staleness when registering a cell (#1336)
Akshay Agrawala118557d73c3
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 4d8238355a..62d7a2120a 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -125,7 +125,7 @@ class CellImpl:@propertydef imports(self) -> Iterable[ImportData]:- """Return a set of the namespaces imported by this cell."""+ """Return a set of import data for this cell."""return [data.import_datafor _, data in self.variable_data.items()diff --git a/marimo/_runtime/reload/autoreload.py b/marimo/_runtime/reload/autoreload.pyindex 9858c294fb..aee137e5e0 100644--- a/marimo/_runtime/reload/autoreload.py+++ b/marimo/_runtime/reload/autoreload.py@@ -13,6 +13,7 @@ import gcimport ioimport osimport sys+import threadingimport tracebackimport typesimport weakref@@ -22,6 +23,7 @@ from importlib.util import source_from_cachefrom typing import Any, Callable, Dict, Generic, List, Tuple, Type, TypeVarfrom marimo import _loggers+from marimo._ast.cell import CellImplfrom marimo._messaging.tracebacks import write_tracebackLOGGER = _loggers.marimo_logger()@@ -48,7 +50,28 @@ OldObjectsMapping = Dict[]+def modules_imported_by_cell(+ cell: CellImpl, sys_modules: dict[str, types.ModuleType]+) -> set[str]:+ """Get the modules imported by a cell"""+ modules = set()+ for import_data in cell.imports:+ if import_data.module in sys_modules:+ modules.add(import_data.module)+ if import_data.imported_symbol in sys_modules:+ # The imported symbol may or may not be a module, which+ # is why we check if it's in sys.modules+ #+ # e.g., from a import b+ #+ # a.b could be a module, but it could also be a function, ...+ modules.add(import_data.imported_symbol)+ return modules++class ModuleReloader:+ """Thread-safe module reloader."""+def __init__(self) -> None:# Modules that failed to reload: {module: mtime-on-failed-reload, ...}self.failed: dict[str, float] = {}@@ -56,6 +79,10 @@ class ModuleReloader:self.old_objects: OldObjectsMapping = {}# module-name -> mtime (module modification timestamps)self.modules_mtimes: dict[str, float] = {}+ # set of modules names known to be stale but haven't been reloaded+ self.stale_modules: set[str] = set()+ # for thread-safety+ self.lock = threading.Lock()# Timestamp existing modulesself.check(modules=sys.modules, reload=False)@@ -94,41 +121,71 @@ class ModuleReloader:return Nonereturn ModuleMTime(py_filename, pymtime)+ def cell_uses_stale_modules(self, cell: CellImpl) -> bool:+ with self.lock:+ return bool(+ self.stale_modules+ & modules_imported_by_cell(cell, sys.modules)+ )+def check(self, modules: dict[str, types.ModuleType], reload: bool) -> set[types.ModuleType]:"""Check timestamps of modules, optionally reload them.Also patches existing objects with hot-reloaded ones.++ Returns a set of modules that were found to have been modified."""- # materialize the module keys, since we'll be reloading while iterating- modified_modules: set[types.ModuleType] = set()- for modname in list(modules.keys()):- m = modules.get(modname, None)- if m is None:- continue+ # module watcher thread and kernel thread might try to use the+ # reloader at the same time, but reloader mutates state+ #+ # Holds a lock because this method modifies stale_modules+ # and also iterates over it+ with self.lock:+ modified_modules: set[types.ModuleType] = set()+ # materialize the module keys, since we'll be reloading while+ # iterating+ for modname in list(modules.keys()):+ m = modules.get(modname, None)+ if m is None:+ continue- module_mtime = self.filename_and_mtime(m)- if module_mtime is None:- continue- py_filename, pymtime = module_mtime.name, module_mtime.mtime+ module_mtime = self.filename_and_mtime(m)+ if module_mtime is None:+ continue+ py_filename, pymtime = module_mtime.name, module_mtime.mtime- try:- if pymtime <= self.modules_mtimes[modname]:+ try:+ if pymtime <= self.modules_mtimes[modname]:+ continue+ except KeyError:+ self.modules_mtimes[modname] = pymtimecontinue- except KeyError:+ else:+ if self.failed.get(py_filename, None) == pymtime:+ continue+self.modules_mtimes[modname] = pymtime- continue- else:- if self.failed.get(py_filename, None) == pymtime:+ modified_modules.add(m)+ self.stale_modules.add(modname)++ if not reload:+ return modified_modules++ for modname in self.stale_modules:+ # Reload after the check loop: if there are any+ # previously discovered stale modules, reload those as well+ m = modules.get(modname, None)+ if m is None:continue- self.modules_mtimes[modname] = pymtime- modified_modules.add(m)+ module_mtime = self.filename_and_mtime(m)+ if module_mtime is None:+ continue+ py_filename, pymtime = module_mtime.name, module_mtime.mtime- # If we've reached this point, we should try to reload the module- if reload:LOGGER.debug(f"Reloading '{modname}'.")try:superreload(m, self.old_objects)@@ -140,6 +197,7 @@ class ModuleReloader:msg.format(modname, traceback.format_exc(10)),)self.failed[py_filename] = pymtime+ self.stale_modules.clear()return modified_modulesdiff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.pyindex c5f432cc3b..6b49ae13cb 100644--- a/marimo/_runtime/reload/module_watcher.py+++ b/marimo/_runtime/reload/module_watcher.py@@ -10,32 +10,17 @@ import warningsfrom modulefinder import ModuleFinderfrom typing import TYPE_CHECKING, Callable, Literal-from marimo._ast.cell import CellId_t, CellImplfrom marimo._messaging.types import Streamfrom marimo._runtime import dataflow-from marimo._runtime.reload.autoreload import ModuleReloader+from marimo._runtime.reload.autoreload import (+ ModuleReloader,+ modules_imported_by_cell,+)if TYPE_CHECKING:import types--def _modules_imported_by_cell(- cell: CellImpl, sys_modules: dict[str, types.ModuleType]-) -> set[str]:- """Get the modules imported by a cell"""- modules = set()- for import_data in cell.imports:- if import_data.module in sys_modules:- modules.add(import_data.module)- if import_data.imported_symbol in sys_modules:- # The imported symbol may or may not be a module, which- # is why we check if it's in sys.modules- #- # e.g., from a import b- #- # a.b could be a module, but it could also be a function, ...- modules.add(import_data.imported_symbol)- return modules+ from marimo._ast.cell import CellId_tdef is_submodule(src_name: str, target_name: str) -> bool:@@ -145,6 +130,7 @@ def _check_modules(def watch_modules(graph: dataflow.DirectedGraph,+ reloader: ModuleReloader,mode: Literal["lazy", "autorun"],enqueue_run_stale_cells: Callable[[], None],should_exit: threading.Event,@@ -157,7 +143,6 @@ def watch_modules(modules imported by the notebook as well as the modules imported by thosemodules, recursively."""- reloader = ModuleReloader()# modules that failed to be analyzedfailed_filenames: set[str] = set()# work with a copy to avoid race conditions@@ -170,7 +155,7 @@ def watch_modules(modname_to_cell_id: dict[str, CellId_t] = {}with graph.lock:for cell_id, cell in graph.cells.items():- for modname in _modules_imported_by_cell(cell, sys_modules):+ 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@@ -210,6 +195,7 @@ class ModuleWatcher:def __init__(self,graph: dataflow.DirectedGraph,+ reloader: ModuleReloader,mode: Literal["lazy", "autorun"],enqueue_run_stale_cells: Callable[[], None],stream: Stream,@@ -217,6 +203,8 @@ class ModuleWatcher:# ModuleWatcher uses the graph to determine the modules used by the# notebookself.graph = graph+ # Reloader is used to keep track of stale modules+ self.reloader = reloader# When set, signals the watcher thread to exitself.should_exit = threading.Event()# When False, an ExecuteStaleRequest is inflight to the kernel@@ -232,6 +220,7 @@ class ModuleWatcher:target=watch_modules,args=(self.graph,+ self.reloader,self.mode,self.enqueue_run_stale_cells,self.should_exit,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 9eac0dc711..8d28ee5b1d 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -73,7 +73,9 @@ from marimo._runtime.packages.utils import is_python_isolatedfrom marimo._runtime.params import CLIArgs, QueryParamsfrom marimo._runtime.redirect_streams import redirect_streamsfrom marimo._runtime.reload.autoreload import ModuleReloader-from marimo._runtime.reload.module_watcher import ModuleWatcher+from marimo._runtime.reload.module_watcher import (+ ModuleWatcher,+)from marimo._runtime.requests import (AppMetadata,CompletionRequest,@@ -369,6 +371,7 @@ class Kernel:if self.module_watcher is None:self.module_watcher = ModuleWatcher(self.graph,+ reloader=self.module_reloader,enqueue_run_stale_cells=self._execute_stale_cells_callback,mode=autoreload_mode,stream=self.stream,@@ -476,6 +479,14 @@ class Kernel:if cell is not None:self.graph.register_cell(cell_id, cell)+ # leaky abstraction: the graph doesn't know about stale modules, so+ # we have to check for them here.+ module_reloader = self.module_reloader+ if (+ module_reloader is not None+ and module_reloader.cell_uses_stale_modules(cell)+ ):+ self.graph.set_stale(set([cell.cell_id]))LOGGER.debug("registered cell %s", cell_id)LOGGER.debug("parents: %s", self.graph.parents[cell_id])LOGGER.debug("children: %s", self.graph.children[cell_id])diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.pyindex 9fc6c401d2..8cfcc2afe1 100644--- a/tests/_runtime/reload/test_module_watcher.py+++ b/tests/_runtime/reload/test_module_watcher.py@@ -12,7 +12,7 @@ from reload_test_utils import random_modname, update_filefrom marimo._config.config import DEFAULT_CONFIGfrom marimo._dependencies.dependencies import DependencyManager-from marimo._runtime.requests import SetUserConfigRequest+from marimo._runtime.requests import SetCellConfigRequest, SetUserConfigRequestfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider@@ -333,3 +333,50 @@ async def test_reload_third_party(assert not k.graph.cells[er_2.cell_id].staleassert not k.graph.cells[er_3.cell_id].staleassert k.globals["x"] == 2+++async def test_reload_with_modified_cell(+ tmp_path: pathlib.Path,+ py_modname: str,+ k: Kernel,+ exec_req: ExecReqProvider,+):+ sys.path.append(str(tmp_path))+ py_file = tmp_path / pathlib.Path(py_modname + ".py")+ py_file.write_text(+ textwrap.dedent(+ """+ def foo():+ return 1+ """+ )+ )++ config = copy.deepcopy(DEFAULT_CONFIG)+ config["runtime"]["auto_reload"] = "lazy"+ k.set_user_config(SetUserConfigRequest(config=config))+ await k.run(+ [+ er_1 := exec_req.get(f"from {py_modname} import foo"),+ er_2 := exec_req.get("x = foo()"),+ er_3 := exec_req.get("pass"),+ ]+ )+ assert k.globals["x"] == 1+ update_file(+ py_file,+ """+ def foo():+ return 2+ """,+ )++ # wait for the watcher to pick up the change+ await asyncio.sleep(2.5)+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale++ # modify the first cell and make sure it is still marked as stale;+ k._maybe_register_cell(er_1.cell_id, f"from {py_modname} import foo; 1")+ assert er_1.cell_id in k.graph.get_stale()