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.

enhancement : Avoid bumping __generated_with when that's the only change in a notebook (#10011) (#10027)

Yair Chuchem9df728ac6c57
diff --git a/marimo/_lint/linter.py b/marimo/_lint/linter.py
index 43d9fbe379..cbdb8fe93e 100644
--- a/marimo/_lint/linter.py
+++ b/marimo/_lint/linter.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
-import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING
@@ -17,6 +16,9 @@ from marimo._lint.rule_engine import EarlyStoppingConfig, RuleEngine
from marimo._loggers import capture_output
from marimo._schemas.serialization import NotebookSerialization
from marimo._utils import async_path
+from marimo._utils.generated_with import (
+ contents_differ_excluding_generated_with,
+)
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Callable, Iterator
@@ -25,24 +27,6 @@ if TYPE_CHECKING:
from marimo._lint.rules.base import LintRule
-def contents_differ_excluding_generated_with(
- original: str, generated: str
-) -> bool:
- """Compare file contents while ignoring __generated_with differences.
-
- This prevents unnecessary file writes when only the __generated_with
- version metadata differs between the original and generated content.
- """
- # Regex to match the __generated_with line
- pattern = r"^__generated_with = .*$"
-
- # Remove __generated_with lines from both contents
- orig_cleaned = re.sub(pattern, "", original, flags=re.MULTILINE).strip()
- gen_cleaned = re.sub(pattern, "", generated, flags=re.MULTILINE).strip()
-
- return orig_cleaned != gen_cleaned
-
-
async def _to_async_iterator(
files_to_check: AsyncIterator[Path] | Iterator[Path],
) -> AsyncIterator[Path]:
diff --git a/marimo/_lint/rules/formatting/markdown_dedent.py b/marimo/_lint/rules/formatting/markdown_dedent.py
index 2e354ec3ca..1d6577ce0f 100644
--- a/marimo/_lint/rules/formatting/markdown_dedent.py
+++ b/marimo/_lint/rules/formatting/markdown_dedent.py
@@ -69,7 +69,7 @@ class MarkdownDedentRule(LintRule):
async def check(self, ctx: RuleContext) -> None:
"""Check for markdown cells with indented content."""
- from marimo._lint.linter import (
+ from marimo._utils.generated_with import (
contents_differ_excluding_generated_with,
)
diff --git a/marimo/_session/file_change_handler.py b/marimo/_session/file_change_handler.py
index 096b2a958b..280507f400 100644
--- a/marimo/_session/file_change_handler.py
+++ b/marimo/_session/file_change_handler.py
@@ -247,7 +247,11 @@ class FileChangeCoordinator:
# mutates the existing document in place via ``apply()`` and
# returns the stamped transaction, so we just relay it.
try:
- transaction, changed_cell_ids = session.app_file_manager.reload()
+ transaction, changed_cell_ids = (
+ session.app_file_manager.reload_and_mark_content_as_last_save(
+ current_content
+ )
+ )
except Exception as e:
# If there are syntax errors, we just skip
# and don't send the changes
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index 5bf6df5fee..d53b577507 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -27,6 +27,9 @@ from marimo._session.notebook.storage import (
StorageInterface,
)
from marimo._types.ids import CellId_t
+from marimo._utils.generated_with import (
+ contents_differ_excluding_generated_with,
+)
from marimo._utils.http import HTTPException, HTTPStatus
from marimo._utils.marimo_path import MarimoPath
from marimo._utils.scripts import with_python_version_requirement
@@ -155,6 +158,15 @@ class AppFileManager:
return transaction, changed_cell_ids
+ def reload_and_mark_content_as_last_save(
+ self, content: str | None
+ ) -> tuple[Transaction, set[CellId_t]]:
+ with self._save_lock:
+ result = self.reload()
+ if content is not None:
+ self._mark_content_as_last_save(content)
+ return result
+
def _is_same_path(self, path: Path) -> bool:
"""Check if the given path is the same as the current filename.
@@ -244,9 +256,11 @@ class AppFileManager:
contents = handler.serialize(notebook)
if persist:
+ if self.content_matches_last_save(contents):
+ return self._last_saved_content or contents
self.storage.write(path, contents)
# Record the last saved content to avoid reloading our own writes
- self._last_saved_content = contents.strip()
+ self._mark_content_as_last_save(contents)
# If this is a new unnamed notebook, update the filename
if self._is_unnamed():
@@ -595,6 +609,9 @@ class AppFileManager:
)
return self.storage.read(self._filename)
+ def _mark_content_as_last_save(self, content: str) -> None:
+ self._last_saved_content = content.strip()
+
def content_matches_last_save(self, content: str) -> bool:
"""Check if the given content matches the last save.
@@ -604,7 +621,11 @@ class AppFileManager:
"""
if self._last_saved_content is None:
return False
- return content.strip() == self._last_saved_content
+ if content.strip() == self._last_saved_content:
+ return True
+ return not contents_differ_excluding_generated_with(
+ content, self._last_saved_content
+ )
def file_content_matches_last_save(self) -> bool:
"""Check if current file content matches the last save.
diff --git a/marimo/_utils/generated_with.py b/marimo/_utils/generated_with.py
new file mode 100644
index 0000000000..4d596ca65a
--- /dev/null
+++ b/marimo/_utils/generated_with.py
@@ -0,0 +1,16 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import re
+
+GENERATED_WITH_RE = re.compile(r"^__generated_with = .*$", re.MULTILINE)
+
+
+def contents_differ_excluding_generated_with(
+ original: str, generated: str
+) -> bool:
+ """Compare file contents while ignoring `__generated_with` differences."""
+ return (
+ GENERATED_WITH_RE.sub("", original).strip()
+ != GENERATED_WITH_RE.sub("", generated).strip()
+ )
diff --git a/tests/_lint/test_generated_with_comparison.py b/tests/_lint/test_generated_with_comparison.py
index cc29ff19c8..1aca9c726c 100644
--- a/tests/_lint/test_generated_with_comparison.py
+++ b/tests/_lint/test_generated_with_comparison.py
@@ -1,6 +1,8 @@
# Copyright 2026 Marimo. All rights reserved.
-from marimo._lint.linter import contents_differ_excluding_generated_with
+from marimo._utils.generated_with import (
+ contents_differ_excluding_generated_with,
+)
def test_contents_differ_excluding_generated_with():
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index 22889cde2f..3017c2b591 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -1242,6 +1242,48 @@ if __name__ == "__main__":
assert manager.file_content_matches_last_save() is False
+def test_file_content_matches_last_save_ignores_generated_with_version(
+ tmp_path: Path,
+) -> None:
+ temp_file = tmp_path / "test_generated_with.py"
+ temp_file.write_text(
+ """
+import marimo
+__generated_with = "0.0.0"
+app = marimo.App()
+
+def cell1():
+ x = 1
+ return x
+
+if __name__ == "__main__":
+ app.run()
+"""
+ )
+
+ manager = AppFileManager(filename=str(temp_file))
+ manager.save(
+ SaveNotebookRequest(
+ cell_ids=[CellId_t("1")],
+ filename=str(temp_file),
+ codes=["x = 1"],
+ names=["cell1"],
+ configs=[CellConfig()],
+ persist=True,
+ )
+ )
+
+ temp_file.write_text(
+ temp_file.read_text().replace(
+ f'__generated_with = "{__version__}"',
+ '__generated_with = "0.0.0"',
+ )
+ )
+
+ assert manager.file_content_matches_last_save() is True
+
+
def test_file_content_matches_last_save_multiple_saves(tmp_path: Path) -> None:
"""Test that file_content_matches_last_save tracks the most recent save."""
temp_file = tmp_path / "test_multiple_saves.py"
diff --git a/tests/_session/test_file_change_handler.py b/tests/_session/test_file_change_handler.py
index b872610137..a8364ed38a 100644
--- a/tests/_session/test_file_change_handler.py
+++ b/tests/_session/test_file_change_handler.py
@@ -9,7 +9,7 @@ from unittest.mock import MagicMock
import pytest
-from marimo import _loggers
+from marimo import __version__, _loggers
from marimo._ast.cell import CellConfig
from marimo._ast.cell_manager import CellManager
from marimo._config.manager import get_default_config_manager
@@ -699,6 +699,60 @@ async def test_file_change_coordinator_skips_own_writes(
strategy.handle_reload.assert_called_once()
+async def test_file_change_coordinator_keeps_reloaded_generated_with(
+ tmp_path: Path, mock_session: MagicMock
+) -> None:
+ temp_file = tmp_path / "test_reloaded_generated_with.py"
+ temp_file.write_text("import marimo\napp = marimo.App()\n")
+
+ afm = AppFileManager(filename=str(temp_file))
+ mock_session.app_file_manager = afm
+ request = SaveNotebookRequest(
+ cell_ids=[CellId_t("1")],
+ filename=str(temp_file),
+ codes=["x = 1"],
+ names=["cell1"],
+ configs=[CellConfig()],
+ persist=True,
+ )
+ afm.save(request)
+ old_content = temp_file.read_text().replace(
+ f'__generated_with = "{__version__}"',
+ '__generated_with = "0.0.0"',
+ )
+
+ afm.save(
+ SaveNotebookRequest(
+ cell_ids=[CellId_t("1")],
+ filename=str(temp_file),
+ codes=["x = 2"],
+ names=["cell1"],
+ configs=[CellConfig()],
+ persist=True,
+ )
+ )
+
+ temp_file.write_text(old_content)
+ result = await FileChangeCoordinator(MagicMock()).handle_change(
+ temp_file, mock_session
+ )
+ assert result.handled
+
+ afm.save(
+ SaveNotebookRequest(
+ cell_ids=list(afm.app.cell_manager.cell_ids()),
+ filename=str(temp_file),
+ codes=list(afm.app.cell_manager.codes()),
+ names=["cell1"],
+ configs=[CellConfig()],
+ persist=True,
+ )
+ )
+
+ assert '__generated_with = "0.0.0"' in temp_file.read_text()
+ assert f'__generated_with = "{__version__}"' not in temp_file.read_text()
+
+
async def test_file_change_coordinator_handles_syntax_errors(
tmp_path: Path, mock_session: MagicMock
) -> None: