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: track contents to avoid reloading on our own writes (#7099)
Myles Scolnick1067a0674913
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex dc787b4bb1..e1074dafe5 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -47,6 +47,8 @@ class AppFileManager:)self._default_sql_output: SqlOutputType | None = default_sql_outputself.app = self._load_app(self.path)+ # Track the last saved content to avoid reloading our own writes+ self._last_saved_content: Optional[str] = None@staticmethoddef from_app(app: InternalApp) -> AppFileManager:@@ -128,6 +130,7 @@ class AppFileManager:def _save_file(self,filename: str,+ *,notebook: NotebookSerializationV1,# Whether or not to persist the app to the file systempersist: bool,@@ -180,6 +183,8 @@ class AppFileManager:if persist:self._create_file(filename, contents)+ # Record the last saved content to avoid reloading our own writes+ self._last_saved_content = contents.strip()if self._is_unnamed():self.rename(filename)@@ -241,7 +246,7 @@ class AppFileManager:if needs_save:self._save_file(self.filename,- self.app.to_ir(),+ notebook=self.app.to_ir(),persist=True,previous_filename=previous_filename,)@@ -286,7 +291,7 @@ class AppFileManager:if self.filename is not None:return self._save_file(self.filename,- self.app.to_ir(),+ notebook=self.app.to_ir(),persist=True,)return ""@@ -330,7 +335,7 @@ class AppFileManager:self.app.update_config({"layout_file": None})return self._save_file(filename,- self.app.to_ir(),+ notebook=self.app.to_ir(),persist=request.persist,)@@ -360,6 +365,26 @@ class AppFileManager:)return Path(self.filename).read_text(encoding="utf-8")+ def file_content_matches_last_save(self) -> bool:+ """Check if the current file content matches the last saved content.++ This is used to avoid reloading the file when we detect our own writes.++ Returns:+ bool: True if the file content matches the last save, False otherwise.+ """+ if self.filename is None or self._last_saved_content is None:+ return False++ try:+ current_content = Path(self.filename).read_text(encoding="utf-8")+ return current_content.strip() == self._last_saved_content+ except Exception as e:+ LOGGER.debug(+ f"Error reading file to check if content matches: {e}"+ )+ return False+def read_css_file(css_file: str, filename: Optional[str]) -> Optional[str]:"""Read the contents of a CSS file.diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 4335d1173a..9b9183d2a8 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -1186,6 +1186,14 @@ class SessionFileChangeHandler:) -> None:LOGGER.debug(f"{file_path} was modified, handling {session}")+ # Check if the file content matches the last save+ # to avoid reloading our own writes+ if session.app_file_manager.file_content_matches_last_save():+ LOGGER.debug(+ f"File {file_path} content matches last save, skipping reload"+ )+ return+# Reload the file manager to get the latest codetry:changed_cell_ids = session.app_file_manager.reload()diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex e29257e0ee..d659446629 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -793,3 +793,63 @@ if __name__ == "__main__":deleted_cell_ids = set(original_cell_ids) - set(reloaded_cell_ids)assert len(deleted_cell_ids) == 2assert deleted_cell_ids.issubset(changed_cell_ids)+++def test_file_content_matches_last_save(tmp_path: Path) -> None:+ """Test that file_content_matches_last_save correctly identifies own writes."""+ # Create a temporary file+ temp_file = tmp_path / "test_match_save.py"+ temp_file.write_text(+ """+import marimo+app = marimo.App()++def cell1():+ x = 1+ return x++if __name__ == "__main__":+ app.run()+"""+ )++ # Initialize AppFileManager+ manager = AppFileManager(filename=str(temp_file))++ # Initially, no save has been made by the manager+ assert manager.file_content_matches_last_save() is False++ # Save the file+ manager.save(+ SaveNotebookRequest(+ cell_ids=[CellId_t("1")],+ filename=str(temp_file),+ codes=["x = 1"],+ names=["cell1"],+ configs=[CellConfig()],+ persist=True,+ )+ )++ # Now the file should match the last save+ assert manager.file_content_matches_last_save() is True++ # Externally modify the file+ temp_file.write_text(+ """+import marimo+app = marimo.App()++def cell1():+ x = 2 # Changed+ return x++if __name__ == "__main__":+ app.run()+"""+ )++ # Now the file should not match the last save+ assert manager.file_content_matches_last_save() is False