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.

refactor: enforce cell_ids parameter in session serialization and caching (#8904)

Myles Scolnick3d9d536cece0
diff --git a/marimo/_server/export/_session_cache.py b/marimo/_server/export/_session_cache.py
index 4b74b5a35f..a3911e6638 100644
--- a/marimo/_server/export/_session_cache.py
+++ b/marimo/_server/export/_session_cache.py
@@ -59,7 +59,7 @@ def serialize_session_snapshot(
view: SessionView,
*,
notebook_path: str | Path | None,
- cell_ids: Iterable[CellId_t] | None = None,
+ cell_ids: Iterable[CellId_t],
) -> NotebookSessionV1:
return serialize_session_view(
view,
@@ -83,7 +83,7 @@ def persist_session_view_to_cache(
*,
view: SessionView,
notebook_path: str | Path | None,
- cell_ids: Iterable[CellId_t] | None = None,
+ cell_ids: Iterable[CellId_t],
) -> Path | None:
if notebook_path is None:
return None
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.py
index e4736ef301..fdb5e1583e 100644
--- a/marimo/_session/extensions/extensions.py
+++ b/marimo/_session/extensions/extensions.py
@@ -156,6 +156,7 @@ class CachingExtension(SessionExtension, SessionEventListener):
LOGGER.debug("Syncing session view from cache")
self.session_cache_manager = SessionCacheManager(
session_view=session.session_view,
+ document=session.document,
path=session.app_file_manager.path,
interval=self.interval,
)
diff --git a/marimo/_session/state/serialize.py b/marimo/_session/state/serialize.py
index b4d3e8240e..9f664df45f 100644
--- a/marimo/_session/state/serialize.py
+++ b/marimo/_session/state/serialize.py
@@ -18,6 +18,7 @@ from marimo._messaging.errors import (
)
from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.msgspec_encoder import asdict
+from marimo._messaging.notebook.document import NotebookDocument
from marimo._messaging.notification import CellNotification
from marimo._schemas.notebook import (
NotebookCell,
@@ -78,7 +79,7 @@ def _normalize_error(error: Union[MarimoError, dict[str, Any]]) -> ErrorOutput:
def serialize_session_view(
view: SessionView,
- cell_ids: Iterable[CellId_t] | None = None,
+ cell_ids: Iterable[CellId_t],
script_metadata_hash: str | None = None,
) -> NotebookSessionV1:
"""Convert a SessionView to a NotebookSession schema.
@@ -90,9 +91,6 @@ def serialize_session_view(
"""
cells: list[Cell] = []
- if cell_ids is None:
- cell_ids = view.cell_notifications.keys()
-
for cell_id in cell_ids:
cell_notif = view.cell_notifications.get(cell_id)
if cell_notif is None:
@@ -377,12 +375,14 @@ class SessionCacheWriter(AsyncBackgroundTask):
def __init__(
self,
session_view: SessionView,
+ document: NotebookDocument,
path: Path,
interval: float,
notebook_path: Path | None = None,
) -> None:
super().__init__()
self.session_view = session_view
+ self.document = document
self.notebook_path = notebook_path
# Windows does not support our async path implementation
self.path: AsyncPath | Path = path
@@ -409,6 +409,7 @@ class SessionCacheWriter(AsyncBackgroundTask):
LOGGER.debug(f"Writing session view to cache {self.path}")
data = serialize_session_view(
self.session_view,
+ cell_ids=self.document.cell_ids,
script_metadata_hash=_script_metadata_hash(
self.notebook_path
),
@@ -443,10 +444,12 @@ class SessionCacheManager:
def __init__(
self,
session_view: SessionView,
+ document: NotebookDocument,
path: Optional[str | Path],
interval: float,
):
self.session_view = session_view
+ self.document = document
self.path = path
self.interval = interval
self.session_cache_writer: SessionCacheWriter | None = None
@@ -461,6 +464,7 @@ class SessionCacheManager:
self.session_cache_writer = SessionCacheWriter(
session_view=self.session_view,
+ document=self.document,
path=cache_file,
interval=self.interval,
notebook_path=notebook_path,
diff --git a/tests/_session/state/test_serialize_session.py b/tests/_session/state/test_serialize_session.py
index e367e3cdd9..0054482601 100644
--- a/tests/_session/state/test_serialize_session.py
+++ b/tests/_session/state/test_serialize_session.py
@@ -9,10 +9,11 @@ from pathlib import Path
import pytest
from marimo import __version__
-from marimo._ast.cell import CellConfig
+from marimo._ast.cell import CellConfig, RuntimeStateType
from marimo._ast.cell_manager import CellManager
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import MarimoExceptionRaisedError, UnknownError
+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
from marimo._messaging.notification import CellNotification
from marimo._runtime.commands import ExecuteCellsCommand
from marimo._schemas.session import NotebookSessionV1
@@ -32,6 +33,36 @@ from tests.mocks import snapshotter
snapshot = snapshotter(__file__)
+CELL1 = CellId_t("cell1")
+CELL2 = CellId_t("cell2")
+
+
+def _make_document(*cell_ids: CellId_t) -> NotebookDocument:
+ """Create a NotebookDocument with the given cell IDs."""
+ return NotebookDocument(
+ [
+ NotebookCell(id=cid, code="", name="__", config=CellConfig())
+ for cid in cell_ids
+ ]
+ )
+
+
+def _make_cell_notification(
+ cell_id: CellId_t,
+ *,
+ output: CellOutput | None = None,
+ status: RuntimeStateType = "idle",
+ console: list[CellOutput] | None = None,
+) -> CellNotification:
+ """Create a CellNotification with sensible defaults."""
+ return CellNotification(
+ cell_id=cell_id,
+ status=status,
+ output=output,
+ console=console or [],
+ timestamp=0,
+ )
+
def _build_code_hash_to_cell_id_mapping(
session: NotebookSessionV1,
@@ -47,52 +78,44 @@ def _build_code_hash_to_cell_id_mapping(
def test_serialize_basic_session(session_view: SessionView):
"""Test serialization of a basic session with a single cell with data output"""
view = session_view
- view.cell_notifications[CellId_t("cell1")] = CellNotification(
- cell_id=CellId_t("cell1"),
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="Hello, world!",
),
- console=[],
- timestamp=0,
)
- view.last_executed_code[CellId_t("cell1")] = "print('Hello, world!')"
+ view.last_executed_code[CELL1] = "print('Hello, world!')"
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL1])
snapshot("basic_session.json", json.dumps(result, indent=2))
def test_serialize_session_with_error(session_view: SessionView):
"""Test serialization of a session with an error output"""
view = session_view
- view.cell_notifications[CellId_t("cell1")] = CellNotification(
- cell_id=CellId_t("cell1"),
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.MARIMO_ERROR,
mimetype="application/vnd.marimo+error",
data=[UnknownError(msg="Something went wrong")],
),
- console=[],
- timestamp=0,
)
- view.last_executed_code[CellId_t("cell1")] = (
+ view.last_executed_code[CELL1] = (
"raise RuntimeError('Something went wrong')"
)
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL1])
snapshot("error_session.json", json.dumps(result, indent=2))
def test_serialize_session_with_console(session_view: SessionView):
"""Test serialization of a session with console output"""
view = session_view
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
- output=None,
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
console=[
CellOutput(
channel=CellChannel.STDOUT,
@@ -105,20 +128,18 @@ def test_serialize_session_with_console(session_view: SessionView):
data="stderr message",
),
],
- timestamp=0,
)
- view.last_executed_code["cell1"] = "print('test')"
+ view.last_executed_code[CELL1] = "print('test')"
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL1])
snapshot("console_session.json", json.dumps(result, indent=2))
def test_serialize_session_with_mime_bundle(session_view: SessionView):
"""Test serialization of a session with a mime bundle output"""
view = session_view
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="application/vnd.marimo+mimebundle",
@@ -127,12 +148,10 @@ def test_serialize_session_with_mime_bundle(session_view: SessionView):
"text/html": "<b>Hello</b>",
},
),
- console=[],
- timestamp=0,
)
- view.last_executed_code["cell1"] = "HTML('Hello')"
+ view.last_executed_code[CELL1] = "HTML('Hello')"
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL1])
snapshot("mime_bundle_session.json", json.dumps(result, indent=2))
@@ -141,28 +160,22 @@ def test_serialize_notebook_basic(session_view: SessionView):
view = session_view
cell_manager = CellManager()
- # Register cell with cell manager
- cell_id = CellId_t("cell1")
cell_manager.register_cell(
- cell_id=cell_id,
+ cell_id=CELL1,
code="print('Hello, world!')",
name="my_cell",
config=CellConfig(column=1, disabled=False, hide_code=True),
)
- # Add to session view
- view.cell_notifications[cell_id] = CellNotification(
- cell_id=cell_id,
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="Hello, world!",
),
- console=[],
- timestamp=0,
)
- view.last_executed_code[cell_id] = "print('Hello, world!')"
+ view.last_executed_code[CELL1] = "print('Hello, world!')"
result = serialize_notebook(view, cell_manager)
@@ -184,47 +197,32 @@ def test_serialize_notebook_multiple_cells(session_view: SessionView):
view = session_view
cell_manager = CellManager()
- # Register first cell
- cell_id1 = CellId_t("cell1")
cell_manager.register_cell(
- cell_id=cell_id1,
+ cell_id=CELL1,
code="x = 1",
name="setup",
config=CellConfig(column=0, disabled=False),
)
- # Register second cell
- cell_id2 = CellId_t("cell2")
cell_manager.register_cell(
- cell_id=cell_id2,
+ cell_id=CELL2,
code="print(x + 1)",
name="output",
config=CellConfig(column=1, hide_code=True),
)
- # Add first cell to session view
- view.cell_notifications[cell_id1] = CellNotification(
- cell_id=cell_id1,
- status="idle",
- output=None,
- console=[],
- timestamp=0,
- )
- view.last_executed_code[cell_id1] = "x = 1"
+ view.cell_notifications[CELL1] = _make_cell_notification(CELL1)
+ view.last_executed_code[CELL1] = "x = 1"
- # Add second cell to session view
- view.cell_notifications[cell_id2] = CellNotification(
- cell_id=cell_id2,
- status="idle",
+ view.cell_notifications[CELL2] = _make_cell_notification(
+ CELL2,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="2",
),
- console=[],
- timestamp=0,
)
- view.last_executed_code[cell_id2] = "print(x + 1)"
+ view.last_executed_code[CELL2] = "print(x + 1)"
result = serialize_notebook(view, cell_manager)
@@ -258,44 +256,32 @@ def test_serialize_notebook_multiple_cells_not_top_down(
view = session_view
cell_manager = CellManager()
- cell_id1 = CellId_t("cell1")
cell_manager.register_cell(
- cell_id=cell_id1,
+ cell_id=CELL1,
code="print(x + 1)",
name="output",
config=CellConfig(column=1, hide_code=True),
)
- cell_id2 = CellId_t("cell2")
cell_manager.register_cell(
- cell_id=cell_id2,
+ cell_id=CELL2,
code="x = 2",
name="setup",
config=CellConfig(column=0, disabled=False),
)
- view.cell_notifications[cell_id2] = CellNotification(
- cell_id=cell_id2,
- status="idle",
- output=None,
- console=[],
- timestamp=0,
- )
- view.last_executed_code[cell_id2] = "x = 1"
+ view.cell_notifications[CELL2] = _make_cell_notification(CELL2)
+ view.last_executed_code[CELL2] = "x = 1"
- # Add second cell to session view
- view.cell_notifications[cell_id1] = CellNotification(
- cell_id=cell_id1,
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="2",
),
- console=[],
- timestamp=0,
)
- view.last_executed_code[cell_id1] = "print(x + 1)"
+ view.last_executed_code[CELL1] = "print(x + 1)"
result = serialize_notebook(view, cell_manager)
@@ -321,23 +307,15 @@ def test_serialize_notebook_empty_code(session_view: SessionView):
view = session_view
cell_manager = CellManager()
- # Register cell with cell manager but with different code
- cell_id = CellId_t("cell1")
cell_manager.register_cell(
- cell_id=cell_id,
+ cell_id=CELL1,
code="# Original code",
name="empty_cell",
config=CellConfig(),
)
# Add to session view but without executed code
- view.cell_notifications[cell_id] = CellNotification(
- cell_id=cell_id,
- status="idle",
- output=None,
- console=[],
- timestamp=0,
- )
+ view.cell_notifications[CELL1] = _make_cell_notification(CELL1)
# No entry in last_executed_code
result = serialize_notebook(view, cell_manager)
@@ -382,16 +360,13 @@ def test_serialize_notebook_missing_cell_data(session_view: SessionView):
# Add cell to session view but don't register it with cell manager
cell_id = CellId_t("orphan_cell")
- view.cell_notifications[cell_id] = CellNotification(
- cell_id=cell_id,
- status="idle",
+ view.cell_notifications[cell_id] = _make_cell_notification(
+ cell_id,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="orphan output",
),
- console=[],
- timestamp=0,
)
view.last_executed_code[cell_id] = "print('orphan')"
@@ -516,21 +491,19 @@ def test_deserialize_session_with_console():
async def test_session_cache_writer(session_view: SessionView):
"""Test AsyncWriter writes session data periodically"""
view = session_view
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
+ doc = _make_document(CELL1)
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="test data",
),
- console=[],
- timestamp=0,
)
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "session.json"
- writer = SessionCacheWriter(view, path, interval=0.1)
+ writer = SessionCacheWriter(view, doc, path, interval=0.1)
# Start writer and wait for first write
writer.start()
@@ -549,10 +522,11 @@ async def test_session_cache_writer(session_view: SessionView):
async def test_session_cache_writer_no_writes(session_view: SessionView):
"""Test AsyncWriter does not write when no changes"""
view = session_view
+ doc = _make_document()
view.mark_auto_export_session()
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "session.json"
- writer = SessionCacheWriter(view, path, interval=0.1)
+ writer = SessionCacheWriter(view, doc, path, interval=0.1)
writer.start()
await asyncio.sleep(0.2)
assert not path.exists()
@@ -774,9 +748,8 @@ def test_deserialize_session_with_console_mimetype():
def test_serialize_session_with_dict_error():
"""Test serialization of a session with a dictionary error"""
view = SessionView()
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.MARIMO_ERROR,
mimetype="application/vnd.marimo+error",
@@ -784,14 +757,12 @@ def test_serialize_session_with_dict_error():
{"type": "unknown", "msg": "Something went wrong"}
], # Dictionary instead of Error object
),
- console=[],
- timestamp=0,
)
- view.last_executed_code["cell1"] = (
+ view.last_executed_code[CELL1] = (
"raise RuntimeError('Something went wrong')"
)
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL1])
assert len(result["cells"]) == 1
assert len(result["cells"][0]["outputs"]) == 1
assert result["cells"][0]["outputs"][0]["type"] == "error"
@@ -816,22 +787,17 @@ def test_serialize_session_with_mixed_error_formats(session_view: SessionView):
UnknownError(msg="Runtime error occurred", error_type="RuntimeError"),
]
- view.cell_notifications[CellId_t("cell1")] = CellNotification(
- cell_id=CellId_t("cell1"),
- status="idle",
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.MARIMO_ERROR,
mimetype="application/vnd.marimo+error",
data=mixed_errors,
),
- console=[],
- timestamp=0,
- )
- view.last_executed_code[CellId_t("cell1")] = (
- "# code that causes mixed errors"
)
+ view.last_executed_code[CELL1] = "# code that causes mixed errors"
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL1])
# Verify the error normalization worked correctly
assert len(result["cells"]) == 1
@@ -863,18 +829,20 @@ class TestSessionCacheManager:
def test_init_without_path(self, session_view: SessionView):
"""Test initialization without path"""
view = session_view
- manager = SessionCacheManager(view, None, 0.1)
+ doc = _make_document()
+ manager = SessionCacheManager(view, doc, None, 0.1)
manager.start()
assert manager.session_cache_writer is None
async def test_rename_path(self, session_view: SessionView):
"""Test renaming path updates writer"""
view = session_view
+ doc = _make_document()
with tempfile.TemporaryDirectory() as tmpdir:
old_path = Path(tmpdir) / "old.py"
new_path = Path(tmpdir) / "new.py"
- manager = SessionCacheManager(view, old_path, 0.1)
+ manager = SessionCacheManager(view, doc, old_path, 0.1)
manager.start()
assert manager.session_cache_writer is not None
old_writer = manager.session_cache_writer
@@ -887,7 +855,8 @@ class TestSessionCacheManager:
def test_read_session_view_no_path(self, session_view: SessionView):
"""Test reading session view without path"""
view = session_view
- manager = SessionCacheManager(view, None, 0.1)
+ doc = _make_document()
+ manager = SessionCacheManager(view, doc, None, 0.1)
assert (
manager.read_session_view(
SessionCacheKey(
@@ -900,9 +869,10 @@ class TestSessionCacheManager:
def test_read_session_view_no_cache(self, session_view: SessionView):
"""Test reading session view with no cache file"""
view = session_view
+ doc = _make_document()
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "notebook.py"
- manager = SessionCacheManager(view, path, 0.1)
+ manager = SessionCacheManager(view, doc, path, 0.1)
assert (
manager.read_session_view(
SessionCacheKey(
@@ -917,16 +887,14 @@ class TestSessionCacheManager:
):
"""Test reading session view from cache file"""
view = session_view
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
+ doc = _make_document(CELL1)
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="test data",
),
- console=[],
- timestamp=0,
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -935,16 +903,16 @@ class TestSessionCacheManager:
cache_file.parent.mkdir(parents=True)
# Write cache file
- data = serialize_session_view(view)
+ data = serialize_session_view(view, cell_ids=[CELL1])
cache_file.write_text(json.dumps(data))
# Read back
- manager = SessionCacheManager(SessionView(), path, 0.1)
+ manager = SessionCacheManager(SessionView(), doc, path, 0.1)
loaded_view = manager.read_session_view(
SessionCacheKey(
codes=(None,),
marimo_version=__version__,
- cell_ids=("cell1",),
+ cell_ids=(CELL1,),
)
)
assert loaded_view.cell_notifications is not None
@@ -954,19 +922,17 @@ class TestSessionCacheManager:
):
"""Test reading session view from cache file"""
view = session_view
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
+ doc = _make_document(CELL1)
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
output=CellOutput(
channel=CellChannel.OUTPUT,
mimetype="text/plain",
data="test data",
),
- console=[],
- timestamp=0,
)
view.add_control_request(
- ExecuteCellsCommand(cell_ids=["cell1"], codes=["a"])
+ ExecuteCellsCommand(cell_ids=[CELL1], codes=["a"])
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -975,17 +941,17 @@ class TestSessionCacheManager:
cache_file.parent.mkdir(parents=True)
# Write cache file
- data = serialize_session_view(view)
+ data = serialize_session_view(view, cell_ids=[CELL1])
cache_file.write_text(json.dumps(data))
# Read back
- manager = SessionCacheManager(SessionView(), path, 0.1)
+ manager = SessionCacheManager(SessionView(), doc, path, 0.1)
loaded_view = manager.read_session_view(
# foo != a, cache miss
SessionCacheKey(
codes=("foo",),
marimo_version=__version__,
- cell_ids=("cell1",),
+ cell_ids=(CELL1,),
)
)
assert not loaded_view.cell_notifications
@@ -995,8 +961,10 @@ class TestSessionCacheManager:
):
"""Test reading session view from cache file"""
view = session_view
+ id1, id2 = CellId_t("1"), CellId_t("2")
+ doc = _make_document(id1, id2)
view.add_control_request(
- ExecuteCellsCommand(cell_ids=["1", "2"], codes=["a", "b"])
+ ExecuteCellsCommand(cell_ids=[id1, id2], codes=["a", "b"])
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -1005,11 +973,11 @@ class TestSessionCacheManager:
cache_file.parent.mkdir(parents=True)
# Write cache file
- data = serialize_session_view(view)
+ data = serialize_session_view(view, cell_ids=[id1, id2])
cache_file.write_text(json.dumps(data))
# Read back
- manager = SessionCacheManager(SessionView(), path, 0.1)
+ manager = SessionCacheManager(SessionView(), doc, path, 0.1)
loaded_view = manager.read_session_view(
SessionCacheKey(
codes=(
@@ -1017,7 +985,7 @@ class TestSessionCacheManager:
"b",
),
marimo_version="-1",
- cell_ids=("1", "2"),
+ cell_ids=(id1, id2),
)
)
assert not loaded_view.cell_notifications
@@ -1027,8 +995,10 @@ class TestSessionCacheManager:
):
"""Test reading session view from cache file."""
view = session_view
+ id1, id2 = CellId_t("1"), CellId_t("2")
+ doc = _make_document(id1, id2)
view.add_control_request(
- ExecuteCellsCommand(cell_ids=["1", "2"], codes=["a", "b"])
+ ExecuteCellsCommand(cell_ids=[id1, id2], codes=["a", "b"])
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -1036,10 +1006,12 @@ class TestSessionCacheManager:
cache_file = get_session_cache_file(path)
cache_file.parent.mkdir(parents=True)
- data = serialize_session_view(view, script_metadata_hash="old")
+ data = serialize_session_view(
+ view, cell_ids=[id1, id2], script_metadata_hash="old"
+ )
cache_file.write_text(json.dumps(data))
- manager = SessionCacheManager(SessionView(), path, 0.1)
+ manager = SessionCacheManager(SessionView(), doc, path, 0.1)
loaded_view = manager.read_session_view(
SessionCacheKey(
codes=(
@@ -1047,7 +1019,7 @@ class TestSessionCacheManager:
"b",
),
marimo_version=__version__,
- cell_ids=("1", "2"),
+ cell_ids=(id1, id2),
script_metadata_hash="new",
)
)
@@ -1058,31 +1030,21 @@ class TestSessionCacheManager:
):
"""Test reading session view from cache file"""
view = session_view
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
- status="idle",
- output=CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="text/plain",
- data="test data",
- ),
- console=[],
- timestamp=0,
+ doc = _make_document(CELL1, CELL2)
+ test_output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="test data",
)
- view.cell_notifications["cell2"] = CellNotification(
- cell_id="cell2",
- status="idle",
- output=CellOutput(
- channel=CellChannel.OUTPUT,
- mimetype="text/plain",
- data="test data",
- ),
- console=[],
- timestamp=0,
+ view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1, output=test_output
+ )
+ view.cell_notifications[CELL2] = _make_cell_notification(
+ CELL2, output=test_output
)
view.add_control_request(
- ExecuteCellsCommand(cell_ids=["cell1", "cell2"], codes=["a", "b"])
+ ExecuteCellsCommand(cell_ids=[CELL1, CELL2], codes=["a", "b"])
)
with tempfile.TemporaryDirectory() as tmpdir:
@@ -1091,11 +1053,11 @@ class TestSessionCacheManager:
cache_file.parent.mkdir(parents=True)
# Write cache file
- data = serialize_session_view(view)
+ data = serialize_session_view(view, cell_ids=[CELL1, CELL2])
cache_file.write_text(json.dumps(data))
# Read back
- manager = SessionCacheManager(SessionView(), path, 0.1)
+ manager = SessionCacheManager(SessionView(), doc, path, 0.1)
loaded_view = manager.read_session_view(
SessionCacheKey(
codes=(
@@ -1103,7 +1065,7 @@ class TestSessionCacheManager:
"b",
),
marimo_version=__version__,
- cell_ids=("cell1", "cell2"),
+ cell_ids=(CELL1, CELL2),
)
)
# cache hit: codes and version match
diff --git a/tests/_session/state/test_serialize_session_missing_type.py b/tests/_session/state/test_serialize_session_missing_type.py
index a1238ba46f..ae96d2aa28 100644
--- a/tests/_session/state/test_serialize_session_missing_type.py
+++ b/tests/_session/state/test_serialize_session_missing_type.py
@@ -4,13 +4,16 @@ from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.notification import CellNotification
from marimo._session.state.serialize import serialize_session_view
from marimo._session.state.session_view import SessionView
+from marimo._types.ids import CellId_t
+
+CELL_ID = CellId_t("cell1")
def test_serialize_session_with_dict_error_missing_type():
"""Test serialization of a session with a dictionary error missing the type key"""
view = SessionView()
- view.cell_notifications["cell1"] = CellNotification(
- cell_id="cell1",
+ view.cell_notifications[CELL_ID] = CellNotification(
+ cell_id=CELL_ID,
status="idle",
output=CellOutput(
channel=CellChannel.MARIMO_ERROR,
@@ -22,11 +25,11 @@ def test_serialize_session_with_dict_error_missing_type():
console=[],
timestamp=0,
)
- view.last_executed_code["cell1"] = (
+ view.last_executed_code[CELL_ID] = (
"raise RuntimeError('Something went wrong')"
)
- result = serialize_session_view(view)
+ result = serialize_session_view(view, cell_ids=[CELL_ID])
assert len(result["cells"]) == 1
assert len(result["cells"][0]["outputs"]) == 1
assert result["cells"][0]["outputs"][0]["type"] == "error"