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: Serialization fix (#5398)

Dylan Madisetti77e95562fb48
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 1571a27a12..b7134b88f1 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -354,4 +354,5 @@ async def run_app_until_completion(
# Stop distributor, terminate kernel process, etc -- all information is
# captured by the session view.
session.close()
+
return session.session_view, session_consumer.did_error
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 5f8b24b842..00d18e8802 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -106,7 +106,9 @@ class Exporter:
config = deep_copy(DEFAULT_CONFIG)
config["display"] = display_config
- session_snapshot = serialize_session_view(session_view)
+ session_snapshot = serialize_session_view(
+ session_view, cell_ids=file_manager.app.cell_manager.cell_ids()
+ )
notebook_snapshot = serialize_notebook(
session_view, file_manager.app.cell_manager
)
diff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.py
index 945927d15c..ef2579dd80 100644
--- a/marimo/_server/session/serialize.py
+++ b/marimo/_server/session/serialize.py
@@ -7,7 +7,7 @@ import json
import os
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Optional, Union, cast
from marimo import __version__, _loggers
from marimo._ast.cell_manager import CellManager
@@ -42,6 +42,9 @@ from marimo._utils.async_path import AsyncPath
from marimo._utils.background_task import AsyncBackgroundTask
from marimo._utils.lists import as_list
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
LOGGER = _loggers.marimo_logger()
@@ -63,11 +66,38 @@ def _normalize_error(error: Union[MarimoError, dict[str, Any]]) -> ErrorOutput:
)
-def serialize_session_view(view: SessionView) -> NotebookSessionV1:
- """Convert a SessionView to a NotebookSession schema."""
+def serialize_session_view(
+ view: SessionView, cell_ids: Iterable[CellId_t] | None = None
+) -> NotebookSessionV1:
+ """Convert a SessionView to a NotebookSession schema.
+
+ When `cell_ids` is provided, it determines the order of the cells in
+ the NotebookSession schema (and only these cells will be saved to the
+ schema). When not provided, this method attempts to recover the notebook
+ order from the SessionView object, but this is not always possible.
+ """
cells: list[Cell] = []
- for cell_id, cell_op in view.cell_operations.items():
+ if cell_ids is None:
+ if view.cell_ids is not None:
+ cell_ids = view.cell_ids.cell_ids
+ else:
+ LOGGER.warning(
+ "When serializing session view, the notebook-order of cells was "
+ "not known. This may cause issues when attempting to "
+ "reconstruct the notebook state from the serialized session "
+ "view."
+ )
+ cell_ids = view.cell_operations.keys()
+
+ for cell_id in cell_ids:
+ cell_op = view.cell_operations.get(cell_id)
+ if cell_op is None:
+ # We haven't seen any outputs or operations for this cell.
+ cells.append(
+ Cell(id=cell_id, code_hash=None, outputs=[], console=[])
+ )
+ continue
outputs: list[OutputType] = []
console: list[ConsoleType] = []
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 88fe2b84e0..ee77c2c44e 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -56,16 +56,23 @@ class AutoExportState:
class SessionView:
- """
- This stores the current view of the session.
+ """A representation of a session state for replay and serialization.
+
+ Of note, a SessionView stores:
+ * the last-seen notebook-order of Cell IDs
+ * a mapping from cell IDs to their last seen operation of interest,
+ such as an output, status, or console output
+ * various other state needed for replay
- Which are the cell's outputs, status, and console.
+ A notebook session can be hydrated from a serialized SessionView,
+ for example on notebook startup when auto-instantiate is off, or
+ on reconnection via a replay.
"""
def __init__(self) -> None:
- # Last seen cell IDs
+ # Last seen notebook-order of cell IDs
self.cell_ids: Optional[UpdateCellIdsRequest] = None
- # List of operations we care about keeping track of.
+ # A mapping from cell (IDs) to their last seen operation
self.cell_operations: dict[CellId_t, CellOp] = {}
# The most recent datasets operation.
self.datasets = Datasets(tables=[])