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.

Save notebook cells without rewriting the app (#11427)

Trevor Manza815c01618f6
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 4a5d7f9cf1..68e60f0e6c 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -1029,14 +1029,14 @@ class InternalApp:
def update_config(self, updates: dict[str, Any]) -> _AppConfig:
return self.config.update(updates)
- def with_data(
+ def apply_data(
self,
*,
cell_ids: Iterable[CellId_t],
codes: Iterable[str],
names: Iterable[str],
configs: Iterable[CellConfig],
- ) -> InternalApp:
+ ) -> Transaction:
"""Rewrite the cell list from textual fields, in place.
Mutates `self._app._cell_manager` rather than replacing it,
@@ -1044,27 +1044,11 @@ class InternalApp:
`app.cell_manager.document` (notably `Session.document`)
continues to see live state without rebinding.
- Cells that survive the rewrite keep their compiled `Cell`;
- callers from save flows pass the frontend's snapshot, which
- renames/reorders/reconfigures cells but doesn't recompile.
+ Cells that survive the rewrite keep their compiled `Cell`. The
+ editor's save passes its snapshot, which renames, reorders, and
+ reconfigures cells without recompiling. Returns the applied
+ transaction.
"""
- self.apply_data(
- cell_ids=cell_ids,
- codes=codes,
- names=names,
- configs=configs,
- )
- return self
-
- def apply_data(
- self,
- *,
- cell_ids: Iterable[CellId_t],
- codes: Iterable[str],
- names: Iterable[str],
- configs: Iterable[CellConfig],
- ) -> Transaction:
- """Rewrite the cell list and return the applied transaction."""
cm = self._app._cell_manager
prev_compiled = dict(cm._compiled_cells)
rebuilt = CellManager(prefix=cm.prefix)
diff --git a/marimo/_server/host/bridge.py b/marimo/_server/host/bridge.py
index 7baaf52c39..7ed01c0601 100644
--- a/marimo/_server/host/bridge.py
+++ b/marimo/_server/host/bridge.py
@@ -316,10 +316,8 @@ class SessionBridge(SessionEventListener):
f"{answer!r} is not an option for {_FILE_CHANGED.id}"
)
# TODO(MO-8005): Move persistence to the notebook, with sessions
- # consuming its events. Until then, save_from_cells on an attached
- # session can replace a concurrent edit with this older snapshot.
- # The notebook's writer must persist snapshots without mutating
- # the live document; cover attached-session edits during a save.
+ # consuming its events. Until then the session's file manager
+ # writes the session's cells, which the host document mirrors.
if session is None:
cells = [documents.to_notebook_cell(c) for c in revision]
manager = None
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index bc44131be1..f3b408337d 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -2,8 +2,6 @@
from __future__ import annotations
import os
-import threading
-from contextlib import nullcontext
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -12,10 +10,6 @@ from marimo._ast import load
from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import overloads_from_env
from marimo._ast.cell import CellConfig
-from marimo._environments.script_metadata import (
- notebook_file_lock,
- with_python_version_requirement,
-)
from marimo._messaging.notebook.changes import (
Transaction,
)
@@ -25,17 +19,14 @@ from marimo._runtime.layout.layout import (
read_layout_config,
save_layout_config,
)
-from marimo._schemas.serialization import Header, NotebookSerializationV1
+from marimo._schemas.serialization import NotebookSerializationV1
from marimo._server.app_defaults import AppDefaults
-from marimo._session.notebook.serializer import get_notebook_serializer
from marimo._session.notebook.storage import (
FilesystemStorage,
StorageInterface,
)
+from marimo._session.notebook.writer import NotebookWriter, cells_to_ir
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
@@ -76,6 +67,7 @@ class AppFileManager:
self._filename = _maybe_path(filename)
self.storage: StorageInterface = storage or FilesystemStorage()
+ self.writer = NotebookWriter(self.storage)
# Configuration defaults
self._defaults = defaults or AppDefaults()
@@ -83,8 +75,6 @@ class AppFileManager:
# Load the app
self.app = self._load_app(self.path)
- # Track the last saved content to avoid reloading our own writes
- self._last_saved_content: str | None = None
# TODO(MO-7927): The host follows the editor's writes through this
# hook until the notebook owns persistence and no second writer
# remains to follow.
@@ -97,10 +87,9 @@ class AppFileManager:
document, which another thread may have changed meanwhile.
"""
- # Serializes concurrent writers. Reentrant so public entry points
- # can wrap the full "mutate app + _save_file" sequence while
- # `_save_file` re-acquires for any direct caller.
- self._save_lock = threading.RLock()
+ # Serializes concurrent writers. Public entry points wrap the full
+ # "mutate app + _save_file" sequence and the writer re-acquires.
+ self._save_lock = self.writer.lock
# Foreground writes supersede queued autosaves.
self._autosave_generation = 0
@@ -231,57 +220,16 @@ class AppFileManager:
Returns:
Serialized notebook contents
"""
- LOGGER.debug("Saving app to %s", path)
-
- # Read the header and write the cells under the same lock as manifest
- # edits, so neither writer can restore the other's stale contents.
- file_lock = notebook_file_lock(str(path)) if persist else nullcontext()
- with self._save_lock, file_lock:
- # Get the header in case it was modified by the user (e.g. package installation)
- handler = get_notebook_serializer(path)
- header: str | None = None
- if previous_path and previous_path.exists():
- header = handler.extract_header(previous_path)
- elif path.exists():
- header = handler.extract_header(path)
-
- # For new .py files in sandbox mode, generate header with marimo
- if header is None and str(path).endswith(".py"):
- from marimo._config.settings import GLOBAL_SETTINGS
-
- if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:
- from marimo._environments import script_metadata
-
- header = script_metadata.dumps(
- with_python_version_requirement(
- {
- "dependencies": ["marimo"],
- }
- )
- )
-
- # Rewrap with header if relevant and set filename.
- notebook = NotebookSerializationV1(
- app=notebook.app,
- header=Header(value=header) if header else notebook.header,
- cells=notebook.cells,
- violations=notebook.violations,
- valid=notebook.valid,
- filename=str(path),
+ with self._save_lock:
+ contents = self.writer.write_ir(
+ path,
+ notebook=notebook,
+ persist=persist,
+ previous_path=previous_path,
)
- 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._mark_content_as_last_save(contents)
-
# If this is a new unnamed notebook, update the filename
if self._is_unnamed():
self._filename = path
-
return contents
def _load_app(self, path: str | None) -> InternalApp:
@@ -525,12 +473,12 @@ class AppFileManager:
expected_filename: Path | None = None,
expected_generation: int | None = None,
) -> str:
- """Persist the notebook from a snapshot of document cells.
+ """Persist a snapshot of document cells with the app's config.
Used by the server-side auto-save path for `code_mode`
- mutations. Unlike `save()`, this takes cells directly — the
- caller is responsible for snapshotting `session.document.cells`
- on a thread where the document is quiescent.
+ mutations and by the host. Unlike `save()`, this changes nothing
+ in memory: the cells are written as given, and a document that
+ has moved on since they were taken keeps its newer state.
Raises:
HTTPException: If the notebook is unnamed or the write fails
@@ -551,15 +499,13 @@ class AppFileManager:
):
return ""
- self.app.with_data(
- cell_ids=[cell.id for cell in cells],
- codes=[cell.code for cell in cells],
- names=[cell.name for cell in cells],
- configs=[cell.config for cell in cells],
- )
contents = self._save_file(
self._filename,
- notebook=self.app.to_ir(),
+ notebook=cells_to_ir(
+ cells,
+ self.app.config.asdict(),
+ header=self.app._app._header,
+ ),
persist=True,
)
self._persisted(cells)
@@ -651,29 +597,23 @@ class AppFileManager:
return self.storage.read(self._filename)
def _mark_content_as_last_save(self, content: str) -> None:
- self._last_saved_content = content.strip()
+ self.writer.remember(content)
def content_matches_last_save(self, content: str) -> bool:
"""Check if the given content matches the last save.
Used to avoid reloading the file when we detect our own writes.
- Prefer this over :meth:`file_content_matches_last_save` when the
+ Prefer this over `file_content_matches_last_save` when the
caller already has the file contents in hand.
"""
- if self._last_saved_content is None:
- return False
- if content.strip() == self._last_saved_content:
- return True
- return not contents_differ_excluding_generated_with(
- content, self._last_saved_content
- )
+ return self.writer.content_matches_last_save(content)
def file_content_matches_last_save(self) -> bool:
"""Check if current file content matches the last save.
Used to avoid reloading the file when we detect our own writes.
"""
- if self._filename is None or self._last_saved_content is None:
+ if self._filename is None or self.writer.last_content is None:
return False
try:
return self.content_matches_last_save(
diff --git a/marimo/_session/notebook/writer.py b/marimo/_session/notebook/writer.py
new file mode 100644
index 0000000000..112f568b3e
--- /dev/null
+++ b/marimo/_session/notebook/writer.py
@@ -0,0 +1,162 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Write notebook sources to a file, remembering what was written."""
+
+from __future__ import annotations
+
+import threading
+from contextlib import nullcontext
+from typing import TYPE_CHECKING, Any
+
+from marimo import _loggers
+from marimo._ast.names import DEFAULT_CELL_NAME
+from marimo._environments.script_metadata import (
+ notebook_file_lock,
+ with_python_version_requirement,
+)
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ Header,
+ NotebookSerializationV1,
+)
+from marimo._session.notebook.serializer import get_notebook_serializer
+from marimo._session.notebook.storage import (
+ FilesystemStorage,
+ StorageInterface,
+)
+from marimo._utils.generated_with import (
+ contents_differ_excluding_generated_with,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Mapping
+ from pathlib import Path
+
+ from marimo._messaging.notebook.document import NotebookCell
+
+LOGGER = _loggers.marimo_logger()
+
+
+def cells_to_ir(
+ cells: Iterable[NotebookCell],
+ app_config: Mapping[str, Any],
+ *,
+ header: str | None = None,
+) -> NotebookSerializationV1:
+ """The serialization of these cells, app options, and loaded header.
+
+ The writer prefers the current file's header and sets the filename.
+ """
+ return NotebookSerializationV1(
+ header=Header(value=header) if header else None,
+ app=AppInstantiation(options=dict(app_config)),
+ cells=[
+ CellDef(
+ code=cell.code,
+ name=cell.name or DEFAULT_CELL_NAME,
+ options=cell.config.asdict(),
+ )
+ for cell in cells
+ ],
+ )
+
+
+class NotebookWriter:
+ """Serializes notebook IR to a file and remembers the text last written.
+
+ Share one writer between everything that writes a notebook file, so a
+ watcher can tell the notebook's own writes from someone else's, and a
+ write whose text is already on disk is skipped.
+ """
+
+ def __init__(self, storage: StorageInterface | None = None) -> None:
+ self.storage: StorageInterface = storage or FilesystemStorage()
+ # Reentrant so a caller can wrap several writes in one critical
+ # section while each write re-acquires for direct callers.
+ self.lock = threading.RLock()
+ self.last_content: str | None = None
+
+ def write_ir(
+ self,
+ path: Path,
+ *,
+ notebook: NotebookSerializationV1,
+ persist: bool,
+ previous_path: Path | None = None,
+ ) -> str:
+ """Serialize `notebook` for `path` and, if `persist`, write it.
+
+ The file's header is kept, read from `previous_path` when the file
+ is being renamed. Returns the text written, or the text already on
+ disk when the serialization matches the last write.
+ """
+ LOGGER.debug("Saving notebook to %s", path)
+
+ # Read the header and write the cells under the same lock as manifest
+ # edits, so neither writer can restore the other's stale contents.
+ file_lock = notebook_file_lock(str(path)) if persist else nullcontext()
+ with self.lock, file_lock:
+ # Get the header in case it was modified by the user (e.g. package installation)
+ handler = get_notebook_serializer(path)
+ header: str | None = None
+ if previous_path and previous_path.exists():
+ header = handler.extract_header(previous_path)
+ elif path.exists():
+ header = handler.extract_header(path)
+
+ if header is None and notebook.header is not None:
+ header = notebook.header.value
+
+ # For new .py files in sandbox mode, generate header with marimo
+ if header is None and str(path).endswith(".py"):
+ from marimo._config.settings import GLOBAL_SETTINGS
+
+ if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:
+ from marimo._environments import script_metadata
+
+ header = script_metadata.dumps(
+ with_python_version_requirement(
+ {
+ "dependencies": ["marimo"],
+ }
+ )
+ )
+
+ # Rewrap with header if relevant and set filename.
+ notebook = NotebookSerializationV1(
+ app=notebook.app,
+ header=Header(value=header) if header else notebook.header,
+ cells=notebook.cells,
+ violations=notebook.violations,
+ valid=notebook.valid,
+ filename=str(path),
+ )
+ contents = handler.serialize(notebook)
+
+ if persist:
+ if self.content_matches_last_save(contents):
+ return self.last_content or contents
+ self.storage.write(path, contents)
+ self.remember(contents)
+
+ return contents
+
+ def remember(self, content: str) -> None:
+ """Record `content` as what is on disk, after a write or a reload."""
+ with self.lock:
+ self.last_content = content.strip()
+
+ def content_matches_last_save(self, content: str) -> bool:
+ """Whether `content` is what this writer last wrote or reloaded.
+
+ Differences in the `__generated_with` version alone do not count.
+ """
+ with self.lock:
+ baseline = self.last_content
+ if baseline is None:
+ return False
+ if content.strip() == baseline:
+ return True
+ return not contents_differ_excluding_generated_with(
+ content, baseline
+ )
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index a44b87a356..45cc419ada 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -1930,9 +1930,9 @@ class TestAppComposition:
assert is_external_cell_id(setup_cell_ids[0])
-class TestInternalAppWithData:
- """`InternalApp.with_data` rewrites the cell list from the
- frontend's snapshot during the save round-trip. It must mutate the
+class TestInternalAppApplyData:
+ """`InternalApp.apply_data` rewrites the cell list from the
+ frontend's snapshot during the editor's save. It must mutate the
existing cell manager in place — Session holds
`app.cell_manager.document` as a property, so swapping in a fresh
manager would orphan `session.document`.
@@ -1953,7 +1953,7 @@ class TestInternalAppWithData:
names = list(cell_manager.names())
configs = list(cell_manager.configs())
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=cell_ids,
codes=[c + " # edited" for c in codes],
names=names,
@@ -1977,7 +1977,7 @@ class TestInternalAppWithData:
names = list(internal_app.cell_manager.names())
configs = list(internal_app.cell_manager.configs())
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=cell_ids,
codes=[c + " # edited" for c in codes],
names=names,
@@ -1999,7 +1999,7 @@ class TestInternalAppWithData:
original_compiled = internal_app.cell_manager._compiled_cells[cell_id]
assert original_compiled is not None
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id],
codes=["x = 2 # renamed-only-here"],
names=["__"],
@@ -2018,7 +2018,7 @@ class TestInternalAppWithData:
internal_app, cell_id = self._seed_single()
compiled = internal_app.cell_manager._compiled_cells
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=["new"],
codes=["y = 2"],
names=["__"],
@@ -2040,7 +2040,7 @@ class TestInternalAppWithData:
internal_app = InternalApp(app)
cell_id = next(iter(internal_app.cell_manager.cell_ids()))
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id],
codes=["x = 99"],
names=["renamed"],
@@ -2069,7 +2069,7 @@ class TestInternalAppWithData:
doc = internal_app.cell_manager.document
before = doc.get_cell_version(cell_id)
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id],
codes=[doc.get_cell(cell_id).code],
names=["__"],
@@ -2083,7 +2083,7 @@ class TestInternalAppWithData:
doc = internal_app.cell_manager.document
before = doc.get_cell_version(cell_id)
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id],
codes=["x = 2"],
names=["__"],
@@ -2096,7 +2096,7 @@ class TestInternalAppWithData:
internal_app, cell_id = self._seed_single()
doc = internal_app.cell_manager.document
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id, "new"],
codes=["x = 1", "y = 2"],
names=["__", "__"],
@@ -2111,7 +2111,7 @@ class TestInternalAppWithData:
internal_app, cell_id = self._seed_single()
# Drop the original cell.
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=["other"],
codes=["y = 2"],
names=["__"],
@@ -2127,19 +2127,19 @@ class TestInternalAppWithData:
internal_app, cell_id = self._seed_single()
internal_app.cell_manager.unparsable = True
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id],
codes=["x = 2"],
names=["__"],
configs=[CellConfig()],
)
- # with_data rebuilds from parsable textual fields, so unparsable
+ # apply_data rebuilds from parsable textual fields, so unparsable
# resets to the rebuilt manager's value (False).
assert internal_app.cell_manager.unparsable is False
def test_noop_save_does_not_bump_document_version(self) -> None:
- # with_data routes through apply(); a save with identical content
+ # apply_data routes through apply(), so a save with identical content
# produces an empty transaction, which leaves the document version
# unchanged (consistent with SetCode no-op staying stable).
internal_app, cell_id = self._seed_single()
@@ -2147,7 +2147,7 @@ class TestInternalAppWithData:
cell = doc.get_cell(cell_id)
before = doc.version
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[cell_id],
codes=[cell.code],
names=[cell.name],
diff --git a/tests/_ast/test_cell_manager.py b/tests/_ast/test_cell_manager.py
index 127d5ab359..f90273fb46 100644
--- a/tests/_ast/test_cell_manager.py
+++ b/tests/_ast/test_cell_manager.py
@@ -86,7 +86,7 @@ class TestCellManager:
self, cell_manager: CellManager
) -> None:
# Externally-supplied ids (e.g. from frontend save round-trip /
- # InternalApp.with_data) must be tracked so subsequent
+ # InternalApp.apply_data) must be tracked so subsequent
# create_cell_id() calls don't produce a colliding id.
explicit_id = CellId_t("test_external")
cell_manager.register_cell(
diff --git a/tests/_export/test_export_ipynb.py b/tests/_export/test_export_ipynb.py
index 94d059c4fd..4eca50889d 100644
--- a/tests/_export/test_export_ipynb.py
+++ b/tests/_export/test_export_ipynb.py
@@ -57,7 +57,7 @@ def test_topological_export_preserves_invalid_cells() -> None:
valid_cell = next(iter(internal_app.cell_manager.cell_data()))
invalid_cell_id = CellId_t("invalid-cell")
_ = internal_app.graph
- internal_app.with_data(
+ internal_app.apply_data(
cell_ids=[invalid_cell_id, valid_cell.cell_id],
codes=["x =", valid_cell.code],
names=["_", valid_cell.name],
diff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.py
index ff7ca1fa7d..0c3281a627 100644
--- a/tests/_runtime/test_manage_script_metadata.py
+++ b/tests/_runtime/test_manage_script_metadata.py
@@ -43,9 +43,11 @@ HAS_UV = DependencyManager.which("uv")
new=property(lambda _: False),
)
async def test_manage_script_metadata_uv(
- tmp_path: pathlib.Path, mocked_kernel: MockedKernel
+ tmp_path: pathlib.Path,
+ mocked_kernel: MockedKernel,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
- GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA = True
+ monkeypatch.setattr(GLOBAL_SETTINGS, "MANAGE_SCRIPT_METADATA", True)
filename = str(tmp_path / "notebook.py")
# Create empty file
with open(filename, "w") as f: # noqa: ASYNC230
@@ -96,9 +98,11 @@ async def test_manage_script_metadata_uv(
new=property(lambda _: False),
)
async def test_manage_script_metadata_uv_deletion(
- tmp_path: pathlib.Path, mocked_kernel: MockedKernel
+ tmp_path: pathlib.Path,
+ mocked_kernel: MockedKernel,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
- GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA = True
+ monkeypatch.setattr(GLOBAL_SETTINGS, "MANAGE_SCRIPT_METADATA", True)
filename = str(tmp_path / "notebook.py")
# Create empty file
with open(filename, "w") as f: # noqa: ASYNC230
@@ -154,9 +158,11 @@ async def test_manage_script_metadata_uv_deletion(
@pytest.mark.skipif(not HAS_UV, reason="uv not installed")
async def test_manage_script_metadata_uv_off(
- tmp_path: pathlib.Path, mocked_kernel: MockedKernel
+ tmp_path: pathlib.Path,
+ mocked_kernel: MockedKernel,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
- GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA = False
+ monkeypatch.setattr(GLOBAL_SETTINGS, "MANAGE_SCRIPT_METADATA", False)
filename = str(tmp_path / "notebook.py")
# Create empty file
with open(filename, "w") as f: # noqa: ASYNC230
@@ -183,9 +189,11 @@ async def test_manage_script_metadata_uv_off(
@pytest.mark.skipif(not HAS_UV, reason="uv not installed")
async def test_manage_script_metadata_uv_no_filename(
- tmp_path: pathlib.Path, mocked_kernel: MockedKernel
+ tmp_path: pathlib.Path,
+ mocked_kernel: MockedKernel,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
- GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA = True
+ monkeypatch.setattr(GLOBAL_SETTINGS, "MANAGE_SCRIPT_METADATA", True)
filename = str(tmp_path / "notebook.py")
# Create empty file
with open(filename, "w") as f: # noqa: ASYNC230
@@ -210,9 +218,11 @@ async def test_manage_script_metadata_uv_no_filename(
async def test_manage_script_metadata_pip_noop(
- tmp_path: pathlib.Path, mocked_kernel: MockedKernel
+ tmp_path: pathlib.Path,
+ mocked_kernel: MockedKernel,
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
- GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA = True
+ monkeypatch.setattr(GLOBAL_SETTINGS, "MANAGE_SCRIPT_METADATA", True)
filename = str(tmp_path / "notebook.py")
# Create empty file
with open(filename, "w") as f: # noqa: ASYNC230
diff --git a/tests/_server/host/test_host_bridge.py b/tests/_server/host/test_host_bridge.py
index 5e75fff64a..e02d5cce3d 100644
--- a/tests/_server/host/test_host_bridge.py
+++ b/tests/_server/host/test_host_bridge.py
@@ -740,14 +740,24 @@ async def test_save_writes_the_cells_and_keeps_the_app_config(
bridge.close()
[email protected]("attached", [False, True])
async def test_saving_keeps_an_edit_made_while_the_file_is_written(
- manager: FakeManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ manager: FakeManager,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ attached: bool,
) -> None:
from marimo._session.notebook import AppFileManager
prepare(manager, tmp_path, "a.py")
path = tmp_path / "a.py"
path.write_text(NOTEBOOK)
+ session = None
+ if attached:
+ session = FakeSession(str(path))
+ session.app_file_manager = AppFileManager(str(path))
+ session.document = session.app_file_manager.app.cell_manager.document
+ manager.sessions["browser-1"] = session
bridge = SessionBridge(manager) # type: ignore[arg-type]
await bridge.open()
record = bridge.index.notebook_for(str(path))
@@ -776,6 +786,7 @@ async def test_saving_keeps_an_edit_made_while_the_file_is_written(
edited = await bridge.edit(
record.id, [replace_code(cell, "x = 2")], request_id="edit-1"
)
+ version = session.document.version if session is not None else None
finally:
release.set()
saved = await asyncio.wait_for(saving, 5)
@@ -786,6 +797,9 @@ async def test_saving_keeps_an_edit_made_while_the_file_is_written(
assert notebook.saved_etag != notebook.document.etag
assert "x = 1" in path.read_text()
assert "x = 2" not in path.read_text()
+ if session is not None:
+ assert [c.code for c in session.document.cells] == ["x = 2"]
+ assert session.document.version == version
bridge.close()
@@ -842,7 +856,7 @@ async def test_the_editor_saving_marks_the_host_document_saved(
from marimo._ast.cell import CellConfig
from marimo._core.document import Document
from marimo._messaging.notebook import NotebookCell
- from marimo._server.host.document import from_file_manager
+ from marimo._server.host.document import sources
from marimo._session.notebook import AppFileManager
from marimo._types.ids import CellId_t
@@ -864,11 +878,12 @@ async def test_the_editor_saving_marks_the_host_document_saved(
before = notebook.document.etag
# The editor writes new content the host has not mirrored yet.
- session.app_file_manager.save_from_cells(
- [NotebookCell(CellId_t(cell.id), "x = 2", cell.name, CellConfig())]
- )
+ cells = [NotebookCell(CellId_t(cell.id), "x = 2", cell.name, CellConfig())]
+ session.app_file_manager.save_from_cells(cells)
- written = Document(*from_file_manager(session.app_file_manager)).etag
+ written = Document(
+ sources(cells), session.app_file_manager.app.config.asdict_difference()
+ ).etag
assert notebook.saved_etag == written
assert notebook.document.etag == before != written
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index 3017c2b591..6b674513dd 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -9,6 +9,7 @@ import pytest
from marimo import __version__
from marimo._ast.app import App, InternalApp
from marimo._ast.cell import CellConfig
+from marimo._config.settings import GLOBAL_SETTINGS
from marimo._server.app_defaults import AppDefaults
from marimo._server.models.models import SaveNotebookRequest
from marimo._session.notebook import AppFileManager
@@ -310,6 +311,65 @@ def test_save_from_cells_persists_cells(
assert "def first" in contents
+def test_save_from_cells_leaves_the_document_alone(
+ app_file_manager: AppFileManager,
+) -> None:
+ """The cells are written as given and nothing in memory changes.
+
+ An autosave runs on a worker thread with a copy of the cells. An
+ edit that lands meanwhile must not be replaced by the older copy.
+ """
+ from marimo._messaging.notebook.document import NotebookCell
+
+ document = app_file_manager.app.cell_manager.document
+ (cell,) = document.cells
+ version = document.version
+
+ app_file_manager.save_from_cells(
+ [NotebookCell(cell.id, "z = 99", cell.name, CellConfig())]
+ )
+
+ assert document.get_cell(cell.id).code == cell.code
+ assert document.version == version
+ assert app_file_manager.filename is not None
+ with open(app_file_manager.filename, encoding="utf-8") as f:
+ assert "z = 99" in f.read()
+
+
[email protected]("recreate", [False, True])
[email protected]("manage_script_metadata", [False, True])
+def test_save_from_cells_preserves_the_header(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ recreate: bool,
+ manage_script_metadata: bool,
+) -> None:
+ monkeypatch.setattr(
+ GLOBAL_SETTINGS, "MANAGE_SCRIPT_METADATA", manage_script_metadata
+ )
+ path = tmp_path / "notebook.py"
+ header = '# /// script\n# dependencies = ["requests"]\n# ///\n'
+ path.write_text(
+ header
+ + "\nimport marimo\napp = marimo.App()\n"
+ + "\[email protected]\ndef _():\n x = 1\n return (x,)\n"
+ )
+ manager = AppFileManager(str(path))
+ cells = list(manager.app.cell_manager.document.cells)
+ if recreate:
+ path.unlink()
+ else:
+ # A package install can update the header after the app was loaded.
+ updated = header.replace("requests", "httpx")
+ path.write_text(path.read_text().replace(header, updated))
+ header = updated
+
+ manager.save_from_cells(cells)
+
+ assert path.read_text().startswith(header)
+ assert "x = 1" in path.read_text()
+
+
def test_save_from_cells_empty_name_normalizes(
app_file_manager: AppFileManager,
) -> None:
@@ -1144,8 +1204,8 @@ if __name__ == "__main__":
manager = AppFileManager(filename=str(temp_file))
- # Should return False when _last_saved_content is None
- assert manager._last_saved_content is None
+ # Should return False when nothing has been written yet
+ assert manager.writer.last_content is None
assert manager.file_content_matches_last_save() is False
diff --git a/tests/_session/notebook/test_writer.py b/tests/_session/notebook/test_writer.py
new file mode 100644
index 0000000000..a248bb7b60
--- /dev/null
+++ b/tests/_session/notebook/test_writer.py
@@ -0,0 +1,162 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import pytest
+
+from marimo._ast.cell import CellConfig
+from marimo._messaging.notebook.document import NotebookCell
+from marimo._session.notebook.storage import FilesystemStorage
+from marimo._session.notebook.writer import NotebookWriter, cells_to_ir
+from marimo._types.ids import CellId_t
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+HEADER = """# /// script
+# dependencies = ["requests"]
+# ///
+"""
+
+NOTEBOOK = (
+ HEADER
+ + """
+import marimo
+
+app = marimo.App()
+
+
+def _():
+ x = 1
+ return (x,)
+"""
+)
+
+
+class CountingStorage(FilesystemStorage):
+ def __init__(self) -> None:
+ super().__init__()
+ self.writes = 0
+ self.fail = False
+
+ def write(self, path: Path, content: str) -> None:
+ if self.fail:
+ raise OSError("disk full")
+ self.writes += 1
+ super().write(path, content)
+
+
+def cells(code: str, name: str = "_") -> list[NotebookCell]:
+ return [NotebookCell(CellId_t("c"), code, name, CellConfig())]
+
+
+def test_cells_to_ir_names_unnamed_cells() -> None:
+ ir = cells_to_ir(cells("x = 1", name=""), {"width": "full"})
+
+ assert [cell.name for cell in ir.cells] == ["_"]
+ assert ir.app.options == {"width": "full"}
+ assert ir.header is None
+
+
+def test_write_keeps_the_header(tmp_path: Path) -> None:
+ path = tmp_path / "nb.py"
+ path.write_text(NOTEBOOK)
+ writer = NotebookWriter()
+
+ text = writer.write_ir(
+ path, notebook=cells_to_ir(cells("x = 2"), {}), persist=True
+ )
+
+ assert text.startswith(HEADER)
+ assert path.read_text() == text
+ assert "x = 2" in text
+
+
+def test_write_reads_the_header_from_the_previous_path(tmp_path: Path) -> None:
+ old = tmp_path / "old.py"
+ old.write_text(NOTEBOOK)
+ new = tmp_path / "new.py"
+ writer = NotebookWriter()
+
+ text = writer.write_ir(
+ new,
+ notebook=cells_to_ir(cells("x = 1"), {}),
+ persist=True,
+ previous_path=old,
+ )
+
+ assert text.startswith(HEADER)
+
+
+def test_unchanged_content_is_not_written_again(tmp_path: Path) -> None:
+ path = tmp_path / "nb.py"
+ path.write_text(NOTEBOOK)
+ storage = CountingStorage()
+ writer = NotebookWriter(storage)
+ notebook = cells_to_ir(cells("x = 2"), {})
+
+ first = writer.write_ir(path, notebook=notebook, persist=True)
+ second = writer.write_ir(path, notebook=notebook, persist=True)
+
+ assert storage.writes == 1
+ assert first.strip() == second.strip()
+
+
+def test_serializing_without_persisting_leaves_the_file_alone(
+ tmp_path: Path,
+) -> None:
+ path = tmp_path / "nb.py"
+ path.write_text(NOTEBOOK)
+ writer = NotebookWriter()
+
+ text = writer.write_ir(
+ path, notebook=cells_to_ir(cells("x = 2"), {}), persist=False
+ )
+
+ assert "x = 2" in text
+ assert path.read_text() == NOTEBOOK
+ assert writer.last_content is None
+
+
+def test_failed_write_keeps_the_baseline(tmp_path: Path) -> None:
+ path = tmp_path / "nb.py"
+ path.write_text(NOTEBOOK)
+ storage = CountingStorage()
+ writer = NotebookWriter(storage)
+ written = writer.write_ir(
+ path, notebook=cells_to_ir(cells("x = 2"), {}), persist=True
+ )
+
+ storage.fail = True
+ with pytest.raises(OSError):
+ writer.write_ir(
+ path, notebook=cells_to_ir(cells("x = 3"), {}), persist=True
+ )
+
+ assert writer.content_matches_last_save(written)
+ assert path.read_text() == written
+
+
+def test_content_matches_ignores_the_generated_with_version(
+ tmp_path: Path,
+) -> None:
+ path = tmp_path / "nb.py"
+ path.write_text(NOTEBOOK)
+ writer = NotebookWriter()
+ written = writer.write_ir(
+ path, notebook=cells_to_ir(cells("x = 2"), {}), persist=True
+ )
+ (line,) = [
+ line
+ for line in written.splitlines()
+ if line.startswith("__generated_with")
+ ]
+
+ assert writer.content_matches_last_save(
+ written.replace(line, '__generated_with = "0.0.0"')
+ )
+ assert not writer.content_matches_last_save(
+ written.replace("x = 2", "x = 3")
+ )