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.

fix: deserialize session by code hash match (#7076)

Myles Scolnick2318f5367478
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index e8d6640aa0..fd65546fd9 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -173,8 +173,18 @@ def serialize_session_view(
)
-def deserialize_session(session: NotebookSessionV1) -> SessionView:
- """Convert a NotebookSession schema to a SessionView."""
+def deserialize_session(
+ session: NotebookSessionV1,
+ code_hash_to_cell_id: dict[str, CellId_t],
+) -> SessionView:
+ """Convert a NotebookSession schema to a SessionView.
+
+ Args:
+ session: The serialized notebook session
+ code_hash_to_cell_id: Mapping from code hash to current cell ID.
+ Cells are matched by code hash instead of using the stored cell_id,
+ which handles cases where cells were added/deleted.
+ """
view = SessionView()
for cell in session["cells"]:
@@ -266,7 +276,22 @@ def deserialize_session(session: NotebookSessionV1) -> SessionView:
)
)
- cell_id = CellId_t(cell["id"])
+ # Match cell by code_hash
+ if cell["code_hash"] is None:
+ # No code hash available - skip this cell
+ LOGGER.debug(
+ f"Skipping cached output for cell {cell['id']} - no code_hash"
+ )
+ continue
+
+ cell_id = code_hash_to_cell_id.get(cell["code_hash"])
+ if cell_id is None:
+ # No matching cell found by code hash - skip this cell
+ LOGGER.debug(
+ f"Skipping cached output for cell with hash "
+ f"{cell['code_hash'][:8]}... - no matching cell found"
+ )
+ continue
view.cell_operations[cell_id] = CellOp(
cell_id=cell_id,
@@ -391,6 +416,7 @@ class SessionCacheWriter(AsyncBackgroundTask):
class SessionCacheKey:
codes: tuple[str | None, ...]
marimo_version: str
+ cell_ids: tuple[CellId_t, ...]
class SessionCacheManager:
@@ -475,5 +501,16 @@ class SessionCacheManager:
LOGGER.info("Session view cache miss")
return self.session_view
- self.session_view = deserialize_session(notebook_session)
+ # Build mapping from code_hash to cell_id based on current cell IDs
+ # This handles cases where cell_ids have changed even though code matches
+ code_hash_to_cell_id: dict[str, CellId_t] = {}
+ for code, cell_id in zip(key.codes, key.cell_ids):
+ code_hash = _hash_code(code)
+ if code_hash is not None:
+ # Map the code_hash to the current cell_id from the key
+ code_hash_to_cell_id[code_hash] = cell_id
+
+ self.session_view = deserialize_session(
+ notebook_session, code_hash_to_cell_id
+ )
return self.session_view
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index e50edc57af..3538122f68 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -740,7 +740,10 @@ class Session:
codes = tuple(
cell_data.code for cell_data in app.cell_manager.cell_data()
)
- key = SessionCacheKey(codes=codes, marimo_version=__version__)
+ cell_ids = tuple(app.cell_manager.cell_ids())
+ key = SessionCacheKey(
+ codes=codes, marimo_version=__version__, cell_ids=cell_ids
+ )
self.session_view = self.session_cache_manager.read_session_view(key)
self.session_cache_manager.start()
diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.py
index a33b4ed798..627f7501a2 100644
--- a/tests/_server/session/test_serialize_session.py
+++ b/tests/_server/session/test_serialize_session.py
@@ -33,6 +33,17 @@ from tests.mocks import snapshotter
snapshot = snapshotter(__file__)
+def _build_code_hash_to_cell_id_mapping(
+ session: NotebookSessionV1,
+) -> dict[str, CellId_t]:
+ """Helper to build code_hash to cell_id mapping for tests."""
+ mapping: dict[str, CellId_t] = {}
+ for cell in session["cells"]:
+ if cell["code_hash"] is not None:
+ mapping[cell["code_hash"]] = CellId_t(cell["id"])
+ return 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
@@ -416,7 +427,8 @@ def test_deserialize_basic_session():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert CellId_t("cell1") in view.cell_operations
cell = view.cell_operations[CellId_t("cell1")]
assert cell.output is not None
@@ -447,7 +459,8 @@ def test_deserialize_session_with_error():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert "cell1" in view.cell_operations
cell = view.cell_operations["cell1"]
assert cell.output is not None
@@ -485,7 +498,8 @@ def test_deserialize_session_with_console():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert "cell1" in view.cell_operations
cell = view.cell_operations["cell1"]
assert isinstance(cell.console, list)
@@ -598,7 +612,8 @@ def test_deserialize_mime_bundle():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert "cell1" in view.cell_operations
cell = view.cell_operations["cell1"]
assert cell.output is not None
@@ -625,7 +640,8 @@ def test_deserialize_empty_data():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert "cell1" in view.cell_operations
cell = view.cell_operations["cell1"]
assert cell.output is None
@@ -672,7 +688,8 @@ def test_deserialize_error_with_traceback():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert "eAXK" in view.cell_operations
cell = view.cell_operations["eAXK"]
assert cell.output is not None
@@ -721,7 +738,8 @@ def test_deserialize_session_with_console_mimetype():
],
)
- view = deserialize_session(session)
+ code_hash_to_cell_id = _build_code_hash_to_cell_id_mapping(session)
+ view = deserialize_session(session, code_hash_to_cell_id)
assert "cell1" in view.cell_operations
cell = view.cell_operations["cell1"]
assert isinstance(cell.console, list)
@@ -854,7 +872,9 @@ class TestSessionCacheManager:
manager = SessionCacheManager(view, None, 0.1)
assert (
manager.read_session_view(
- SessionCacheKey(codes=tuple(), marimo_version="-1")
+ SessionCacheKey(
+ codes=tuple(), marimo_version="-1", cell_ids=tuple()
+ )
)
== view
)
@@ -867,7 +887,9 @@ class TestSessionCacheManager:
manager = SessionCacheManager(view, path, 0.1)
assert (
manager.read_session_view(
- SessionCacheKey(codes=tuple(), marimo_version="-1")
+ SessionCacheKey(
+ codes=tuple(), marimo_version="-1", cell_ids=tuple()
+ )
)
== view
)
@@ -901,12 +923,13 @@ class TestSessionCacheManager:
# Read back
manager = SessionCacheManager(SessionView(), path, 0.1)
loaded_view = manager.read_session_view(
- SessionCacheKey(codes=(None,), marimo_version=__version__)
+ SessionCacheKey(
+ codes=(None,),
+ marimo_version=__version__,
+ cell_ids=("cell1",),
+ )
)
- assert "cell1" in loaded_view.cell_operations
- cell = loaded_view.cell_operations["cell1"]
- assert cell.output is not None
- assert cell.output.data == "test data"
+ assert loaded_view.cell_operations is not None
async def test_read_session_view_cache_miss_code(
self, session_view: SessionView
@@ -941,7 +964,11 @@ class TestSessionCacheManager:
manager = SessionCacheManager(SessionView(), path, 0.1)
loaded_view = manager.read_session_view(
# foo != a, cache miss
- SessionCacheKey(codes=("foo",), marimo_version=__version__)
+ SessionCacheKey(
+ codes=("foo",),
+ marimo_version=__version__,
+ cell_ids=("cell1",),
+ )
)
assert not loaded_view.cell_operations
@@ -972,6 +999,7 @@ class TestSessionCacheManager:
"b",
),
marimo_version="-1",
+ cell_ids=("1", "2"),
)
)
assert not loaded_view.cell_operations
@@ -1028,6 +1056,7 @@ class TestSessionCacheManager:
"b",
),
marimo_version=__version__,
+ cell_ids=("cell1", "cell2"),
)
)
# cache hit: codes and version match