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: drop stale autosaves after newer foreground writes (#9239)
Junghwan4091e040284d
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.pyindex cb805457a1..b5b4129ec9 100644--- a/marimo/_session/extensions/extensions.py+++ b/marimo/_session/extensions/extensions.py@@ -294,7 +294,10 @@ class NotificationListenerExtension(SessionExtension):if self.kernel_manager.mode != SessionMode.EDIT:return- if session.app_file_manager.path is None:+ expected_filename, expected_generation = (+ session.app_file_manager.capture_autosave_target()+ )+ if expected_filename is None:if not self._unnamed_autosave_logged:LOGGER.debug("Skipping code_mode auto-save for unnamed notebook"@@ -311,7 +314,12 @@ class NotificationListenerExtension(SessionExtension):)self._autosave_runner.submit(- partial(session.app_file_manager.save_from_cells, cells_snapshot),+ partial(+ session.app_file_manager.save_from_cells,+ cells_snapshot,+ expected_filename=expected_filename,+ expected_generation=expected_generation,+ ),on_error=partial(self._post_autosave_failure, session),)diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.pyindex 2c14c09299..bf577c7936 100644--- a/marimo/_session/notebook/file_manager.py+++ b/marimo/_session/notebook/file_manager.py@@ -80,6 +80,8 @@ class AppFileManager:# can wrap the full "mutate app + _save_file" sequence while# ``_save_file`` re-acquires for any direct caller.self._save_lock = threading.RLock()+ # Foreground writes supersede queued autosaves.+ self._autosave_generation = 0@propertydef filename(self) -> str | None:@@ -306,6 +308,7 @@ class AppFileManager:return new_path.nameself._assert_path_does_not_exist(new_path)+ self._invalidate_autosaves()if self._filename is not None:self.storage.rename(self._filename, new_path)@@ -384,6 +387,7 @@ class AppFileManager:with self._save_lock:self.app.update_config(config)if self._filename is not None:+ self._invalidate_autosaves()return self._save_file(self._filename,notebook=self.app.to_ir(),@@ -443,13 +447,25 @@ class AppFileManager:# Remove the layout from the configself.app.update_config({"layout_file": None})+ if request.persist:+ self._invalidate_autosaves()return self._save_file(filename_path,notebook=self.app.to_ir(),persist=request.persist,)- def save_from_cells(self, cells: Sequence[NotebookCell]) -> str:+ def capture_autosave_target(self) -> tuple[Path | None, int]:+ with self._save_lock:+ return self._filename, self._autosave_generation++ def save_from_cells(+ self,+ cells: Sequence[NotebookCell],+ *,+ expected_filename: Path | None = None,+ expected_generation: int | None = None,+ ) -> str:"""Persist the notebook from a snapshot of document cells.Used by the server-side auto-save path for ``code_mode``@@ -467,6 +483,15 @@ class AppFileManager:)with self._save_lock:+ if expected_generation is not None:+ if expected_generation != self._autosave_generation:+ return ""+ if expected_filename is not None:+ if self._filename is None or not self._is_same_path(+ expected_filename+ ):+ return ""+self.app.with_data(cell_ids=[cell.id for cell in cells],codes=[cell.code for cell in cells],@@ -479,6 +504,9 @@ class AppFileManager:persist=True,)+ def _invalidate_autosaves(self) -> None:+ self._autosave_generation += 1+def copy(self, request: CopyNotebookRequest) -> str:"""Copy a notebook file.diff --git a/tests/_session/extensions/test_notification_listener_autosave.py b/tests/_session/extensions/test_notification_listener_autosave.pyindex fbaf837970..852b20c295 100644--- a/tests/_session/extensions/test_notification_listener_autosave.py+++ b/tests/_session/extensions/test_notification_listener_autosave.py@@ -26,6 +26,7 @@ from marimo._messaging.notification import ()from marimo._messaging.serde import serialize_kernel_messagefrom marimo._messaging.types import KernelMessage+from marimo._server.models.models import SaveNotebookRequestfrom marimo._session.extensions.extensions import (NotificationListenerExtension,)@@ -430,9 +431,9 @@ class TestCellSnapshotIsolation:received: list[list[NotebookCell]] = []real_save = session.app_file_manager.save_from_cells- def _capture(cells: list[NotebookCell]) -> str:+ def _capture(cells: list[NotebookCell], **kwargs: object) -> str:received.append(list(cells))- return real_save(cells)+ return real_save(cells, **kwargs)session.app_file_manager.save_from_cells = _capture # type: ignore[method-assign]@@ -470,9 +471,9 @@ class TestCellSnapshotIsolation:received: list[list[NotebookCell]] = []real_save = session.app_file_manager.save_from_cells- def _capture(cells: list[NotebookCell]) -> str:+ def _capture(cells: list[NotebookCell], **kwargs: object) -> str:received.append(list(cells))- return real_save(cells)+ return real_save(cells, **kwargs)session.app_file_manager.save_from_cells = _capture # type: ignore[method-assign]@@ -514,3 +515,51 @@ class TestLayoutPreservation:app_file_manager.app.config.layout_file== "layouts/with_layout.grid.json")+++class TestAutosaveOrdering:+ """Queued autosaves must not clobber newer foreground save state."""++ def test_stale_autosave_does_not_clobber_newer_rename_and_save(+ self,+ ext: NotificationListenerExtension,+ session: Mock,+ app_file_manager: AppFileManager,+ existing_cell_id: CellId_t,+ notebook_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ queued_work: list[tuple[object, object | None]] = []++ def _capture_submit(+ work: object, *, on_error: object | None = None+ ) -> None:+ queued_work.append((work, on_error))++ monkeypatch.setattr(ext._autosave_runner, "submit", _capture_submit)++ ext._on_kernel_message(+ session,+ _serialize_tx(SetCode(cell_id=existing_cell_id, code="old = 1")),+ )+ assert len(queued_work) == 1++ renamed_path = notebook_path.with_name("renamed_after_autosave.py")+ app_file_manager.rename(str(renamed_path))+ app_file_manager.save(+ SaveNotebookRequest(+ cell_ids=[existing_cell_id],+ filename=str(renamed_path),+ codes=["new = 2"],+ names=[""],+ configs=[CellConfig()],+ )+ )++ work, _on_error = queued_work.pop()+ assert callable(work)+ work()++ contents = renamed_path.read_text()+ assert "new = 2" in contents+ assert "old = 1" not in contents