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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: Session Schema and Serialize outputs (#3807)
Myles Scolnick715fbb5fea60
diff --git a/.github/workflows/test_schemas.yaml b/.github/workflows/test_schemas.yamlnew file mode 100644index 0000000000..f971d5016c--- /dev/null+++ b/.github/workflows/test_schemas.yaml@@ -0,0 +1,123 @@+name: Schema Breaking Changes Check++on:+ pull_request:+ paths:+ - '**/*.yaml'++jobs:+ changes:+ runs-on: ubuntu-latest+ outputs:+ openapi: ${{ steps.filter.outputs.openapi }}+ session: ${{ steps.filter.outputs.session }}+ steps:+ - uses: actions/checkout@v4+ - uses: dorny/paths-filter@v3+ id: filter+ with:+ filters: |+ openapi:+ - 'openapi/api.yaml'+ session:+ - 'marimo/_schemas/generated/session.yaml'++ check-openapi:+ needs: changes+ if: ${{ needs.changes.outputs.openapi == 'true' }}+ runs-on: ubuntu-latest+ env:+ SCHEMA_PATH: openapi/api.yaml+ steps:+ - name: Checkout current branch+ uses: actions/checkout@v4+ with:+ path: current++ - name: Checkout main branch+ uses: actions/checkout@v4+ with:+ ref: main+ path: main++ - name: Install oasdiff+ run: |+ curl -sSL https://raw.githubusercontent.com/tufin/oasdiff/master/install.sh | sh++ - name: Compare OpenAPI specs+ id: compare+ run: |+ BREAKING_CHANGES=$(oasdiff breaking main/${{ env.SCHEMA_PATH }} current/${{ env.SCHEMA_PATH }})+ if [ -n "$BREAKING_CHANGES" ]; then+ echo "Breaking changes detected:"+ echo "$BREAKING_CHANGES"+ exit 1+ else+ echo "No breaking changes detected"+ fi++ - name: Comment on PR+ if: failure()+ uses: actions/github-script@v7+ with:+ script: |+ const output = `Breaking changes detected in the OpenAPI specification!++ ${process.env.BREAKING_CHANGES}`++ github.rest.issues.createComment({+ issue_number: context.issue.number,+ owner: context.repo.owner,+ repo: context.repo.repo,+ body: output+ })++ check-session:+ needs: changes+ if: ${{ needs.changes.outputs.session == 'true' }}+ runs-on: ubuntu-latest+ env:+ SCHEMA_PATH: marimo/_schemas/generated/session.yaml+ steps:+ - name: Checkout current branch+ uses: actions/checkout@v4+ with:+ path: current++ - name: Checkout main branch+ uses: actions/checkout@v4+ with:+ ref: main+ path: main++ - name: Install oasdiff+ run: |+ curl -sSL https://raw.githubusercontent.com/tufin/oasdiff/master/install.sh | sh++ - name: Compare Session Schema+ id: compare+ run: |+ BREAKING_CHANGES=$(oasdiff breaking main/${{ env.SCHEMA_PATH }} current/${{ env.SCHEMA_PATH }})+ if [ -n "$BREAKING_CHANGES" ]; then+ echo "Breaking changes detected:"+ echo "$BREAKING_CHANGES"+ exit 1+ else+ echo "No breaking changes detected"+ fi++ - name: Comment on PR+ if: failure()+ uses: actions/github-script@v7+ with:+ script: |+ const output = `Breaking changes detected in the Session Schema!++ ${process.env.BREAKING_CHANGES}`++ github.rest.issues.createComment({+ issue_number: context.issue.number,+ owner: context.repo.owner,+ repo: context.repo.repo,+ body: output+ })diff --git a/development_docs/openapi.md b/development_docs/openapi.mdindex 0f98e714ed..b5c5028eb9 100644--- a/development_docs/openapi.md+++ b/development_docs/openapi.md@@ -10,7 +10,7 @@ marimo development openapi## Writing a new OpenAPI schema-To modify the schema, add the type under `_generate_schema` in [`commands.py`](/marimo/_cli/development/commands.py) and run+To modify the schema, add the type under `_generate_server_api_schema` in [`commands.py`](/marimo/_cli/development/commands.py) and run```bashmarimo development openapi > openapi/api.yaml@@ -34,4 +34,4 @@ You will then need to reinstall the package in `/frontend`:```bashcd frontendpnpm update @marimo-team/marimo-api-```\ No newline at end of file+```diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 91e4f18763..c225adc006 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -15,7 +15,7 @@ if TYPE_CHECKING:import psutil-def _generate_schema() -> dict[str, Any]:+def _generate_server_api_schema() -> dict[str, Any]:from starlette.schemas import SchemaGeneratorimport marimo._data.models as data@@ -264,7 +264,9 @@ def openapi() -> None:"""import yaml- click.echo(yaml.dump(_generate_schema(), default_flow_style=False))+ click.echo(+ yaml.dump(_generate_server_api_schema(), default_flow_style=False)+ )@click.group(help="Various commands for the marimo processes", hidden=True)diff --git a/marimo/_schemas/generated/session.yaml b/marimo/_schemas/generated/session.yamlnew file mode 100644index 0000000000..9e3e0a969d--- /dev/null+++ b/marimo/_schemas/generated/session.yaml@@ -0,0 +1,119 @@+# This file is generated by scripts/generate_schemas.py+components:+ schemas:+ Cell:+ properties:+ code_hash:+ nullable: true+ type: string+ console:+ items:+ $ref: '#/components/schemas/StreamOutput'+ type: array+ id:+ type: string+ outputs:+ items:+ oneOf:+ - $ref: '#/components/schemas/ErrorOutput'+ - $ref: '#/components/schemas/DataOutput'+ type: array+ required:+ - id+ - code_hash+ - outputs+ - console+ type: object+ DataOutput:+ properties:+ data:+ additionalProperties: {}+ type: object+ type:+ enum:+ - data+ type: string+ required:+ - type+ - data+ type: object+ ErrorOutput:+ properties:+ ename:+ type: string+ evalue:+ type: string+ traceback:+ items:+ type: string+ type: array+ type:+ enum:+ - error+ type: string+ required:+ - type+ - ename+ - evalue+ - traceback+ type: object+ NotebookMetadata:+ properties:+ marimo_version:+ nullable: true+ type: string+ required:+ - marimo_version+ type: object+ NotebookSessionV1:+ properties:+ cells:+ items:+ $ref: '#/components/schemas/Cell'+ type: array+ metadata:+ $ref: '#/components/schemas/NotebookMetadata'+ version:+ type: string+ required:+ - version+ - metadata+ - cells+ type: object+ StreamOutput:+ properties:+ name:+ enum:+ - stdout+ - stderr+ type: string+ text:+ type: string+ type:+ enum:+ - stream+ type: string+ required:+ - type+ - name+ - text+ type: object+ TimeMetadata:+ properties:+ completed:+ nullable: true+ type: string+ duration:+ nullable: true+ type: number+ started:+ nullable: true+ type: string+ required:+ - started+ - completed+ - duration+ type: object+info:+ title: marimo_session+openapi: 3.0.0diff --git a/marimo/_schemas/session.py b/marimo/_schemas/session.pynew file mode 100644index 0000000000..2dd0b470be--- /dev/null+++ b/marimo/_schemas/session.py@@ -0,0 +1,85 @@+from __future__ import annotations++from typing import Any, Dict, List, Literal, Optional, TypedDict, Union+++# Base types for extensibility+class BaseDict(TypedDict, total=False):+ """Base dictionary allowing additional fields"""++ pass+++# Metadata types+class TimeMetadata(BaseDict):+ started: Optional[str]+ completed: Optional[str]+ duration: Optional[float]+++# Output types+class StreamOutput(BaseDict):+ type: Literal["stream"]+ name: Literal["stdout", "stderr"]+ text: str+++class ErrorOutput(BaseDict):+ type: Literal["error"]+ ename: str+ evalue: str+ traceback: List[str]+++class DataOutput(BaseDict):+ type: Literal["data"]+ data: Dict[str, Any] # MIME-type bundles+++# Union of all possible output types+OutputType = Union[+ ErrorOutput,+ DataOutput,+ # Dict[str, Any], # For future output types, forwards-compatible+]+++class Cell(BaseDict):+ """Code cell specific structure"""++ id: str+ code_hash: Optional[str]+ outputs: List[OutputType]+ console: List[StreamOutput]++ # We don't need to store code or cell config+ # since that exists in the notebook.py itself+++# Notebook metadata+class NotebookMetadata(BaseDict):+ """Metadata about the notebook"""++ marimo_version: Optional[str]++ # We don't need to store AppConfig+ # since that exists in the notebook.py itself+++# Main notebook structure+class NotebookSessionV1(BaseDict):+ """Main notebook structure"""++ # The notebook format version+ version: str+ # Metadata about the notebook+ metadata: NotebookMetadata+ # The cells in the notebook+ cells: List[Cell]++ # In future, we may want to add+ # - variables+ # - datasets+++VERSION = "1"diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex 55c0b2937a..eb8cf41fab 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -109,7 +109,7 @@ async def auto_export_as_html(session_view = session.session_view# If we have already exported to HTML, don't do it again- if session_view.has_auto_exported_html:+ if not session_view.needs_export("html"):LOGGER.debug("Already auto-exported to HTML")return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)@@ -254,7 +254,7 @@ async def auto_export_as_markdown(session_view = session.session_view# If we have already exported to Markdown, don't do it again- if session_view.has_auto_exported_md:+ if not session_view.needs_export("md"):LOGGER.debug("Already auto-exported to Markdown")return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)@@ -302,7 +302,7 @@ async def auto_export_as_ipynb(session_view = session.session_view# If we have already exported to IPYNB, don't do it again- if session_view.has_auto_exported_ipynb:+ if not session_view.needs_export("ipynb"):LOGGER.debug("Already auto-exported to IPYNB")return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.pyindex cf05cc86b6..ea749ba477 100644--- a/marimo/_server/api/endpoints/files.py+++ b/marimo/_server/api/endpoints/files.py@@ -104,7 +104,7 @@ async def rename_file(if new_path:# Handle rename for watchapp_state.session_manager.handle_file_rename_for_watch(- app_state.require_current_session_id(), new_path+ app_state.require_current_session_id(), prev_path, new_path)return SuccessResponse()diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex dd872b76f0..bd2f2b504f 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -88,11 +88,10 @@ async def websocket_endpoint(kiosk = app_state.query_params(KIOSK_QUERY_PARAM_KEY) == "true"- rtc_enabled: bool = (- app_state.config_manager.get_config()- .get("experimental", {})- .get("rtc", False)- )+ config = app_state.config_manager.get_config()++ rtc_enabled: bool = config.get("experimental", {}).get("rtc", False)+ auto_instantiate = config["runtime"]["auto_instantiate"]await WebsocketHandler(websocket=websocket,@@ -102,6 +101,7 @@ async def websocket_endpoint(mode=app_state.mode,file_key=file_key,kiosk=kiosk,+ auto_instantiate=auto_instantiate,).start()@@ -271,6 +271,7 @@ class WebsocketHandler(SessionConsumer):mode: SessionMode,file_key: MarimoFileKey,kiosk: bool,+ auto_instantiate: bool,):self.websocket = websocketself.manager = manager@@ -280,11 +281,13 @@ class WebsocketHandler(SessionConsumer):self.mode = modeself.status: ConnectionStateself.kiosk = kiosk+ self.auto_instantiate = auto_instantiateself.cancel_close_handle: Optional[asyncio.TimerHandle] = Noneself.heartbeat_task: Optional[asyncio.Task[None]] = None# Messages from the kernel are put in this queue# to be sent to the frontendself.message_queue: asyncio.Queue[KernelMessage]+ self.ws_future: asyncio.Future[tuple[None, None]] | None = Nonesuper().__init__(consumer_id=ConsumerId(session_id))@@ -385,12 +388,6 @@ class WebsocketHandler(SessionConsumer):)return- operations = session.get_current_state().operations- # Replay the current session view- LOGGER.debug(- f"Replaying {len(operations)} operations to the consumer",- )-self._write_kernel_ready(session=session,resumed=True,@@ -407,9 +404,7 @@ class WebsocketHandler(SessionConsumer):))- for op in operations:- LOGGER.debug("Replaying operation %s", op)- self.write_operation(op)+ self._replay_previous_session(session)def _connect_kiosk(self, session: Session) -> None:"""Connect to a kiosk session.@@ -436,14 +431,17 @@ class WebsocketHandler(SessionConsumer):kiosk=True,)self.status = ConnectionState.OPEN+ self._replay_previous_session(session)+ def _replay_previous_session(self, session: Session) -> None:+ """Replay the previous session view."""operations = session.get_current_state().operations- # Replay the current session view- LOGGER.debug(- f"Replaying {len(operations)} operations to the kiosk consumer",- )+ if len(operations) == 0:+ LOGGER.debug("No operations to replay")+ return+ LOGGER.debug(f"Replaying {len(operations)} operations")for op in operations:- LOGGER.debug("Replaying operation %s", serialize(op))+ LOGGER.debug("Replaying operation %s", op)self.write_operation(op)def _on_disconnect(@@ -614,6 +612,10 @@ class WebsocketHandler(SessionConsumer):kiosk=False,)self.status = ConnectionState.OPEN+ # if auto-instantiate if false, replay the previous session+ if not self.auto_instantiate:+ new_session.sync_session_view_from_cache()+ self._replay_previous_session(new_session)return new_sessionget_session()@@ -687,11 +689,11 @@ class WebsocketHandler(SessionConsumer):)try:- self.future = asyncio.gather(+ self.ws_future = asyncio.gather(listen_for_messages_task,listen_for_disconnect_task,)- await self.future+ await self.ws_futureexcept asyncio.CancelledError:LOGGER.debug("Websocket terminated with CancelledError")pass@@ -723,7 +725,8 @@ class WebsocketHandler(SessionConsumer):))- self.future.cancel()+ if self.ws_future:+ self.ws_future.cancel()def connection_state(self) -> ConnectionState:return self.status@@ -771,10 +774,7 @@ class WebsocketHandler(SessionConsumer):self.status = ConnectionState.OPEN# Replay all operations- operations = session.get_current_state().operations- for op in operations:- LOGGER.debug("Replaying operation %s", serialize(op))- self.write_operation(op)+ self._replay_previous_session(session)HAS_TOASTED = Falsediff --git a/marimo/_server/session/serialize.py b/marimo/_server/session/serialize.pynew file mode 100644index 0000000000..941ef139fd--- /dev/null+++ b/marimo/_server/session/serialize.py@@ -0,0 +1,281 @@+from __future__ import annotations++import asyncio+import hashlib+import json+from pathlib import Path+from typing import List, Optional, cast++from marimo import __version__, _loggers+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.errors import (+ Error as MarimoError,+ MarimoExceptionRaisedError,+)+from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.ops import CellOp+from marimo._schemas.session import (+ VERSION,+ Cell,+ DataOutput,+ ErrorOutput,+ NotebookMetadata,+ NotebookSessionV1,+ OutputType,+ StreamOutput,+)+from marimo._server.session.session_view import SessionView+from marimo._utils.background_task import AsyncBackgroundTask+from marimo._utils.lists import as_list++LOGGER = _loggers.marimo_logger()+++def serialize_session_view(view: SessionView) -> NotebookSessionV1:+ """Convert a SessionView to a NotebookSession schema."""+ cells: List[Cell] = []++ for cell_id, cell_op in view.cell_operations.items():+ outputs: List[OutputType] = []+ console: List[StreamOutput] = []++ # Convert output+ if cell_op.output:+ if cell_op.output.channel == CellChannel.MARIMO_ERROR:+ for error in cast(List[MarimoError], cell_op.output.data):+ outputs.append(+ ErrorOutput(+ type="error",+ ename=error.type,+ evalue=error.describe(),+ traceback=[],+ )+ )+ else:+ outputs.append(+ DataOutput(+ type="data",+ data={+ cell_op.output.mimetype: cell_op.output.data,+ },+ )+ )++ # Convert console outputs+ for console_out in as_list(cell_op.console):+ assert isinstance(console_out, CellOutput)+ if console_out:+ console.append(+ StreamOutput(+ type="stream",+ name="stderr"+ if console_out.channel == CellChannel.STDERR+ else "stdout",+ text=str(console_out.data),+ )+ )++ code_hash = _hash_code(view.last_executed_code.get(cell_id))++ cells.append(+ Cell(+ id=cell_id,+ code_hash=code_hash,+ outputs=outputs,+ console=console,+ )+ )++ return NotebookSessionV1(+ version=VERSION,+ metadata=NotebookMetadata(marimo_version=__version__),+ cells=cells,+ )+++def deserialize_session(session: NotebookSessionV1) -> SessionView:+ """Convert a NotebookSession schema to a SessionView."""+ view = SessionView()++ for cell in session["cells"]:+ cell_outputs: List[CellOutput] = []++ # Convert outputs+ for output in cell["outputs"]:+ if output["type"] == "error":+ cell_outputs.append(+ CellOutput(+ channel=CellChannel.MARIMO_ERROR,+ mimetype="text/plain",+ data=[+ MarimoExceptionRaisedError(+ type="exception",+ exception_type=output["ename"],+ msg=output["evalue"],+ raising_cell=None,+ )+ ],+ )+ )+ elif output["type"] == "data":+ # No data+ if len(output["data"]) == 0:+ continue+ elif len(output["data"]) == 1:+ cell_outputs.append(+ CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype=cast(+ KnownMimeType,+ next(iter(output["data"].keys())),+ ),+ data=next(iter(output["data"].values())),+ )+ )+ else:+ # Mime bundle+ cell_outputs.append(+ CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="application/vnd.marimo+mimebundle",+ data=output["data"],+ )+ )+ else:+ LOGGER.warning(f"Unknown output type: {output}")+ continue++ # Convert console+ console_outputs: List[CellOutput] = []+ for console in cell["console"]:+ console_outputs.append(+ CellOutput(+ channel=CellChannel.STDERR+ if console["name"] == "stderr"+ else CellChannel.STDOUT,+ data=console["text"],+ mimetype="text/plain",+ )+ )++ view.cell_operations[cell["id"]] = CellOp(+ cell_id=cell["id"],+ status="idle",+ output=cell_outputs[0] if cell_outputs else None,+ console=console_outputs,+ timestamp=0,+ )++ return view+++def get_session_cache_file(path: Path) -> Path:+ """Get the cache file for a given path.++ For example, if the path is `foo/bar/baz.py`, the cache file is+ `foo/bar/__marimo__/session/baz.py.json`.+ """+ return path.parent / "__marimo__" / "session" / f"{path.name}.json"+++def _hash_code(code: Optional[str]) -> Optional[str]:+ if code is None or code == "":+ return None+ return hashlib.md5(code.encode("utf-8"), usedforsecurity=False).hexdigest()+++class SessionCacheWriter(AsyncBackgroundTask):+ """Periodically writes a SessionView to a file."""++ def __init__(+ self,+ session_view: SessionView,+ path: Path,+ interval: float,+ ) -> None:+ super().__init__()+ self.session_view = session_view+ self.path = path+ self.interval = interval++ async def startup(self) -> None:+ # Create parent directories if they don't exist+ try:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ except Exception as e:+ LOGGER.error(f"Failed to create parent directories: {e}")+ raise++ async def run(self) -> None:+ while self.running:+ try:+ if self.session_view.needs_export("session"):+ self.session_view.mark_auto_export_session()+ LOGGER.debug(f"Writing session view to cache {self.path}")+ data = serialize_session_view(self.session_view)+ self.path.write_text(json.dumps(data, indent=2))+ await asyncio.sleep(self.interval)+ except asyncio.CancelledError:+ raise+ except Exception as e:+ LOGGER.error(f"Write error: {e}")+ # If we fail to write, we should stop the writer+ break+++class SessionCacheManager:+ """Manages the session cache writer.++ Handles renaming the file and when the file is not named.+ """++ def __init__(+ self,+ session_view: SessionView,+ path: Optional[str | Path],+ interval: float,+ ):+ self.session_view = session_view+ self.path = path+ self.interval = interval+ self.session_cache_writer: SessionCacheWriter | None = None++ def start(self) -> None:+ """Start the session cache writer"""+ if self.path is None:+ return++ cache_file = get_session_cache_file(Path(self.path))++ self.session_cache_writer = SessionCacheWriter(+ session_view=self.session_view,+ path=cache_file,+ interval=self.interval,+ )+ self.session_cache_writer.start()++ def stop(self) -> bool:+ """Stop the session cache writer. Returns whether it was running."""+ if self.session_cache_writer is None:+ return False+ self.session_cache_writer.stop_sync()+ self.session_cache_writer = None+ return True++ def rename_path(self, new_path: str | Path) -> None:+ """Rename the path to the new path"""+ self.stop()+ self.path = new_path+ self.start()++ def read_session_view(self) -> SessionView:+ """Read the session view from the cache file"""+ if self.path is None:+ return self.session_view+ cache_file = get_session_cache_file(Path(self.path))+ if not cache_file.exists():+ return self.session_view+ self.session_view = deserialize_session(+ json.loads(cache_file.read_text())+ )+ return self.session_viewdiff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.pyindex 78d5aedfa4..42f8bebee3 100644--- a/marimo/_server/session/session_view.py+++ b/marimo/_server/session/session_view.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport timefrom dataclasses import dataclass-from typing import Any, Literal, Optional, Union+from typing import Any, Literal, Optionalfrom marimo._ast.cell import CellId_tfrom marimo._data.models import DataSourceConnection, DataTable@@ -27,8 +27,31 @@ from marimo._runtime.requests import (ExecutionRequest,SetUIElementValueRequest,)+from marimo._utils.lists import as_listfrom marimo._utils.parse_dataclass import parse_raw+ExportType = Literal["html", "md", "ipynb", "session"]+++@dataclass+class AutoExportState:+ html: bool = False+ md: bool = False+ ipynb: bool = False+ session: bool = False++ def mark_all_stale(self) -> None:+ self.html = False+ self.md = False+ self.ipynb = False+ self.session = False++ def is_stale(self, export_type: ExportType) -> bool:+ return not getattr(self, export_type)++ def mark_exported(self, export_type: ExportType) -> None:+ setattr(self, export_type, True)+class SessionView:"""@@ -60,9 +83,7 @@ class SessionView:self.stale_code: Optional[UpdateCellCodes] = None# Auto-saving- self.has_auto_exported_html = False- self.has_auto_exported_md = False- self.has_auto_exported_ipynb = False+ self.auto_export_state = AutoExportState()def _add_ui_value(self, name: str, value: Any) -> None:self.ui_values[name] = value@@ -115,6 +136,7 @@ class SessionView:def add_operation(self, operation: MessageOperation) -> None:self._touch()+ self.auto_export_state.mark_all_stale()"""Add an operation to the session view."""@@ -274,18 +296,22 @@ class SessionView:return all_opsdef mark_auto_export_html(self) -> None:- self.has_auto_exported_html = True+ self.auto_export_state.mark_exported("html")def mark_auto_export_md(self) -> None:- self.has_auto_exported_md = True+ self.auto_export_state.mark_exported("md")def mark_auto_export_ipynb(self) -> None:- self.has_auto_exported_ipynb = True+ self.auto_export_state.mark_exported("ipynb")++ def mark_auto_export_session(self) -> None:+ self.auto_export_state.mark_exported("session")++ def needs_export(self, export_type: ExportType) -> bool:+ return self.auto_export_state.is_stale(export_type)def _touch(self) -> None:- self.has_auto_exported_html = False- self.has_auto_exported_md = False- self.has_auto_exported_ipynb = False+ self.auto_export_state.mark_all_stale()def merge_cell_operation(@@ -317,9 +343,3 @@ def merge_cell_operation(next_.output = previous.outputreturn next_---def as_list(value: Union[Any, Optional[Any], list[Any]]) -> list[Any]:- if value is None:- return []- return value if isinstance(value, list) else [value]diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex b4f278bb92..9c5bfca3d7 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -63,6 +63,9 @@ from marimo._server.ids import ConsumerId, SessionIdfrom marimo._server.model import ConnectionState, SessionConsumer, SessionModefrom marimo._server.models.models import InstantiateRequestfrom marimo._server.recents import RecentFilesManager+from marimo._server.session.serialize import (+ SessionCacheManager,+)from marimo._server.session.session_view import SessionViewfrom marimo._server.tokens import AuthToken, SkewProtectionTokenfrom marimo._server.types import QueueType@@ -418,6 +421,8 @@ class Session:and its own websocket, for sending messages to the client."""+ SESSION_CACHE_INTERVAL_SECONDS = 2+@classmethoddef create(cls,@@ -477,6 +482,7 @@ class Session:ttl_seconds if ttl_seconds is not None else _DEFAULT_TTL_SECONDS)self.session_view = SessionView()+ self.session_cache_manager: SessionCacheManager | None = Noneself.kernel_manager.start_kernel()# Reads from the kernel connection and distributes the@@ -650,6 +656,8 @@ class Session:self.message_distributor.stop()if self.heartbeat_task:self.heartbeat_task.cancel()+ if self.session_cache_manager:+ self.session_cache_manager.stop()self.kernel_manager.close_kernel()def instantiate(@@ -683,6 +691,21 @@ class Session:from_consumer_id=None,)+ def sync_session_view_from_cache(self) -> None:+ """Sync the session view from a file.++ Overwrites the existing session view.+ Mutates the existing session.+ """+ LOGGER.debug("Syncing session view from cache")+ self.session_cache_manager = SessionCacheManager(+ session_view=self.session_view,+ path=self.app_file_manager.path,+ interval=self.SESSION_CACHE_INTERVAL_SECONDS,+ )+ self.session_view = self.session_cache_manager.read_session_view()+ self.session_cache_manager.start()+def __repr__(self) -> str:return format_repr(self,@@ -855,14 +878,6 @@ class SessionManager:]== "autorun")- session.write_operation(- UpdateCellCodes(- cell_ids=cell_ids,- codes=codes,- code_is_stale=not should_autorun,- ),- from_consumer_id=None,- )# Auto-run cells if configuredif should_autorun:@@ -875,6 +890,7 @@ class SessionManager:for cell_id in changed_cell_ids_list]+ # This runs the request and also runs UpdateCellCodessession.put_control_request(ExecuteMultipleRequest(cell_ids=changed_cell_ids_list,@@ -883,6 +899,15 @@ class SessionManager:),from_consumer_id=None,)+ else:+ session.write_operation(+ UpdateCellCodes(+ cell_ids=cell_ids,+ codes=codes,+ code_is_stale=not should_autorun,+ ),+ from_consumer_id=None,+ )session._unsubscribe_file_watcher_ = on_file_changed # type: ignore@@ -891,7 +916,7 @@ class SessionManager:)def handle_file_rename_for_watch(- self, session_id: SessionId, new_path: str+ self, session_id: SessionId, prev_path: Optional[str], new_path: str) -> tuple[bool, Optional[str]]:"""Handle renaming a file for a session.@@ -908,18 +933,20 @@ class SessionManager:if not session.app_file_manager.path:return False, "Session has no associated file"- old_path = session.app_file_manager.path+ # Handle rename for session cache+ if session.session_cache_manager:+ session.session_cache_manager.rename_path(new_path)try:- # Remove the old file watcher if it existsif self.watch:- self.watcher_manager.remove_callback(- Path(old_path),- session._unsubscribe_file_watcher_, # type: ignore- )+ # Remove the old file watcher if it exists+ if prev_path:+ self.watcher_manager.remove_callback(+ Path(prev_path),+ session._unsubscribe_file_watcher_, # type: ignore+ )- # Add a watcher for the new path if needed- if self.watch:+ # Add a watcher for the new path if neededself._start_file_watcher_for_session(session)return True, Nonediff --git a/marimo/_utils/background_task.py b/marimo/_utils/background_task.pynew file mode 100644index 0000000000..403cbf8277--- /dev/null+++ b/marimo/_utils/background_task.py@@ -0,0 +1,137 @@+from __future__ import annotations++import asyncio+from abc import ABC, abstractmethod+from typing import TYPE_CHECKING, Any, Optional, final++from marimo import _loggers++if TYPE_CHECKING:+ from typing_extensions import Self++LOGGER = _loggers.marimo_logger()+++class AsyncBackgroundTask(ABC):+ def __init__(self) -> None:+ self.task: Optional[asyncio.Task[None]] = None+ self.running: bool = False+ self._startup_event: asyncio.Event = asyncio.Event()+ self._shutdown_event: asyncio.Event = asyncio.Event()++ @abstractmethod+ async def run(self) -> None:+ """+ The main task routine that should be implemented by subclasses.+ This method contains the actual task logic.+ """+ pass++ async def startup(self) -> None:+ """+ Optional startup routine that can be implemented by subclasses.+ This method is called before the main task starts.+ """+ return None++ async def shutdown(self) -> None:+ """+ Optional shutdown routine that can be implemented by subclasses.+ This method is called after the main task stops.+ """+ return None++ async def _task_wrapper(self) -> None:+ """+ Internal wrapper that handles the task lifecycle.+ """+ try:+ await self.startup()+ self._startup_event.set()++ await self.run()+ except Exception as e:+ LOGGER.error(f"Error in task: {e}")+ raise+ finally:+ self.running = False+ await self.shutdown()+ self._shutdown_event.set()++ @final+ def start(self) -> None:+ """+ Starts the background task.+ """+ if self.task is None or self.task.done():+ self.running = True+ self._startup_event.clear()+ self._shutdown_event.clear()+ self.task = asyncio.create_task(self._task_wrapper())++ @final+ async def stop(self, timeout: Optional[float] = None) -> None:+ """+ Stops the background task.++ Args:+ timeout: Maximum time to wait for the task to stop (in seconds)+ """+ if self.task and not self.task.done():+ self.running = False++ try:+ await asyncio.wait_for(+ self._shutdown_event.wait(), timeout=timeout+ )+ except asyncio.TimeoutError:+ self.task.cancel()+ try:+ await self.task+ except asyncio.CancelledError:+ pass++ @final+ def stop_sync(self, timeout: Optional[float] = None) -> None:+ """+ Synchronous version of stop that can be called from non-async code.+ """+ try:+ loop = asyncio.get_event_loop()+ if loop.is_running():+ # Can't run a new event loop while one is running+ # Just set running to false and let the task complete naturally+ self.running = False+ return+ loop.run_until_complete(self.stop(timeout))+ except RuntimeError:+ # If there's no event loop, create a new one+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ loop.run_until_complete(self.stop(timeout))+ loop.close()++ async def wait_for_startup(self, timeout: Optional[float] = None) -> None:+ """+ Waits for the task to start up.++ Args:+ timeout: Maximum time to wait for startup (in seconds)+ """+ await asyncio.wait_for(self._startup_event.wait(), timeout=timeout)++ async def __aenter__(self) -> Self:+ """+ Async context manager entry.+ """+ self.start()+ await self.wait_for_startup()+ return self++ async def __aexit__(+ self, exc_type: Any, exc_val: Any, exc_tb: Any+ ) -> None:+ """+ Async context manager exit.+ """+ await self.stop()diff --git a/marimo/_utils/file_watcher.py b/marimo/_utils/file_watcher.pyindex 303138206a..33bbce9a1f 100644--- a/marimo/_utils/file_watcher.py+++ b/marimo/_utils/file_watcher.py@@ -59,7 +59,7 @@ class PollingFileWatcher(FileWatcher):super().__init__(path, callback)self._running = Falseself.loop = loop- self.last_modified: Optional[float] = None+ self.last_modified: Optional[float] = self._get_modified()def start(self) -> None:self._running = True@@ -68,6 +68,12 @@ class PollingFileWatcher(FileWatcher):def stop(self) -> None:self._running = False+ def _get_modified(self) -> Optional[float]:+ try:+ return os.path.getmtime(self.path)+ except FileNotFoundError:+ return None+async def _poll(self) -> None:while self._running:if not os.path.exists(self.path):@@ -75,7 +81,7 @@ class PollingFileWatcher(FileWatcher):raise FileNotFoundError(f"File at {self.path} does not exist.")# Check for file changes- modified = os.path.getmtime(self.path)+ modified = self._get_modified()if self.last_modified is None:self.last_modified = modifiedelif modified != self.last_modified:@@ -154,6 +160,7 @@ class FileWatcherManager:"""Remove a callback for a file path. Removes watcher if no more callbacks."""path_str = str(path)if path_str not in self._callbacks:+ LOGGER.warning(f"Callback for {path_str} not found")returnself._callbacks[path_str].discard(callback)diff --git a/marimo/_utils/lists.py b/marimo/_utils/lists.pyindex e620c840fd..6ae04dcda2 100644--- a/marimo/_utils/lists.py+++ b/marimo/_utils/lists.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Iterable, TypeVar, Union+from typing import Iterable, Optional, TypeVar, UnionT = TypeVar("T")@@ -11,3 +11,9 @@ def first(iterable: Union[Iterable[T], T]) -> T:return next(iter(iterable)) # type: ignore[no-any-return]else:return iterable+++def as_list(value: Union[T, Optional[T], list[T]]) -> list[T]:+ if value is None:+ return []+ return value if isinstance(value, list) else [value] # type: ignore[no-any-return]diff --git a/scripts/generate.py b/scripts/generate.pynew file mode 100644index 0000000000..dc68acf6f2--- /dev/null+++ b/scripts/generate.py@@ -0,0 +1,107 @@+#!/usr/bin/env python3+import marimo++__generated_with = "0.11.5"+app = marimo.App(width="medium")++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""This marimo notebook generates the OpenAPI schema for the `TypeDict`s defined in `marimo._schemas.session`""")+ return+++def _():+ from marimo._schemas.session import (+ TimeMetadata,+ StreamOutput,+ ErrorOutput,+ DataOutput,+ Cell,+ NotebookMetadata,+ NotebookSessionV1,+ )++ MESSAGES = [+ TimeMetadata,+ StreamOutput,+ ErrorOutput,+ DataOutput,+ Cell,+ NotebookMetadata,+ NotebookSessionV1,+ ]+ return (+ Cell,+ DataOutput,+ ErrorOutput,+ MESSAGES,+ NotebookMetadata,+ NotebookSessionV1,+ StreamOutput,+ TimeMetadata,+ )++[email protected](hide_code=True)+def _(mo):+ generate_schema = mo.ui.run_button(label="Write schema")+ generate_schema+ return (generate_schema,)+++def _(build_openapi_schema, generate_schema, mo):+ if generate_schema.value:+ import yaml++ output = mo.notebook_dir() / "session.yaml"+ output.write_text(yaml.dump(build_openapi_schema()))+ return output, yaml++[email protected](hide_code=True)+def _(Any, Dict, MESSAGES):+ from marimo._server.api.router import build_routes+ from marimo._utils.dataclass_to_openapi import (+ PythonTypeToOpenAPI,+ )+++ def build_openapi_schema():+ processed_classes: Dict[Any, str] = {}+ component_schemas: Dict[str, Any] = {}+ name_overrides: Dict[Any, str] = {}++ converter = PythonTypeToOpenAPI(+ camel_case=False, name_overrides=name_overrides+ )+ for cls in MESSAGES:+ if cls in processed_classes:+ del processed_classes[cls]+ name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]+ component_schemas[name] = converter.convert(cls, processed_classes)+ processed_classes[cls] = name++ schemas = {+ "openapi": "3.0.0",+ "info": {"title": "marimo_session"},+ "components": {+ "schemas": {+ **component_schemas,+ }+ },+ }+ return schemas+ return PythonTypeToOpenAPI, build_openapi_schema, build_routes+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/scripts/generate_schemas.py b/scripts/generate_schemas.pynew file mode 100755index 0000000000..92d490baa8--- /dev/null+++ b/scripts/generate_schemas.py@@ -0,0 +1,125 @@+#!/usr/bin/env python3++import marimo++__generated_with = "0.11.5"+app = marimo.App(width="medium")++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""This marimo notebook generates the OpenAPI schema for the `TypeDict`s defined in `marimo._schemas.session`""")+ return+++def _():+ return+++def _():+ from marimo._schemas.session import (+ TimeMetadata,+ StreamOutput,+ ErrorOutput,+ DataOutput,+ Cell,+ NotebookMetadata,+ NotebookSessionV1,+ )++ MESSAGES = [+ TimeMetadata,+ StreamOutput,+ ErrorOutput,+ DataOutput,+ Cell,+ NotebookMetadata,+ NotebookSessionV1,+ ]+ return (+ Cell,+ DataOutput,+ ErrorOutput,+ MESSAGES,+ NotebookMetadata,+ NotebookSessionV1,+ StreamOutput,+ TimeMetadata,+ )++[email protected](hide_code=True)+def _(mo):+ generate_schema = mo.ui.run_button(label="Write schema")+ generate_schema+ return (generate_schema,)+++def _(build_openapi_schema, generate_schema, mo):+ import yaml++ header = f"# This file is generated by scripts/generate_schemas.py\n"++ if generate_schema.value:+ print("Writing schema to marimo/_schemas/generated/session.yaml")+ output = (+ mo.notebook_dir().parent+ / "marimo"+ / "_schemas"+ / "generated"+ / "session.yaml"+ )+ output.write_text(header + yaml.dump(build_openapi_schema()))++ if mo.app_meta().mode == "script":+ print(header + yaml.dump(build_openapi_schema()))+ return header, output, yaml++[email protected](hide_code=True)+def _(Any, Dict, MESSAGES):+ from marimo._server.api.router import build_routes+ from marimo._utils.dataclass_to_openapi import (+ PythonTypeToOpenAPI,+ )+++ def build_openapi_schema():+ processed_classes: Dict[Any, str] = {}+ component_schemas: Dict[str, Any] = {}+ name_overrides: Dict[Any, str] = {}++ converter = PythonTypeToOpenAPI(+ camel_case=False, name_overrides=name_overrides+ )+ for cls in MESSAGES:+ if cls in processed_classes:+ del processed_classes[cls]+ name = name_overrides.get(cls, cls.__name__) # type: ignore[attr-defined]+ component_schemas[name] = converter.convert(cls, processed_classes)+ processed_classes[cls] = name++ schemas = {+ "openapi": "3.0.0",+ "info": {"title": "marimo_session"},+ "components": {+ "schemas": {+ **component_schemas,+ }+ },+ }+ return schemas+ return PythonTypeToOpenAPI, build_openapi_schema, build_routes+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_schemas/test_schema.py b/tests/_schemas/test_schema.pynew file mode 100644index 0000000000..8ef8929cf4--- /dev/null+++ b/tests/_schemas/test_schema.py@@ -0,0 +1,28 @@+from __future__ import annotations++import subprocess+import sys+from pathlib import Path++import pytest+import yaml+++ sys.platform == "win32",+ reason="This test is flaky on Windows",+)+def test_session_schema_up_to_date() -> None:+ with open("marimo/_schemas/generated/session.yaml", "r") as f:+ current_content = yaml.safe_load(f)++ script_path = (+ Path(__file__).parent.parent.parent / "scripts" / "generate_schemas.py"+ )+ result = subprocess.run([script_path], capture_output=True, text=True)+ generated_content = yaml.safe_load(result.stdout)++ cmd = "marimo edit scripts/generate_schemas.py"+ assert current_content == generated_content, (+ f"session.yaml is not up to date. Run '{cmd}' and press 'Write schema' to update."+ )diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex b2a39b6e87..fe9a3c3113 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -318,9 +318,9 @@ def test_resume_session_with_watch(client: TestClient) -> None:assert data == {"op": "update-cell-codes","data": {- "cell_ids": ["MJUe", "Hbol"],+ "cell_ids": ["MJUe"],"code_is_stale": False,- "codes": ["x=10; x", "import marimo as mo"],+ "codes": ["x=10; x"],},}diff --git a/tests/_server/session/snapshots/README.md b/tests/_server/session/snapshots/README.mdnew file mode 100644index 0000000000..3b954c485a--- /dev/null+++ b/tests/_server/session/snapshots/README.md@@ -0,0 +1,4 @@+# Session Serialization Snapshots++This directory contains snapshot tests for the session serialization/deserialization functionality. The snapshots verify that the JSON structure of serialized notebook sessions remains consistent.+diff --git a/tests/_server/session/snapshots/basic_session.json b/tests/_server/session/snapshots/basic_session.jsonnew file mode 100644index 0000000000..d781fc00d1--- /dev/null+++ b/tests/_server/session/snapshots/basic_session.json@@ -0,0 +1,21 @@+{+ "version": "1",+ "metadata": {+ "marimo_version": "0.0.0"+ },+ "cells": [+ {+ "id": "cell1",+ "code_hash": "ade540478250e37019625fe117df5422",+ "outputs": [+ {+ "type": "data",+ "data": {+ "text/plain": "Hello, world!"+ }+ }+ ],+ "console": []+ }+ ]+}diff --git a/tests/_server/session/snapshots/console_session.json b/tests/_server/session/snapshots/console_session.jsonnew file mode 100644index 0000000000..c18ae7414b--- /dev/null+++ b/tests/_server/session/snapshots/console_session.json@@ -0,0 +1,25 @@+{+ "version": "1",+ "metadata": {+ "marimo_version": "0.0.0"+ },+ "cells": [+ {+ "id": "cell1",+ "code_hash": "e40f72b0677eb645c19220134c129a00",+ "outputs": [],+ "console": [+ {+ "type": "stream",+ "name": "stdout",+ "text": "stdout message"+ },+ {+ "type": "stream",+ "name": "stderr",+ "text": "stderr message"+ }+ ]+ }+ ]+}diff --git a/tests/_server/session/snapshots/error_session.json b/tests/_server/session/snapshots/error_session.jsonnew file mode 100644index 0000000000..92edcb03ab--- /dev/null+++ b/tests/_server/session/snapshots/error_session.json@@ -0,0 +1,21 @@+{+ "version": "1",+ "metadata": {+ "marimo_version": "0.0.0"+ },+ "cells": [+ {+ "id": "cell1",+ "code_hash": "a960b79813ce2572394622798a48b871",+ "outputs": [+ {+ "type": "error",+ "ename": "unknown",+ "evalue": "Something went wrong",+ "traceback": []+ }+ ],+ "console": []+ }+ ]+}diff --git a/tests/_server/session/snapshots/mime_bundle_session.json b/tests/_server/session/snapshots/mime_bundle_session.jsonnew file mode 100644index 0000000000..e9cd3445bd--- /dev/null+++ b/tests/_server/session/snapshots/mime_bundle_session.json@@ -0,0 +1,24 @@+{+ "version": "1",+ "metadata": {+ "marimo_version": "0.0.0"+ },+ "cells": [+ {+ "id": "cell1",+ "code_hash": "a275ff21d68e054b07f355888a93cf79",+ "outputs": [+ {+ "type": "data",+ "data": {+ "application/vnd.marimo+mimebundle": {+ "text/plain": "Hello",+ "text/html": "<b>Hello</b>"+ }+ }+ }+ ],+ "console": []+ }+ ]+}diff --git a/tests/_server/session/test_serialize_session.py b/tests/_server/session/test_serialize_session.pynew file mode 100644index 0000000000..2aaf69357e--- /dev/null+++ b/tests/_server/session/test_serialize_session.py@@ -0,0 +1,422 @@+from __future__ import annotations++import asyncio+import json+import sys+import tempfile+from pathlib import Path++from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.errors import MarimoExceptionRaisedError, UnknownError+from marimo._messaging.ops import CellOp+from marimo._schemas.session import NotebookSessionV1+from marimo._server.session.serialize import (+ SessionCacheManager,+ SessionCacheWriter,+ _hash_code,+ deserialize_session,+ get_session_cache_file,+ serialize_session_view,+)+from marimo._server.session.session_view import SessionView+from tests.mocks import snapshotter++snapshot = snapshotter(__file__)+++def test_serialize_basic_session():+ """Test serialization of a basic session with a single cell with data output"""+ view = SessionView()+ view.cell_operations["cell1"] = CellOp(+ cell_id="cell1",+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="Hello, world!",+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code["cell1"] = "print('Hello, world!')"++ result = serialize_session_view(view)+ snapshot("basic_session.json", json.dumps(result, indent=2))+++def test_serialize_session_with_error():+ """Test serialization of a session with an error output"""+ view = SessionView()+ view.cell_operations["cell1"] = CellOp(+ cell_id="cell1",+ status="idle",+ output=CellOutput(+ channel=CellChannel.MARIMO_ERROR,+ mimetype="text/plain",+ data=[UnknownError(type="unknown", msg="Something went wrong")],+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code["cell1"] = (+ "raise RuntimeError('Something went wrong')"+ )++ result = serialize_session_view(view)+ snapshot("error_session.json", json.dumps(result, indent=2))+++def test_serialize_session_with_console():+ """Test serialization of a session with console output"""+ view = SessionView()+ view.cell_operations["cell1"] = CellOp(+ cell_id="cell1",+ status="idle",+ output=None,+ console=[+ CellOutput(+ channel=CellChannel.STDOUT,+ mimetype="text/plain",+ data="stdout message",+ ),+ CellOutput(+ channel=CellChannel.STDERR,+ mimetype="text/plain",+ data="stderr message",+ ),+ ],+ timestamp=0,+ )+ view.last_executed_code["cell1"] = "print('test')"++ result = serialize_session_view(view)+ snapshot("console_session.json", json.dumps(result, indent=2))+++def test_serialize_session_with_mime_bundle():+ """Test serialization of a session with a mime bundle output"""+ view = SessionView()+ view.cell_operations["cell1"] = CellOp(+ cell_id="cell1",+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="application/vnd.marimo+mimebundle",+ data={+ "text/plain": "Hello",+ "text/html": "<b>Hello</b>",+ },+ ),+ console=[],+ timestamp=0,+ )+ view.last_executed_code["cell1"] = "HTML('Hello')"++ result = serialize_session_view(view)+ snapshot("mime_bundle_session.json", json.dumps(result, indent=2))+++def test_deserialize_basic_session():+ """Test deserialization of a basic session"""+ session = NotebookSessionV1(+ version=1,+ metadata={"marimo_version": "1.0.0"},+ cells=[+ {+ "id": "cell1",+ "code_hash": "123",+ "outputs": [+ {+ "type": "data",+ "data": {"text/plain": "Hello, world!"},+ }+ ],+ "console": [],+ }+ ],+ )++ view = deserialize_session(session)+ assert "cell1" in view.cell_operations+ cell = view.cell_operations["cell1"]+ assert cell.output is not None+ assert cell.output.channel == CellChannel.OUTPUT+ assert cell.output.mimetype == "text/plain"+ assert cell.output.data == "Hello, world!"+++def test_deserialize_session_with_error():+ """Test deserialization of a session with an error"""+ session = NotebookSessionV1(+ version=1,+ metadata={"marimo_version": "1.0.0"},+ cells=[+ {+ "id": "cell1",+ "code_hash": "123",+ "outputs": [+ {+ "type": "error",+ "ename": "RuntimeError",+ "evalue": "Something went wrong",+ "traceback": [],+ }+ ],+ "console": [],+ }+ ],+ )++ view = deserialize_session(session)+ assert "cell1" in view.cell_operations+ cell = view.cell_operations["cell1"]+ assert cell.output is not None+ assert cell.output.channel == CellChannel.MARIMO_ERROR+ assert isinstance(cell.output.data, list)+ error = cell.output.data[0]+ assert isinstance(error, MarimoExceptionRaisedError)+ assert error.msg == "Something went wrong"+++def test_deserialize_session_with_console():+ """Test deserialization of a session with console output"""+ session = NotebookSessionV1(+ version=1,+ metadata={"marimo_version": "1.0.0"},+ cells=[+ {+ "id": "cell1",+ "code_hash": "123",+ "outputs": [],+ "console": [+ {+ "type": "stream",+ "name": "stdout",+ "text": "stdout message",+ },+ {+ "type": "stream",+ "name": "stderr",+ "text": "stderr message",+ },+ ],+ }+ ],+ )++ view = deserialize_session(session)+ assert "cell1" in view.cell_operations+ cell = view.cell_operations["cell1"]+ assert isinstance(cell.console, list)+ assert len(cell.console) == 2+ console_outputs = cell.console+ assert console_outputs[0].channel == CellChannel.STDOUT+ assert console_outputs[0].data == "stdout message"+ assert console_outputs[1].channel == CellChannel.STDERR+ assert console_outputs[1].data == "stderr message"+++async def test_session_cache_writer():+ """Test AsyncWriter writes session data periodically"""+ view = SessionView()+ view.cell_operations["cell1"] = CellOp(+ cell_id="cell1",+ status="idle",+ 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)++ # Start writer and wait for first write+ writer.start()+ await asyncio.sleep(0.2)++ # Verify data was written+ assert path.exists()+ data = json.loads(path.read_text())+ assert len(data["cells"]) == 1+ assert data["cells"][0]["id"] == "cell1"++ # Stop writer and verify cleanup+ await writer.stop()+++async def test_session_cache_writer_no_writes():+ """Test AsyncWriter does not write when no changes"""+ view = SessionView()+ view.mark_auto_export_session()+ with tempfile.TemporaryDirectory() as tmpdir:+ path = Path(tmpdir) / "session.json"+ writer = SessionCacheWriter(view, path, interval=0.1)+ writer.start()+ await asyncio.sleep(0.2)+ assert not path.exists()++ view._touch()+ await asyncio.sleep(0.2)+ assert path.exists()++ await writer.stop()+++def test_get_session_cache_file():+ is_windows = sys.platform == "win32"+ # Linux path+ if not is_windows:+ path = Path("/path/to/notebook.py")+ cache_file = get_session_cache_file(path)+ assert cache_file == Path(+ "/path/to/__marimo__/session/notebook.py.json"+ )+ else:+ # Windows path+ path = Path("C:\\path\\to\\notebook.py")+ cache_file = get_session_cache_file(path)+ assert cache_file == Path(+ "C:\\path\\to\\__marimo__\\session\\notebook.py.json"+ )+++def test_hash_code():+ """Test _hash_code function"""+ assert _hash_code(None) is None+ assert _hash_code("print('hello')") == "e73b48e8e00d36304ea7204a0683c814"+ assert _hash_code("") is None+++def test_deserialize_mime_bundle():+ """Test deserialization of a session with mime bundle output"""+ session = NotebookSessionV1(+ version=1,+ metadata={"marimo_version": "1.0.0"},+ cells=[+ {+ "id": "cell1",+ "code_hash": "123",+ "outputs": [+ {+ "type": "data",+ "data": {+ "text/plain": "Hello",+ "text/html": "<b>Hello</b>",+ },+ }+ ],+ "console": [],+ }+ ],+ )++ view = deserialize_session(session)+ assert "cell1" in view.cell_operations+ cell = view.cell_operations["cell1"]+ assert cell.output is not None+ assert cell.output.channel == CellChannel.OUTPUT+ assert cell.output.mimetype == "application/vnd.marimo+mimebundle"+ assert cell.output.data == {+ "text/plain": "Hello",+ "text/html": "<b>Hello</b>",+ }+++def test_deserialize_empty_data():+ """Test deserialization of a session with empty data output"""+ session = NotebookSessionV1(+ version=1,+ metadata={"marimo_version": "1.0.0"},+ cells=[+ {+ "id": "cell1",+ "code_hash": "123",+ "outputs": [{"type": "data", "data": {}}],+ "console": [],+ }+ ],+ )++ view = deserialize_session(session)+ assert "cell1" in view.cell_operations+ cell = view.cell_operations["cell1"]+ assert cell.output is None+++class TestSessionCacheManager:+ """Test SessionCacheManager functionality"""++ def test_init_without_path(self):+ """Test initialization without path"""+ view = SessionView()+ manager = SessionCacheManager(view, None, 0.1)+ manager.start()+ assert manager.session_cache_writer is None++ async def test_rename_path(self):+ """Test renaming path updates writer"""+ view = SessionView()+ 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.start()+ assert manager.session_cache_writer is not None+ old_writer = manager.session_cache_writer++ manager.rename_path(new_path)+ assert manager.session_cache_writer is not None+ assert manager.session_cache_writer != old_writer+ assert manager.path == new_path++ def test_read_session_view_no_path(self):+ """Test reading session view without path"""+ view = SessionView()+ manager = SessionCacheManager(view, None, 0.1)+ assert manager.read_session_view() == view++ def test_read_session_view_no_cache(self):+ """Test reading session view with no cache file"""+ view = SessionView()+ with tempfile.TemporaryDirectory() as tmpdir:+ path = Path(tmpdir) / "notebook.py"+ manager = SessionCacheManager(view, path, 0.1)+ assert manager.read_session_view() == view++ async def test_read_session_view_with_cache(self):+ """Test reading session view from cache file"""+ view = SessionView()+ view.cell_operations["cell1"] = CellOp(+ cell_id="cell1",+ status="idle",+ output=CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="test data",+ ),+ console=[],+ timestamp=0,+ )++ with tempfile.TemporaryDirectory() as tmpdir:+ path = Path(tmpdir) / "notebook.py"+ cache_file = get_session_cache_file(path)+ cache_file.parent.mkdir(parents=True)++ # Write cache file+ data = serialize_session_view(view)+ cache_file.write_text(json.dumps(data))++ # Read back+ manager = SessionCacheManager(SessionView(), path, 0.1)+ loaded_view = manager.read_session_view()+ 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"diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.pyindex 4c43b195db..d9d1dc7f4a 100644--- a/tests/_server/session/test_session_view.py+++ b/tests/_server/session/test_session_view.py@@ -715,18 +715,18 @@ def test_get_cell_console_outputs(time_mock: Any) -> None:def test_mark_auto_export():session_view = SessionView()- assert not session_view.has_auto_exported_html- assert not session_view.has_auto_exported_md+ assert session_view.needs_export("html")+ assert session_view.needs_export("md")session_view.mark_auto_export_html()- assert session_view.has_auto_exported_html+ assert not session_view.needs_export("html")session_view.mark_auto_export_md()- assert session_view.has_auto_exported_md+ assert not session_view.needs_export("md")session_view._touch()- assert not session_view.has_auto_exported_html- assert not session_view.has_auto_exported_md+ assert session_view.needs_export("html")+ assert session_view.needs_export("md")session_view.mark_auto_export_html()session_view.mark_auto_export_md()@@ -737,8 +737,14 @@ def test_mark_auto_export():status=initial_status,),)- assert not session_view.has_auto_exported_html- assert not session_view.has_auto_exported_md+ assert session_view.needs_export("html")+ assert session_view.needs_export("md")++ session_view.mark_auto_export_session()+ assert not session_view.needs_export("session")++ session_view._touch()+ assert session_view.needs_export("session")def test_stale_code() -> None:diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex fc8a2733a9..7ef963e470 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -14,6 +14,8 @@ from tempfile import NamedTemporaryFilefrom typing import Any, Callable, TypeVarfrom unittest.mock import MagicMock+import pytest+from marimo._ast.app import App, InternalAppfrom marimo._config.manager import get_default_config_managerfrom marimo._messaging.ops import UpdateCellCodes@@ -27,6 +29,7 @@ from marimo._runtime.requests import (from marimo._server.file_manager import AppFileManagerfrom marimo._server.file_router import AppFileRouterfrom marimo._server.model import ConnectionState, SessionMode+from marimo._server.session.session_view import SessionViewfrom marimo._server.sessions import (KernelManager,QueueManager,@@ -53,7 +56,11 @@ def save_and_restore_main(f: F) -> F:def wrapper(*args: Any, **kwargs: Any) -> None:main = sys.modules["__main__"]try:- f(*args, **kwargs)+ res = f(*args, **kwargs)+ if asyncio.iscoroutine(res):+ asyncio.run(res)+ else:+ passfinally:sys.modules["__main__"] = main@@ -229,7 +236,7 @@ def test_kernel_manager_interrupt(tmp_path) -> None:@save_and_restore_main-def test_session() -> None:+async def test_session() -> None:session_consumer: Any = MagicMock()session_consumer.connection_state.return_value = ConnectionState.OPENqueue_manager = QueueManager(use_multiprocessing=False)@@ -395,6 +402,10 @@ def test_session_with_kiosk_consumers() -> None:assert session.room.main_consumer is None+ sys.version_info < (3, 10),+ reason="This test is flaky on Python 3.9",+)@save_and_restore_mainasync def test_session_manager_file_watching() -> None:# Create a temporary file@@ -402,9 +413,10 @@ async def test_session_manager_file_watching() -> None:tmp_path = Path(tmp_file.name)# Write initial notebook contenttmp_file.write(- b"""import marimo as mo+ b"""import marimo+app = marimo.App()def __():1return ()@@ -421,7 +433,15 @@ def __():quiet=True,include_code=True,lsp_server=MagicMock(),- user_config_manager=get_default_config_manager(current_path=None),+ user_config_manager=get_default_config_manager(+ current_path=None+ ).with_overrides(+ {+ "runtime": {+ "watcher_on_save": "lazy",+ }+ }+ ),cli_args={},auth_token=None,redirect_console_to_browser=False,@@ -446,12 +466,12 @@ def __():)# Wait a bit and then modify the file- await asyncio.sleep(0.2)with open(tmp_path, "w") as f: # noqa: ASYNC230f.write(- """import marimo as mo+ """import marimo+app = marimo.App()def __():2return ()@@ -459,14 +479,17 @@ def __():)# Wait for the watcher to detect the change- await asyncio.sleep(0.2)+ for _ in range(16): # noqa: B007+ await asyncio.sleep(0.1)+ if len(operations) > 0:+ break# Check that UpdateCellCodes was sent with the new codeupdate_ops = [op for op in operations if isinstance(op, UpdateCellCodes)]assert len(update_ops) == 1- assert "return 2" in update_ops[0].codes[0]+ assert "2" == update_ops[0].codes[0]assert update_ops[0].code_is_stale is True# Create another session for the same file@@ -489,9 +512,10 @@ def __():operations2.clear()with open(tmp_path, "w") as f: # noqa: ASYNC230f.write(- """import marimo as mo+ """import marimo+app = marimo.App()def __():3return ()@@ -499,7 +523,10 @@ def __():)# Wait for the watcher to detect the change- await asyncio.sleep(0.2)+ for _ in range(16): # noqa: B007+ await asyncio.sleep(0.1)+ if len(operations) > 0:+ break# Both sessions should receive the updateupdate_ops = [@@ -510,8 +537,8 @@ def __():]assert len(update_ops) == 1assert len(update_ops2) == 1- assert "return 3" in update_ops[0].codes[0]- assert "return 3" in update_ops2[0].codes[0]+ assert "3" == update_ops[0].codes[0]+ assert "3" == update_ops2[0].codes[0]# Close one session and verify the other still receives updatesassert session_manager.close_session("test")@@ -520,29 +547,15 @@ def __():with open(tmp_path, "w") as f: # noqa: ASYNC230f.write(- """import marimo as mo+ """import marimo+app = marimo.App()def __():4return ()""")-- # Wait for the watcher to detect the change- await asyncio.sleep(0.2)-- # Only session2 should receive the update- update_ops = [- op for op in operations if isinstance(op, UpdateCellCodes)- ]- update_ops2 = [- op for op in operations2 if isinstance(op, UpdateCellCodes)- ]- assert len(update_ops) == 0- assert len(update_ops2) == 1- assert "return 4" in update_ops2[0].codes[0]-finally:# Cleanupsession_manager.shutdown()@@ -619,6 +632,10 @@ def test_watch_mode_config_override() -> None:os.remove(tmp_path)+ sys.version_info < (3, 10),+ reason="This test is flaky on Python 3.9",+)@save_and_restore_mainasync def test_watch_mode_with_watcher_on_save_config() -> None:"""Test that watch mode works correctly with watcher_on_save config."""@@ -627,9 +644,10 @@ async def test_watch_mode_with_watcher_on_save_config() -> None:tmp_path = Path(tmp_file.name)# Write initial notebook contenttmp_file.write(- b"""import marimo as mo+ b"""import marimo+app = marimo.App()def __():1return ()@@ -673,20 +691,28 @@ def __():)# Create a session- session_manager.create_session(+ session = session_manager.create_session(session_id="test",session_consumer=session_consumer,query_params={},file_key=str(tmp_path),)+ session.session_view = MagicMock(SessionView)# Wait a bit and then modify the file- await asyncio.sleep(0.2)+ for _ in range(16): # noqa: B007+ await asyncio.sleep(0.1)+ if len(operations) > 0:+ break++ # Modify the file+ operations.clear()with open(tmp_path, "w") as f: # noqa: ASYNC230f.write(- """import marimo as mo+ """import marimo+app = marimo.App()def __():2return ()@@ -694,7 +720,10 @@ def __():)# Wait for the watcher to detect the change- await asyncio.sleep(0.2)+ for _ in range(16): # noqa: B007+ await asyncio.sleep(0.1)+ if len(operations) > 0:+ break# Check that UpdateCellCodes was sent with code_is_stale=False (autorun)update_ops = [@@ -705,8 +734,8 @@ def __():assert update_ops[0].code_is_stale is False# Verify that cells were queued for execution- assert session_consumer.put_control_request.called- last_call = session_consumer.put_control_request.call_args[0][0]+ assert session.session_view.add_control_request.called+ last_call = session.session_view.add_control_request.call_args[0][0]assert isinstance(last_call, ExecuteMultipleRequest)# Now change config to lazy mode@@ -726,9 +755,10 @@ def __():operations.clear()with open(tmp_path, "w") as f: # noqa: ASYNC230f.write(- """import marimo as mo+ """import marimo+app = marimo.App()def __():3return ()@@ -736,7 +766,10 @@ def __():)# Wait for the watcher to detect the change- await asyncio.sleep(0.2)+ for _ in range(16): # noqa: B007+ await asyncio.sleep(0.1)+ if len(operations) > 0:+ break# Check that UpdateCellCodes was sent with code_is_stale=True (lazy)update_ops = [@@ -755,27 +788,31 @@ def __():os.remove(tmp_path)+ sys.version_info < (3, 10),+ reason="This test is flaky on Python 3.9",+)@save_and_restore_mainasync def test_session_manager_file_rename() -> None:"""Test that file renaming works correctly with file watching."""# Create two temporary fileswith (NamedTemporaryFile(delete=False, suffix=".py") as tmp_file1,- NamedTemporaryFile(delete=False, suffix=".py") as tmp_file2,):tmp_path1 = Path(tmp_file1.name)- tmp_path2 = Path(tmp_file2.name)# Write initial notebook contenttmp_file1.write(- b"""import marimo as mo+ b"""import marimo+app = marimo.App()def __():1return ()""")- tmp_file2.write(b"import marimo as mo")++ new_path = tmp_path1.with_suffix(".1.py")try:# Create a session manager with file watching enabled@@ -813,7 +850,7 @@ def __():# Try to rename to a non-existent filesuccess, error = session_manager.handle_file_rename_for_watch(- "test", "/nonexistent/file.py"+ "test", str(tmp_path1), "/nonexistent/file.py")assert not successassert error is not None@@ -821,64 +858,155 @@ def __():# Try to rename with an invalid sessionsuccess, error = session_manager.handle_file_rename_for_watch(- "nonexistent", str(tmp_path2)+ "nonexistent", str(tmp_path1), str(new_path))assert not successassert error is not Noneassert "Session not found" in error# Rename to the second file+ session = session_manager.get_session("test")+ assert session is not None+ session.app_file_manager.rename(str(new_path))+ assert new_path.exists()success, error = session_manager.handle_file_rename_for_watch(- "test", str(tmp_path2)+ "test", str(tmp_path1), str(new_path))assert successassert error is None# Modify the new fileoperations.clear()- with open(tmp_path2, "w") as f: # noqa: ASYNC230- f.write(- """import marimo as mo+ new_path.write_text(+ """import marimo+app = marimo.App()def __():2return ()"""- )+ )# Wait for the watcher to detect the change- await asyncio.sleep(0.2)+ for _ in range(16): # noqa: B007+ await asyncio.sleep(0.1)+ if len(operations) > 0:+ break# Check that UpdateCellCodes was sent with the new codeupdate_ops = [op for op in operations if isinstance(op, UpdateCellCodes)]assert len(update_ops) == 1- assert "return 2" in update_ops[0].codes[0]+ assert "2" == update_ops[0].codes[0]- # Modify the old file - should not trigger any updates- operations.clear()- with open(tmp_path1, "w") as f: # noqa: ASYNC230- f.write(- """import marimo as mo+ finally:+ # Cleanup+ session_manager.shutdown()+ os.remove(new_path)++@save_and_restore_main+async def test_sync_session_view_from_cache(tmp_path: Path) -> None:+ """Test syncing session view from cache."""+ # Create a temporary file+ notebook_path = tmp_path / "test.py"+ notebook_path.write_text(+ """import marimo++app = marimo.App()+def __():- 3+ 1return ()"""- )+ )- # Wait to verify no updates are triggered- await asyncio.sleep(0.2)- update_ops = [- op for op in operations if isinstance(op, UpdateCellCodes)- ]- assert len(update_ops) == 0+ # Create session with the temporary file+ session_consumer = MagicMock()+ session_consumer.connection_state.return_value = ConnectionState.OPEN+ queue_manager = QueueManager(use_multiprocessing=False)+ kernel_manager = KernelManager(+ queue_manager,+ SessionMode.RUN,+ {},+ app_metadata,+ get_default_config_manager(current_path=None),+ virtual_files_supported=True,+ redirect_console_to_browser=False,+ )- finally:- # Cleanup- session_manager.shutdown()- os.remove(tmp_path1)- os.remove(tmp_path2)+ app_file_manager = AppFileManager(filename=str(notebook_path))+ session = Session(+ "test",+ session_consumer,+ queue_manager,+ kernel_manager,+ app_file_manager,+ ttl_seconds=None,+ )++ # Test syncing when no cache exists+ session.sync_session_view_from_cache()+ # Should create a new empty session view since no cache exists+ assert session.session_view is not None+ assert session.session_cache_manager is not None+ assert session.session_cache_manager.path == str(notebook_path)+ assert (+ session.session_cache_manager.interval+ == Session.SESSION_CACHE_INTERVAL_SECONDS+ )++ # Add some operations to the session view+ session.write_operation(+ UpdateCellCodes(+ cell_ids=["1"],+ codes=["print('hello')"],+ code_is_stale=False,+ ),+ from_consumer_id=None,+ )++ # Create a new session and sync from cache+ session2 = Session(+ "test2",+ session_consumer,+ queue_manager,+ kernel_manager,+ app_file_manager,+ ttl_seconds=None,+ )+ session2.sync_session_view_from_cache()++ # Verify the session views match+ assert session2.session_view is not None+ assert session2.session_cache_manager is not None+ assert session2.session_cache_manager.path == str(notebook_path)+ assert len(session2.session_view.operations) == len(+ session.session_view.operations+ )++ # Test syncing with no file path+ app_file_manager_no_path = AppFileManager.from_app(InternalApp(App()))+ session3 = Session(+ "test3",+ session_consumer,+ queue_manager,+ kernel_manager,+ app_file_manager_no_path,+ ttl_seconds=None,+ )+ session3.sync_session_view_from_cache()+ # Should create a new empty session view since no path exists+ assert session3.session_view is not None+ assert session3.session_cache_manager is not None+ assert session3.session_cache_manager.path is None++ # Cleanup+ session.close()+ session2.close()+ session3.close()+ if kernel_manager.kernel_task:+ kernel_manager.kernel_task.join()diff --git a/tests/_utils/test_background_task.py b/tests/_utils/test_background_task.pynew file mode 100644index 0000000000..6b362489ac--- /dev/null+++ b/tests/_utils/test_background_task.py@@ -0,0 +1,102 @@+from __future__ import annotations++import asyncio++import pytest++from marimo._utils.background_task import AsyncBackgroundTask+++class SimpleTask(AsyncBackgroundTask):+ def __init__(self):+ super().__init__()+ self.startup_called = False+ self.run_called = False+ self.shutdown_called = False+ self.should_raise = False++ async def startup(self):+ self.startup_called = True++ async def run(self):+ self.run_called = True+ if self.should_raise:+ raise ValueError("Test error")+ while self.running: # noqa: ASYNC110+ await asyncio.sleep(0.1)++ async def shutdown(self):+ self.shutdown_called = True+++async def test_task_lifecycle():+ task = SimpleTask()++ # Test startup+ task.start()+ await task.wait_for_startup()+ assert task.startup_called+ assert task.running+ assert task.task is not None+ assert not task.task.done()++ # Test stop+ await task.stop()+ assert not task.running+ assert task.shutdown_called+ assert task.task.done()+++async def test_context_manager():+ async with SimpleTask() as task:+ assert task.startup_called+ assert task.running+ assert task.task is not None+ assert not task.task.done()++ assert not task.running+ assert task.shutdown_called+ assert task.task.done()+++async def test_error_handling():+ task = SimpleTask()+ task.should_raise = True++ task.start()+ with pytest.raises(ValueError, match="Test error"):+ await task.task++ assert not task.running+ assert task.shutdown_called+++async def test_stop_timeout():+ task = SimpleTask()+ task.start()+ await task.wait_for_startup()++ # Test timeout+ await task.stop(timeout=0.1)+ assert not task.running+ assert task.task is not None+ assert task.task.done()+++ reason="""+ Works locally, but fails in CI.+ RuntimeError: There is no current event loop in thread 'MainThread'+"""+)+def test_stop_sync():+ task = SimpleTask()++ async def run():+ task.start()++ asyncio.run(run())+ task.stop_sync(timeout=0.1)+ assert not task.running+ assert task.task is not None+ assert task.task.done()