Skip to content

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.

feat: file watcher in run mode (--watch) (#722)

Myles Scolnickb30cf9515cf3
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index d3c1737c9e..ba90705c7d 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -16,6 +16,7 @@ jobs:
test_frontend:
name: 🖥️ Lint, test, build frontend
runs-on: ubuntu-latest
+ timeout-minutes: 10
defaults:
run:
working-directory: ./frontend
@@ -65,6 +66,7 @@ jobs:
test_python:
name: Tests on ${{ matrix.os }}, Python ${{ matrix.python-version }}
runs-on: ${{ matrix.os }}
+ timeout-minutes: 10
defaults:
run:
shell: bash
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index ccaee61bba..1cbd111e9d 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -212,6 +212,9 @@ export type OperationMessage =
| {
op: "completed-run";
}
+ | {
+ op: "reload";
+ }
| {
op: "interrupted";
}
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 319c09f487..ed85150ab5 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -53,6 +53,9 @@ export function useMarimoWebSocket(opts: {
const handleMessage = (e: MessageEvent<string>) => {
const msg = jsonParseWithSpecialChar<OperationMessage>(e.data);
switch (msg.op) {
+ case "reload":
+ window.location.reload();
+ return;
case "kernel-ready": {
const {
codes,
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index e57ea379aa..e2cc62e848 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -223,6 +223,7 @@ def edit(
filename=name,
mode=SessionMode.EDIT,
include_code=True,
+ watch=False,
)
@@ -268,6 +269,18 @@ Example:
type=bool,
help="Include notebook code in the app.",
)
+ "--watch",
+ is_flag=True,
+ default=False,
+ show_default=True,
+ type=bool,
+ help="""
+ Watch the file for changes and reload the app.
+ If watchdog is installed, it will be used to watch the file.
+ Otherwise, file watcher will poll the file every 1s.
+ """,
+)
@click.option(
"--base-url",
default="",
@@ -282,6 +295,7 @@ def run(
host: str,
headless: bool,
include_code: bool,
+ watch: bool,
name: str,
base_url: str,
) -> None:
@@ -303,6 +317,7 @@ def run(
filename=name,
mode=SessionMode.RUN,
include_code=include_code,
+ watch=watch,
base_url=base_url,
)
@@ -422,6 +437,7 @@ def tutorial(
filename=fname,
include_code=True,
headless=headless,
+ watch=False,
)
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index b0b6042039..cbcd61bd65 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -106,3 +106,8 @@ class DependencyManager:
def has_plotly() -> bool:
"""Return True if plotly is installed."""
return importlib.util.find_spec("plotly") is not None
+
+ @staticmethod
+ def has_watchdog() -> bool:
+ """Return True if watchdog is installed."""
+ return importlib.util.find_spec("watchdog") is not None
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 469bc8b7ed..06e29a1412 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -301,6 +301,11 @@ class Banner(Op):
action: Optional[Literal["restart"]] = None
+@dataclass
+class Reload(Op):
+ name: ClassVar[str] = "reload"
+
+
@dataclass
class VariableDeclaration:
name: str
@@ -364,6 +369,7 @@ class VariableValues(Op):
MessageOperation = Union[
CellOp,
HumanReadableStatus,
+ Reload,
Reconnected,
FunctionCallResult,
RemoveUIElements,
diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.py
index 9f92b2b580..34d78d4e10 100644
--- a/marimo/_server/api/lifespans.py
+++ b/marimo/_server/api/lifespans.py
@@ -100,6 +100,15 @@ async def lsp(app: Starlette) -> AsyncIterator[None]:
yield
+async def watcher(app: Starlette) -> AsyncIterator[None]:
+ watch: bool = app.state.watch
+ if watch:
+ session_mgr = get_manager()
+ session_mgr.start_file_watcher()
+ yield
+
+
@contextlib.asynccontextmanager
async def open_browser(app: Starlette) -> AsyncIterator[None]:
host = app.state.host
@@ -165,5 +174,13 @@ async def etc(app: Starlette) -> AsyncIterator[None]:
LIFESPANS = Lifespans(
- [user_configuration, lsp, etc, signal_handler, logging, open_browser]
+ [
+ user_configuration,
+ lsp,
+ watcher,
+ etc,
+ signal_handler,
+ logging,
+ open_browser,
+ ]
)
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index db1d02878a..b7d62207c2 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -23,6 +23,7 @@ import sys
import threading
from multiprocessing import connection
from multiprocessing.queues import Queue as MPQueue
+from pathlib import Path
from typing import Any, Optional
from uuid import uuid4
@@ -30,7 +31,7 @@ from marimo import _loggers
from marimo._ast import codegen
from marimo._ast.app import App, InternalApp
from marimo._ast.cell import CellConfig, CellId_t
-from marimo._messaging.ops import Alert, MessageOperation
+from marimo._messaging.ops import Alert, MessageOperation, Reload
from marimo._messaging.types import KernelMessage
from marimo._output.formatters.formatters import register_formatters
from marimo._runtime import requests, runtime
@@ -43,7 +44,9 @@ from marimo._server.model import (
from marimo._server.session.session_view import SessionView
from marimo._server.types import QueueType
from marimo._server.utils import import_files, print_tabbed
+from marimo._utils.disposable import Disposable
from marimo._utils.distributor import Distributor
+from marimo._utils.file_watcher import FileWatcher
from marimo._utils.repr import format_repr
from marimo._utils.typed_connection import TypedConnection
@@ -354,12 +357,13 @@ class SessionManager:
self.sessions: dict[str, Session] = {}
self.include_code = include_code
self.lsp_server = lsp_server
+ self.watcher: Optional[FileWatcher] = None
app = self.load_app()
self.app_config = app.config
self.app_metadata = AppMetadata(
- filename=self._get_filename(),
+ filename=self._get_file_path(),
)
if mode == SessionMode.EDIT:
@@ -401,7 +405,7 @@ class SessionManager:
or opened another file.
"""
self.filename = filename
- self.app_metadata.filename = self._get_filename()
+ self.app_metadata.filename = self._get_file_path()
def create_session(
self, session_id: SessionId, session_consumer: SessionConsumer
@@ -471,7 +475,7 @@ class SessionManager:
)
return None
- def _get_filename(self) -> Optional[str]:
+ def _get_file_path(self) -> Optional[str]:
if self.filename is None:
return None
try:
@@ -520,11 +524,40 @@ class SessionManager:
LOGGER.debug("Shutting down")
self.close_all_sessions()
self.lsp_server.stop()
+ if self.watcher:
+ self.watcher.stop()
def should_send_code_to_frontend(self) -> bool:
"""Returns True if the server can send messages to the frontend."""
return self.mode == SessionMode.EDIT or self.include_code
+ def start_file_watcher(self) -> Disposable:
+ """Starts the file watcher if it is not already started"""
+ if self.mode == SessionMode.EDIT:
+ # We don't support file watching in edit mode yet
+ # as there are some edge cases that would need to be handled.
+ # - what to do if the file is deleted, or is renamed
+ # - do we re-run the app or just show the changed code
+ # - we don't properly handle saving from the frontend
+ LOGGER.warn("Cannot start file watcher in edit mode")
+ return Disposable.empty()
+
+ file_path = self._get_file_path()
+ if file_path is None:
+ LOGGER.warn("Cannot start file watcher without a filename")
+ return Disposable.empty()
+
+ async def on_file_changed(path: Path) -> None:
+ LOGGER.debug(f"{path} was modified")
+ for _, session in self.sessions.items():
+ session.app = self.load_app()
+ await session.write_operation(Reload())
+
+ LOGGER.debug("Starting file watcher for %s", file_path)
+ self.watcher = FileWatcher.create(Path(file_path), on_file_changed)
+ self.watcher.start()
+ return Disposable(self.watcher.stop)
+
class LspServer:
def __init__(self, port: int) -> None:
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index 7c3d3ceac9..9bcb917cdf 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -18,6 +18,7 @@ DEFAULT_PORT = 2718
def start(
+ *,
filename: Optional[str],
mode: SessionMode,
development_mode: bool,
@@ -26,6 +27,7 @@ def start(
headless: bool,
port: Optional[int],
host: str,
+ watch: bool,
base_url: str = "",
) -> None:
"""
@@ -52,6 +54,7 @@ def start(
app.state.headless = headless
app.state.port = port
app.state.host = host or "localhost"
+ app.state.watch = watch
app.state.session_manager = session_manager
app.state.base_url = base_url
app.state.user_config = get_configuration()
diff --git a/marimo/_utils/file_watcher.py b/marimo/_utils/file_watcher.py
new file mode 100644
index 0000000000..8cf44b615c
--- /dev/null
+++ b/marimo/_utils/file_watcher.py
@@ -0,0 +1,121 @@
+# Copyright 2024 Marimo. All rights reserved.
+import asyncio
+import os
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import Any, Callable, Coroutine, Optional
+
+from marimo._ast.app import LOGGER
+from marimo._dependencies.dependencies import DependencyManager
+
+Callback = Callable[[Path], Coroutine[None, None, None]]
+
+
+class FileWatcher(ABC):
+ @staticmethod
+ def create(path: Path, callback: Callback) -> "FileWatcher":
+ if DependencyManager.has_watchdog():
+ LOGGER.debug("Using watchdog file watcher")
+ return _create_watchdog(path, callback, asyncio.get_event_loop())
+ else:
+ LOGGER.warning(
+ "watchdog is not installed, using polling file watcher"
+ )
+ return PollingFileWatcher(path, callback, asyncio.get_event_loop())
+
+ def __init__(
+ self,
+ path: Path,
+ callback: Callback,
+ ):
+ self.path = path
+ self.callback = callback
+
+ async def on_file_changed(self) -> None:
+ LOGGER.debug(f"File at {self.path} was modified.")
+ await self.callback(self.path)
+
+ @abstractmethod
+ def start(self) -> None:
+ pass
+
+ @abstractmethod
+ def stop(self) -> None:
+ pass
+
+
+class PollingFileWatcher(FileWatcher):
+ POLL_SECONDS = 1.0 # Poll every 1s
+
+ def __init__(
+ self,
+ path: Path,
+ callback: Callback,
+ loop: asyncio.AbstractEventLoop,
+ ):
+ super().__init__(path, callback)
+ self._running = False
+ self.loop = loop
+ self.last_modified: Optional[float] = None
+
+ def start(self) -> None:
+ self._running = True
+ self.loop.create_task(self._poll())
+
+ def stop(self) -> None:
+ self._running = False
+
+ async def _poll(self) -> None:
+ while self._running:
+ if not os.path.exists(self.path):
+ LOGGER.warning(f"File at {self.path} does not exist.")
+ raise FileNotFoundError(f"File at {self.path} does not exist.")
+
+ # Check for file changes
+ modified = os.path.getmtime(self.path)
+ if self.last_modified is None:
+ self.last_modified = modified
+ elif modified != self.last_modified:
+ self.last_modified = modified
+ await self.on_file_changed()
+ await asyncio.sleep(self.POLL_SECONDS)
+
+
+def _create_watchdog(
+ path: Path, callback: Callback, loop: asyncio.AbstractEventLoop
+) -> FileWatcher:
+ import watchdog.events # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ import watchdog.observers # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+
+ class WatchdogFileWatcher(FileWatcher):
+ def __init__(
+ self,
+ path: Path,
+ callback: Callback,
+ loop: asyncio.AbstractEventLoop,
+ ):
+ super().__init__(path, callback)
+ self.loop = loop
+ self.observer = watchdog.observers.Observer()
+
+ def on_modified(self, event: Any) -> None:
+ del event
+ self.loop.create_task(self.on_file_changed())
+
+ def start(self) -> None:
+ event_handler = watchdog.events.PatternMatchingEventHandler(
+ patterns=[str(self.path)]
+ )
+ event_handler.on_modified = self.on_modified
+ self.observer.schedule(
+ event_handler,
+ str(self.path.parent),
+ recursive=False,
+ )
+ self.observer.start()
+
+ def stop(self) -> None:
+ self.observer.stop()
+ self.observer.join()
+
+ return WatchdogFileWatcher(path, callback, loop)
diff --git a/pyproject.toml b/pyproject.toml
index 7b3deb2a4a..1a0b35742b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -78,6 +78,7 @@ dev = [
"polars==0.19.12",
"pytest~=7.4.0",
"pytest-codecov~=0.5.1",
+ "pytest-asyncio~=0.23.4",
"mypy~=1.7.0",
"ruff~=0.0.275",
"typos~=1.17.1",
@@ -99,7 +100,8 @@ testcore = [
# for server testing
"httpx~=0.26.0",
"pytest~=7.4.0",
- "pytest-codecov~=0.5.1"
+ "pytest-codecov~=0.5.1",
+ "pytest-asyncio~=0.23.4",
]
testoptional = [
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index d0169f8bdb..7755c8ecd3 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -7,15 +7,15 @@ from marimo._plugins.ui._impl.table import (
_normalize_data,
)
from marimo._plugins.ui._impl.utils.dataframe import TableData
-from marimo._runtime.runtime import ExecutionContext
-from tests.conftest import MockedKernel
+from marimo._runtime.runtime import Kernel
-def test_normalize_data() -> None:
- # Create kernel and give the execution context an existing cell
- mocked = MockedKernel()
- mocked.k.execution_context = ExecutionContext("test_cell_id", False)
+def test_normalize_data(executing_kernel: Kernel) -> None:
+ # unused, except for the side effect of giving the kernel an execution
+ # context
+ del executing_kernel
+ # Create kernel and give the execution context an existing cell
data: TableData
# Test with list of integers
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index e00dc6d775..92c2423ad2 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from pathlib import Path
from typing import Any, Optional
import pytest
@@ -8,7 +9,9 @@ from starlette.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from marimo._messaging.ops import KernelReady
+from marimo._server.model import SessionMode
from marimo._utils.parse_dataclass import parse_raw
+from tests._server.conftest import get_session_manager
def create_response(
@@ -117,3 +120,24 @@ def test_fails_on_multiple_connections_with_other_sessions(
assert exc_info.value.code == 1003
assert exc_info.value.reason == "MARIMO_ALREADY_CONNECTED"
client.post("/api/kernel/shutdown", headers=HEADERS)
+
+
+async def test_file_watcher_calls_reload(client: TestClient) -> None:
+ session_manager = get_session_manager(client)
+ with client.websocket_connect("/ws?session_id=123") as websocket:
+ data = websocket.receive_json()
+ assert_kernel_ready_response(data)
+ session_manager.mode = SessionMode.RUN
+ unsubscribe = session_manager.start_file_watcher()
+ assert session_manager.filename
+ with open(session_manager.filename, "a") as f:
+ f.write("\n# test")
+ f.close()
+ assert session_manager.watcher
+ await session_manager.watcher.callback(Path(session_manager.filename))
+ unsubscribe()
+ data = websocket.receive_json()
+ assert data == {"op": "reload", "data": {}}
+ session_manager.mode = SessionMode.EDIT
+ client.post("/api/kernel/shutdown", headers=HEADERS)
diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.py
index 20c604373d..49196f0414 100644
--- a/tests/_server/api/test_middleware.py
+++ b/tests/_server/api/test_middleware.py
@@ -2,7 +2,6 @@
import uvicorn
from starlette.testclient import TestClient
-from marimo import __version__
from marimo._config.config import get_configuration
from marimo._server.main import create_starlette_app
from tests._server.mocks import get_mock_session_manager
diff --git a/tests/_utils/test_file_watcher.py b/tests/_utils/test_file_watcher.py
new file mode 100644
index 0000000000..78e4e562a8
--- /dev/null
+++ b/tests/_utils/test_file_watcher.py
@@ -0,0 +1,44 @@
+# Test for PollingFileWatcher
+import asyncio
+import os
+from pathlib import Path
+from tempfile import NamedTemporaryFile
+from typing import List
+
+import pytest
+
+from marimo._utils.file_watcher import PollingFileWatcher
+
+
+async def test_polling_file_watcher():
+ with NamedTemporaryFile(delete=False) as tmp_file:
+ tmp_path = Path(tmp_file.name)
+
+ callback_calls: List[Path] = []
+
+ async def test_callback(path: Path):
+ return callback_calls.append(path)
+
+ PollingFileWatcher.POLL_SECONDS = 0.1
+
+ # Create
+ loop = asyncio.get_event_loop()
+ watcher = PollingFileWatcher(tmp_path, test_callback, loop)
+ watcher.start()
+
+ # Wait a bit and then modify the file
+ await asyncio.sleep(0.2)
+ with open(tmp_path, "w") as f:
+ f.write("modification")
+
+ # Wait for the watcher to detect the change
+ await asyncio.sleep(0.2)
+
+ # Stop / cleanup
+ watcher.stop()
+ os.remove(tmp_path)
+
+ # Assert that the callback was called
+ assert len(callback_calls) == 1
+ assert callback_calls[0] == tmp_path
diff --git a/tests/conftest.py b/tests/conftest.py
index 38d9ec132e..a21028b9d3 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -69,6 +69,8 @@ class MockStdin(Stdin):
@dataclasses.dataclass
class MockedKernel:
+ """Should only be created in fixtures b/c inits a runtime context"""
+
stream: _MockStream = dataclasses.field(default_factory=_MockStream)
def __post_init__(self) -> None:
@@ -92,9 +94,11 @@ class MockedKernel:
stream=self.stream, # type: ignore
)
- def __del__(self) -> None:
- # have to teardown the runtime context because it's a global
+ def teardown(self):
+ # must be called by fixtures that instantiate this
teardown_context()
+ self.stdout._watcher.stop()
+ self.stderr._watcher.stop()
# fixture that provides a kernel (and tears it down)
@@ -102,6 +106,7 @@ class MockedKernel:
def k() -> Generator[Kernel, None, None]:
mocked = MockedKernel()
yield mocked.k
+ mocked.teardown()
# fixture that wraps a kernel and other mocked objects
@@ -109,6 +114,7 @@ def k() -> Generator[Kernel, None, None]:
def mocked_kernel() -> Generator[MockedKernel, None, None]:
mocked = MockedKernel()
yield mocked
+ mocked.teardown()
# Installs an execution context without stream redirection
@@ -120,6 +126,7 @@ def executing_kernel() -> Generator[Kernel, None, None]:
mocked.k.stdin = None
with mocked.k._install_execution_context(cell_id="0"):
yield mocked.k
+ mocked.teardown()
# Factory to create ExecutionRequests and abstract away cell ID