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
feat: mo.watch.{file, directory} (#4884)
Dylan Madisetti23e47acec3ae
diff --git a/docs/api/index.md b/docs/api/index.mdindex 4d8f6b3c5c..4b2faf0fe3 100644--- a/docs/api/index.md+++ b/docs/api/index.md@@ -26,4 +26,5 @@ Use the marimo library in marimo notebooks (`import marimo as mo`) to| [state](state.md) | Synchronize multiple UI elements with `mo.state` || [app](app.md) | Embed notebooks in other notebooks || [cell](cell.md) | Run cells defined in another notebook |+| [watch](watch.md) | Reactively respond to file changes on disk || [miscellaneous](miscellaneous.md) | Miscellaneous utilities |diff --git a/docs/api/watch.md b/docs/api/watch.mdnew file mode 100644index 0000000000..f47560c6e5--- /dev/null+++ b/docs/api/watch.md@@ -0,0 +1,7 @@+# Watch+++::: marimo.watch.file+++::: marimo.watch.directorydiff --git a/marimo/__init__.py b/marimo/__init__.pyindex 86cefb30a1..351f010ef8 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -47,6 +47,7 @@ __all__ = ["icon","iframe","image",+ "json","latex","lazy","left",@@ -79,14 +80,15 @@ __all__ = ["style","tabs","tree",- "json","video","vstack",+ "watch",]__version__ = "0.13.7"import marimo._ai as aiimport marimo._islands as islands+import marimo._runtime.watch as watchfrom marimo._ast.app import Appfrom marimo._ast.cell import Cellfrom marimo._islands._island_generator import MarimoIslandGeneratordiff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.pyindex 375453f21d..8308f9530d 100644--- a/marimo/_runtime/primitives.py+++ b/marimo/_runtime/primitives.py@@ -23,6 +23,8 @@ FN_CACHE_TYPE = Optional[dict[Union[Callable[..., Any], type], bool]]UNCLONABLE_TYPES = ["marimo._runtime.state.State","marimo._runtime.state.SetFunctor",+ "marimo._runtime.watch._file.FileState",+ "marimo._runtime.watch._directory.DirectoryState",]UNCLONABLE_MODULES = set(diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex c4b8c5c0c0..bbb5cec0c5 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -548,6 +548,7 @@ class Kernel:self._post_execution_hooks.append(render_toplevel_defs)self._globals_lock = threading.RLock()+ self._state_lock = threading.RLock()self._completion_worker_started = Falseself.debugger = debugger_override@@ -1403,9 +1404,11 @@ class Kernel:# redirected to frontend (it's printed to console),# which is incorrectawait runner.run_all()- cells_with_stale_state = runner.resolve_state_updates(- self.state_updates- )+ with self._state_lock:+ cells_with_stale_state = runner.resolve_state_updates(+ self.state_updates+ )+ self.state_updates.clear()self.state_updates.clear()return cells_with_stale_state@@ -1417,9 +1420,16 @@ class Kernel:# store the state and the currently executing cellctx = get_context()assert ctx.execution_context is not None- self.state_updates[state] = ctx.execution_context.cell_id- # TODO(akshayka): Send VariableValues message for any globals- # bound to this state object (just like UI elements)+ cell_id = ctx.execution_context.cell_id+ with self._state_lock:+ self.state_updates[state] = cell_id+ to_update = self.update_stateful_values(+ ctx.state_registry.bound_names(state), state._value+ )+ if self.reactive_execution_mode == "autorun":+ # If autorun, run the cells that depend on the state+ self.graph.set_stale(to_update)+ self._execute_stale_cells_callback()@kernel_tracer.start_as_current_span("delete_cell")async def delete_cell(self, request: DeleteCellRequest) -> None:@@ -1770,44 +1780,15 @@ class Kernel:else:updated_components.append(component)- bound_names = (+ bound_names = {namefor name in ctx.ui_element_registry.bound_names(object_id)if not is_local(name)+ }+ referring_cells.update(+ self.update_stateful_values(bound_names, value))- variable_values: list[VariableValue] = []- for name in bound_names:- # TODO update variable values even for namespaces? lenses? etc- variable_values.append(- VariableValue(name=name, value=component)- )- try:- # subtracting self.graph.definitions[name]: never rerun the- # cell that created the name- referring_cells.update(- self.graph.get_referring_cells(name, language="python")- - self.graph.get_defining_cells(name)- )- except Exception:- # Internal marimo error- sys.stderr.write(- "An exception was raised when finding cells that "- f"refer to a UIElement value, for bound name {name}. "- "This is a bug in marimo. "- "Please copy the below traceback and paste it in an "- "issue: https://github.com/marimo-team/marimo/issues\n"- )- tmpio = io.StringIO()- traceback.print_exc(file=tmpio)- tmpio.seek(0)- write_traceback(tmpio.read())- # Entering undefined behavior territory ...- continue-- if variable_values:- VariableValues(variables=variable_values).broadcast()-if self.reactive_execution_mode == "autorun":await self._run_cells(referring_cells)else:@@ -1855,6 +1836,41 @@ class Kernel:def reset_ui_initializers(self) -> None:self.ui_initializers = {}+ def update_stateful_values(+ self, bound_names: set[str], value: Any+ ) -> set[CellId_t]:+ variable_values: list[VariableValue] = []+ referring_cells: set[CellId_t] = set()+ for name in bound_names:+ # TODO update variable values even for namespaces? lenses? etc+ variable_values.append(VariableValue(name=name, value=value))+ try:+ # subtracting self.graph.definitions[name]: never rerun the+ # cell that created the name+ referring_cells |= self.graph.get_referring_cells(+ name, language="python"+ ) - self.graph.get_defining_cells(name)+ except Exception:+ # Internal marimo error+ sys.stderr.write(+ "An exception was raised when finding cells that "+ f"refer to a UIElement value, for bound name {name}. "+ "This is a bug in marimo. "+ "Please copy the below traceback and paste it in an "+ "issue: https://github.com/marimo-team/marimo/issues\n"+ )+ tmpio = io.StringIO()+ traceback.print_exc(file=tmpio)+ tmpio.seek(0)+ write_traceback(tmpio.read())+ # Entering undefined behavior territory ...+ continue++ if variable_values:+ VariableValues(variables=variable_values).broadcast()++ return referring_cells+@kernel_tracer.start_as_current_span("function_call_request")async def function_call_request(self, request: FunctionCallRequestdiff --git a/marimo/_runtime/side_effect.py b/marimo/_runtime/side_effect.pyindex 14249a9cd4..f5f32d398f 100644--- a/marimo/_runtime/side_effect.py+++ b/marimo/_runtime/side_effect.py@@ -11,18 +11,20 @@ if TYPE_CHECKING:class SideEffect(CellLifecycleItem):- def __init__(self, key: str) -> None:+ def __init__(self, key: str | bytes) -> None:self._key = key@property- def key(self) -> str:+ def key(self) -> bytes:assert self._key is not None- return self._key+ if isinstance(self._key, bytes):+ return self._key+ return self._key.encode("utf-8")@propertydef hash(self) -> bytes:"""Hash the lookup to a consistent size."""- return hashlib.sha256(self._key.encode()).digest()+ return hashlib.sha256(self.key).digest()def create(self, context: RuntimeContext | None) -> None:"""NoOp for side effect.diff --git a/marimo/_runtime/threads.py b/marimo/_runtime/threads.pyindex 2465393b9c..3069e17996 100644--- a/marimo/_runtime/threads.py+++ b/marimo/_runtime/threads.py@@ -142,7 +142,10 @@ class Thread(threading.Thread):def run(self) -> None:if self._marimo_ctx is not None:- initialize_context(self._marimo_ctx)+ try:+ initialize_context(self._marimo_ctx)+ except RuntimeError:+ passif isinstance(self._marimo_ctx, KernelRuntimeContext):self._marimo_ctx.execution_context = ExecutionContext(cell_id=self._marimo_ctx.stream.cell_id, # type: ignorediff --git a/marimo/_runtime/watch/__init__.py b/marimo/_runtime/watch/__init__.pynew file mode 100644index 0000000000..3ac28b6a1d--- /dev/null+++ b/marimo/_runtime/watch/__init__.py@@ -0,0 +1,11 @@+# Copyright 2025 Marimo. All rights reserved.+from marimo._runtime.watch._directory import directory+from marimo._runtime.watch._file import file++# NB. _runtime/reload captures module level changes and+# marimo/_server/sessions.py captures notebook level changes.++__all__ = [+ "file",+ "directory",+]diff --git a/marimo/_runtime/watch/_directory.py b/marimo/_runtime/watch/_directory.pynew file mode 100644index 0000000000..814e3c9794--- /dev/null+++ b/marimo/_runtime/watch/_directory.py@@ -0,0 +1,149 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import hashlib+import os+import sys+import time+from pathlib import Path+from typing import TYPE_CHECKING, Callable, cast++from marimo._output.rich_help import mddoc+from marimo._runtime.watch._path import (+ WATCHER_SLEEP_INTERVAL,+ PathState,+ write_side_effect,+)++if TYPE_CHECKING:+ import threading+ from collections.abc import Iterable+++# For testing only - do not use in production+_TEST_SLEEP_INTERVAL: float | None = None+++def walk(path: Path) -> Iterable[tuple[Path, list[str], list[str]]]:+ if sys.version_info >= (3, 12):+ return path.walk()+ return os.walk(path)+++def _hashable_walk(+ walked: Iterable[tuple[Path, list[str], list[str]]],+) -> set[tuple[Path, tuple[str], tuple[str]]]:+ return cast(+ set[tuple[Path, tuple[str], tuple[str]]],+ set((p, *map(tuple, r)) for p, *r in walked),+ )+++def hashable_walk(path: Path) -> set[tuple[Path, tuple[str], tuple[str]]]:+ return _hashable_walk(walk(path))+++def watch_directory(+ path: Path, state: DirectoryState, should_exit: threading.Event+) -> None:+ """Watch a directory for changes and update the state."""+ last_structure = hashable_walk(path)+ current_structure = last_structure+ sleep_interval = _TEST_SLEEP_INTERVAL or WATCHER_SLEEP_INTERVAL+ while not should_exit.is_set():+ time.sleep(sleep_interval)+ try:+ current_structure = hashable_walk(path)+ except FileNotFoundError:+ # Directory has been deleted, trigger a change+ current_structure = set()+ except Exception as e:+ # Handle other exceptions (e.g., permission denied)+ sys.stderr.write(f"Error watching directory {path}: {e}\n")+ continue++ if current_structure != last_structure:+ last_structure = current_structure+ state._set_value(path)+++class DirectoryState(PathState):+ """Wrapper for directory state."""++ _forbidden_attributes = {+ "open",+ "rename",+ "replace",+ "remove",+ "unlink",+ "write_text",+ "write_bytes",+ "read_text",+ "read_bytes",+ "mkdir",+ "touch",+ }+ _target: Callable[[Path, DirectoryState, threading.Event], None] = (+ staticmethod(watch_directory)+ )++ def walk(self) -> Iterable[tuple[Path, list[str], list[str]]]:+ """Walk the directory."""+ items = walk(self._value)+ as_list = list(_hashable_walk(items))+ write_side_effect(f"walk:{sorted(as_list)}")+ return iter(items)++ def iterdir(self) -> Iterable[Path]:+ """Iterate over the directory."""+ items = list(self._value.iterdir())+ write_side_effect(f"iterdir:{items}")+ return iter(items)++ def glob(self, pattern: str) -> Iterable[Path]:+ """Glob the directory."""+ items = list(self._value.glob(pattern))+ write_side_effect(f"glob:{items}")+ return iter(items)++ def rglob(self, pattern: str) -> Iterable[Path]:+ """Recursive glob the directory."""+ items = list(self._value.rglob(pattern))+ write_side_effect(f"rglob:{items}")+ return iter(items)++ def __repr__(self) -> str:+ """Return a string representation of the file state."""+ _walk = self.walk() # Call to issue side effect+ _hash = hashlib.sha256(f"{list(_walk)}".encode()).hexdigest()+ return f"DirectoryState({self._value}: {_hash})"+++@mddoc+def directory(path: Path | str) -> DirectoryState:+ """+ A reactive wrapper for directory paths.++ This function takes a directory path to watch and returns a wrapper to+ reactively list the contents of the directory.++ This object will trigger dependent cells to re-evaluate when the directory+ structure is changed (i.e., files are added or removed).++ Note:+ This function does NOT react to file content changes, only to changes in+ the directory structure. Utilize `mo.watch.file()` to watch for changes+ in specific files. Additional note: this will not follow symlinks.++ Args:+ path: Path to watch.++ Returns:+ A reactive wrapper for watching the directory.+ """++ if isinstance(path, str):+ path = Path(path)+ if not path.is_dir():+ raise ValueError("Path must be a directory, use mo.file()")+ return DirectoryState(path, allow_self_loops=True)diff --git a/marimo/_runtime/watch/_file.py b/marimo/_runtime/watch/_file.pynew file mode 100644index 0000000000..95f3367e1e--- /dev/null+++ b/marimo/_runtime/watch/_file.py@@ -0,0 +1,148 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import hashlib+import sys+import threading+import time+from pathlib import Path+from typing import Any, Callable++from marimo._output.rich_help import mddoc+from marimo._runtime.watch._path import (+ WATCHER_SLEEP_INTERVAL,+ PathState,+ write_side_effect,+)++# For testing only - do not use in production+_TEST_SLEEP_INTERVAL: float | None = None+++def watch_file(+ path: Path, state: FileState, should_exit: threading.Event+) -> None:+ """Watch a file for changes and update the state."""+ last_mtime: float = 0+ current_mtime = last_mtime+ sleep_interval = _TEST_SLEEP_INTERVAL or WATCHER_SLEEP_INTERVAL+ while not should_exit.is_set():+ time.sleep(sleep_interval)+ try:+ current_mtime = path.stat().st_mtime+ except FileNotFoundError:+ # File has been deleted, trigger a change+ current_mtime = 0+ except Exception as e:+ # Handle other exceptions (e.g., permission denied)+ sys.stderr.write(f"Error watching file {path}: {e}\n")+ continue++ if current_mtime != last_mtime:+ last_mtime = current_mtime+ with state._debounce_lock:+ if not state._debounced:+ state._set_value(path)+ state._debounced = False+++class FileState(PathState):+ """Wrapper for file state."""++ _forbidden_attributes = {+ "open",+ "iterdir",+ "glob",+ "rglob",+ "mkdir",+ "rename",+ "replace",+ "walk",+ }+ _target: Callable[[Path, FileState, threading.Event], None] = staticmethod(+ watch_file+ )++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._debounced = False+ self._debounce_lock = threading.Lock()++ def read_text(self) -> str:+ """Read the file as a string."""+ text = self._value.read_text()+ write_side_effect(f"read_text:{text}")+ return text++ def write_text(self, value: str) -> int:+ """Write the file as a string."""+ response = self._value.write_text(value)+ text = self._value.read_text()+ write_side_effect(f"write_text:{text}")+ with self._debounce_lock:+ self._debounced = True+ self._set_value(self._value)+ return response++ def read_bytes(self) -> bytes:+ """Read the file as bytes."""+ data = self._value.read_bytes()+ write_side_effect(f"read_bytes:{data!r}")+ return data++ def write_bytes(self, value: bytes) -> int:+ """Write the file as bytes."""+ response = self._value.write_bytes(value)+ data = self._value.read_bytes()+ write_side_effect(f"write_bytes:{data!r}")+ with self._debounce_lock:+ self._debounced = True+ self._set_value(self._value)+ return response++ def __repr__(self) -> str:+ """Return a string representation of the file state."""+ if not self._value.exists():+ return f"FileState({self._value}: File not found)"+ _hash = hashlib.sha256(self._value.read_bytes()).hexdigest()+ return f"FileState({self._value}: {_hash})"+++@mddoc+def file(path: Path | str) -> FileState:+ """+ A reactive wrapper for file paths.++ This function takes a file path to watch and returns a wrapper to reactively+ read and write from the file.++ The "wrapped" file Path object exposes most of the same methods as the+ [pathlib.Path object](https://docs.python.org/3/library/pathlib.html#pathlib.Path),+ with a few exceptions. The following methods are not available:++ - `open()`+ - `rename()`+ - `replace()`++ This object will trigger dependent cells to re-evaluate when the file is+ changed.++ Warning:+ It is possible to misuse this API in similar ways to `state()`. Consider+ reading the warning and caveats in the+ [`state()` documentation](../state), and using this function only when+ reading file paths, and not when writing them.++ Args:+ path: Path to watch.++ Returns:+ A reactive wrapper for watching the file path.+ """+ if isinstance(path, str):+ path = Path(path)+ if path.is_dir():+ raise ValueError(+ "Path must be a file, not a directory, use mo.directory() instead"+ )+ return FileState(path, allow_self_loops=True)diff --git a/marimo/_runtime/watch/_path.py b/marimo/_runtime/watch/_path.pynew file mode 100644index 0000000000..589553baed--- /dev/null+++ b/marimo/_runtime/watch/_path.py@@ -0,0 +1,107 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import sys+import threading+from pathlib import Path+from typing import Any, Callable, TypeVar++from marimo._runtime.context import (+ ContextNotInitializedError,+ get_context,+ runtime_context_installed,+)+from marimo._runtime.side_effect import SideEffect+from marimo._runtime.state import State+from marimo._runtime.threads import Thread++if sys.version_info >= (3, 11):+ from typing import Self+else:+ from typing_extensions import Self+++T = TypeVar("T")++WATCHER_SLEEP_INTERVAL = 1.0+++def write_side_effect(data: str | bytes) -> None:+ """Write side effect to the context."""+ try:+ ctx = get_context()+ except ContextNotInitializedError:+ # Context is not initialized, nothing we can do+ return+ ctx.cell_lifecycle_registry.add(SideEffect(data))+++class PathState(State[Path]):+ """Base class for path state."""++ _forbidden_attributes: set[str]+ _target: Callable[[Path, Self, threading.Event], None]++ def __init__(+ self,+ path: Path,+ *args: Any,+ allow_self_loops: bool = True,+ **kwargs: Any,+ ) -> None:+ if kwargs.pop("_context", None) is not None:+ raise ValueError(+ "The '_context' argument is not supported for this class."+ )+ if kwargs.pop("allow_self_loops", None) is not None:+ raise ValueError(+ "The 'allow_self_loops' argument is not supported for this class."+ )++ # Mypy seems to think we could provide multiple kwargs definitions here+ # but we can't.+ super().__init__(+ path,+ *args,+ allow_self_loops=allow_self_loops,+ _context="file",+ **kwargs,+ ) # type: ignore[misc]+ self._should_exit = threading.Event()+ # Only bother with the watcher if the context is installed+ # State is not enabled in script mode+ if runtime_context_installed():+ Thread(+ target=self._target,+ args=(path, self, self._should_exit),+ daemon=True,+ ).start()++ def __getattr__(self, name: str) -> Any:+ """Get an attribute from the file path."""+ # Disable some attributes+ if name in self._forbidden_attributes:+ raise AttributeError(+ f"'{self.__class__.__name__}' does not "+ f"expose attribute '{name}'"+ )+ if hasattr(self._value, name):+ return getattr(self._value, name)+ raise AttributeError(+ f"'{self.__class__.__name__}' object has no attribute '{name}'"+ )++ def __del__(self) -> None:+ self._should_exit.set()++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}({self._value})"++ def exists(self) -> bool:+ """Check if the path exists."""+ exists = self._value.exists()+ if not exists:+ write_side_effect(f"doesn't exists:{self._value}")+ else:+ _ = self.read_text()+ return existsdiff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex 4419674b9e..4e7d543c1d 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -30,6 +30,7 @@ from marimo._runtime.primitives import ()from marimo._runtime.side_effect import SideEffectfrom marimo._runtime.state import SetFunctor, State+from marimo._runtime.watch._path import PathStatefrom marimo._save.cache import Cache, CacheTypefrom marimo._types.ids import CellId_t@@ -261,7 +262,7 @@ def attempt_signed_bytes(value: bytes, label: str) -> bytes:try:return type_sign(common_container_to_bytes(value), label)# Fallback to raw state for eval in content hash.- except TypeError:+ except (TypeError, ValueError):return value@@ -660,7 +661,14 @@ class BlockHasher:if value is not None and (ref not in scope or isinstance(scope[ref], State)):- scope[ref] = attempt_signed_bytes(value(), "state")+ if isinstance(value, PathState):+ # Path state only contains the path as value, it should+ # contain the path contents.+ scope[ref] = attempt_signed_bytes(+ repr(value).encode(), "pathstate"+ )+ else:+ scope[ref] = attempt_signed_bytes(value(), "state")if ctx:for state_name in ctx.state_registry.bound_names(value):scope[state_name] = scope[ref]diff --git a/tests/_runtime/watch/test_watch.py b/tests/_runtime/watch/test_watch.pynew file mode 100644index 0000000000..3eaf79e55c--- /dev/null+++ b/tests/_runtime/watch/test_watch.py@@ -0,0 +1,159 @@+# Copyright 2025 Marimo. All rights reserved.+import asyncio+from pathlib import Path++import pytest++from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++ True, reason="Flaky in CI, can't repro locally", strict=False+)+async def test_read_and_write_path(+ execution_kernel: Kernel, exec_req: ExecReqProvider, tmp_path: Path+) -> None:+ k = execution_kernel+ await k.run(+ [+ exec_req.get("from pathlib import Path"),+ exec_req.get(+ f'tmp = Path("{tmp_path.as_posix()}") / "test.txt"; tmp.write_text("0")'+ ),+ exec_req.get(+ """+ import time+ import marimo as mo+ mo.watch._file._TEST_SLEEP_INTERVAL = 0.05+ """+ ),+ exec_req.get("path = mo.watch.file(tmp)"),+ exec_req.get("x = path.read_text()"),+ exec_req.get(+ """+ x+ if x == "0":+ path.write_text("1")+ """+ ),+ ]+ )+ await asyncio.sleep(0.1)++ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ assert k.globals["x"] == "1"+++ True, reason="Flaky in CI, can't repro locally", strict=False+)+async def test_read_and_write_iteration(+ execution_kernel: Kernel, exec_req: ExecReqProvider, tmp_path: Path+) -> None:+ k = execution_kernel+ await k.run(+ [+ exec_req.get("from pathlib import Path"),+ exec_req.get(+ f'tmp = Path("{tmp_path.as_posix()}") / "test.txt"; tmp.touch()'+ ),+ exec_req.get(+ """+ import asyncio+ import marimo as mo+ mo.watch._file._TEST_SLEEP_INTERVAL = 0.01+ """+ ),+ exec_req.get("path = mo.watch.file(tmp)"),+ exec_req.get("x = path.read_bytes()"),+ exec_req.get(+ """+ x+ if len(x) < 3:+ print("Writing 0")+ path.write_bytes(b"0" * (len(x) + 1))+ """+ ),+ ]+ )+ await asyncio.sleep(0.1)++ assert not k.stderr.messages, k.stderr+ assert k.globals["x"] == b"000"+++ True, reason="Flaky in CI, can't repro locally", strict=False+)+async def test_allow_self_loops(+ execution_kernel: Kernel, exec_req: ExecReqProvider, tmp_path: Path+) -> None:+ k = execution_kernel+ await k.run(+ [+ exec_req.get("from pathlib import Path"),+ exec_req.get(+ """+ import asyncio+ import marimo as mo+ mo.watch._file._TEST_SLEEP_INTERVAL = 0.01+ """+ ),+ exec_req.get(+ f'tmp = Path("{tmp_path.as_posix()}") / "test.txt"; tmp.touch()'+ ),+ exec_req.get("path = mo.watch.file(tmp)"),+ exec_req.get(+ """+ path() # Just returns the path+ x = len(path.read_bytes())+ if x < 3:+ path.write_bytes(b"0" * (x + 1))+ """+ ),+ ]+ )+ await asyncio.sleep(0.1)+ # Flakey in CI 3.13+ await k.run([])++ assert not k.stderr.messages, k.stderr+ assert k.globals["x"] == 3+++ True, reason="Flaky in CI, can't repro locally", strict=False+)+async def test_directory_watch(+ execution_kernel: Kernel, exec_req: ExecReqProvider, tmp_path: Path+) -> None:+ k = execution_kernel+ await k.run(+ [+ exec_req.get("from pathlib import Path"),+ exec_req.get(f'tmp = Path("{tmp_path.as_posix()}")'),+ exec_req.get(+ """+ import time+ import marimo as mo+ mo.watch._directory._TEST_SLEEP_INTERVAL = 0.05+ """+ ),+ exec_req.get("path = mo.watch.directory(tmp)"),+ exec_req.get("x = len(list(path.glob('*')))"),+ exec_req.get(+ """+ x+ if x == 0:+ (tmp / "test.txt").write_text("1")+ """+ ),+ ]+ )+ await asyncio.sleep(0.25)+ await k.run([])++ assert not k.stderr.messages, k.stderr+ assert k.globals["x"] == 1diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 0708d384ec..7215676d2b 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -2,6 +2,7 @@from __future__ import annotations+import asynciofrom typing import Anyimport pytest@@ -1143,3 +1144,177 @@ class TestSideEffects:assert non_primitive[1] == 0assert v == 1assert hashes[0] != hashes[1]++ @staticmethod+ async def test_side_effect_file(+ k: Kernel, exec_req: ExecReqProvider, tmp_path+ ) -> None:+ await k.run(+ [+ exec_req.get(+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'+ ),+ exec_req.get("""+ from tests._save.loaders.mocks import MockLoader+ import marimo as mo+ mo.watch._file._TEST_SLEEP_INTERVAL = 0.01+ from pathlib import Path++ hashes = []+ """),+ exec_req.get("""+ f = mo.watch.file(tmp_path_fixture / "test.txt")+ """),+ ]+ )+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ await k.run(+ [+ exec_req.get("""+ f+ non_primitive = [object(), len(hashes), f.exists()]+ """),+ exec_req.get("""+ with mo.persistent_cache("get_v", save_path=tmp_path_fixture) as v_cache:+ v = non_primitive[1]+ """),+ ]+ )+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ await k.run(+ [+ r := exec_req.get("""+ if len(hashes) < 1:+ assert non_primitive[1] == 0+ hashes.append((v_cache.cache_type, v_cache._cache.hash))+ """),+ ]+ )+ (tmp_path / "test.txt").touch()+ await asyncio.sleep(0.25)+ await k.run([])+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ v = k.globals["v"]+ hashes = k.globals["hashes"]+ non_primitive = k.globals["non_primitive"]+ assert len(hashes) == 2+ assert hashes[0] != hashes[1]+ assert non_primitive[1] == 1 == v++ @staticmethod+ async def test_side_effect_directory(+ k: Kernel, exec_req: ExecReqProvider, tmp_path+ ) -> None:+ await k.run(+ [+ exec_req.get(+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'+ ),+ exec_req.get("""+ from tests._save.loaders.mocks import MockLoader+ import marimo as mo+ mo.watch._directory._TEST_SLEEP_INTERVAL = 0.01+ from pathlib import Path++ hashes = []+ """),+ exec_req.get("""+ (tmp_path_fixture / "test_dir").mkdir(parents=True, exist_ok=True)+ d = mo.watch.directory(tmp_path_fixture / "test_dir")+ """),+ ]+ )+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ await k.run(+ [+ exec_req.get("""+ non_primitive = [object(), len(hashes), d.glob("*")]+ """),+ exec_req.get("""+ with mo.persistent_cache("get_v", save_path=tmp_path_fixture) as v_cache:+ v = non_primitive[1]+ """),+ ]+ )+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ await k.run(+ [+ r := exec_req.get("""+ if len(hashes) < 1:+ assert non_primitive[1] == 0+ hashes.append((v_cache.cache_type, v_cache._cache.hash))+ """),+ ]+ )+ (tmp_path / "test_dir" / "test.txt").write_text("test")+ await asyncio.sleep(0.25)+ await k.run([])+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ v = k.globals["v"]+ hashes = k.globals["hashes"]+ non_primitive = k.globals["non_primitive"]+ assert len(hashes) == 2+ assert hashes[0] != hashes[1]+ assert non_primitive[1] == 1 == v++ @staticmethod+ async def test_side_effect_file_ref(+ k: Kernel, exec_req: ExecReqProvider, tmp_path+ ) -> None:+ await k.run(+ [+ exec_req.get(+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'+ ),+ exec_req.get("""+ from tests._save.loaders.mocks import MockLoader+ import marimo as mo+ from pathlib import Path++ hashes = []+ """),+ exec_req.get(+ 'u = mo.watch.file(tmp_path_fixture / "test.txt")'+ ),+ exec_req.get("""+ non_primitive = [object(), len(hashes)]+ with mo.cache("prim") as prim_cache:+ # unused, but should trigger side effect+ u+ """),+ exec_req.get("""+ with mo.persistent_cache("get_v", save_path=tmp_path_fixture) as v_cache:+ v = non_primitive[1]+ """),+ ]+ )+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ await k.run(+ [+ exec_req.get("""+ if len(hashes) < 1:+ assert non_primitive[1] == 0+ u.write_text("test")+ hashes.append((v_cache.cache_type, v_cache._cache.hash))+ hashes.append((prim_cache.cache_type, prim_cache._cache.hash))+ """),+ ]+ )+ assert not k.stdout.messages, k.stdout+ assert not k.stderr.messages, k.stderr+ v = k.globals["v"]+ hashes = k.globals["hashes"]+ non_primitive = k.globals["non_primitive"]+ # Docs warn not to use write directly since RC can occur, causing double+ # event.+ assert len(hashes) == 4+ assert hashes[1] != hashes[3]+ assert hashes[0] != hashes[2]+ assert non_primitive[1] == 2 == vdiff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex aa6bc64abd..33058f6d25 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -114,4 +114,7 @@ uitexttext_areavideo-vstack\ No newline at end of file+vstack+watch+ directory+ file\ No newline at end of file