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: add `marimo export session` CLI tool (#8533)
Péter Gyarmatib1a479966c2f
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.mdindex 291304a3b2..157570fc6d 100644--- a/docs/guides/exporting.md+++ b/docs/guides/exporting.md@@ -122,6 +122,59 @@ their dependency graph.marimo export ipynb notebook.py -o notebook.ipynb```+## Export session snapshots++Run notebooks and write their serialized session snapshots:++```bash+marimo export session notebook.py+```++By default, snapshots are written to:++```text+<notebook_dir>/__marimo__/session/<notebook_filename>.json+```++For example, exporting `notebook.py` writes:++```text+__marimo__/session/notebook.py.json+```++`marimo export session` accepts one positional target: a notebook file or a directory.+To process multiple notebooks, pass a directory target.++Export every notebook in a directory:++```bash+marimo export session folder/+```++Pass CLI args through to notebooks with `--`:++```bash+marimo export session notebook.py -- --foo 123+```++By default, marimo only rewrites session snapshots when they are stale (for example, when the notebook code has changed).+Up-to-date snapshots are skipped.++To force rewriting all snapshots, even when they are up-to-date:++```bash+marimo export session folder/ --force-overwrite+```++If one notebook fails, marimo continues by default and exits non-zero after processing all targets.+Use `--no-continue-on-error` to stop at the first failure.++To execute in a sandboxed environment, pass `--sandbox`:++```bash+marimo export session notebook.py --sandbox+```+## Exporting to PDF, slides, or rst### Export PDF using Quartodiff --git a/marimo/_cli/export/_common.py b/marimo/_cli/export/_common.pynew file mode 100644index 0000000000..0f6d0b2554--- /dev/null+++ b/marimo/_cli/export/_common.py@@ -0,0 +1,95 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import subprocess+from pathlib import Path+from typing import TYPE_CHECKING, Any++import click++from marimo._server.file_router import flatten_files+from marimo._server.files.directory_scanner import DirectoryScanner+from marimo._utils.http import HTTPException, HTTPStatus+from marimo._utils.marimo_path import MarimoPath++if TYPE_CHECKING:+ from collections.abc import Iterable+++def is_multi_target(paths: list[Path]) -> bool:+ return len(paths) > 1 or any(path.is_dir() for path in paths)+++def collect_notebooks(paths: Iterable[Path]) -> list[MarimoPath]:+ notebooks: dict[str, MarimoPath] = {}++ for path in paths:+ if path.is_dir():+ scanner = DirectoryScanner(str(path), include_markdown=True)+ try:+ file_infos = scanner.scan()+ except HTTPException as e:+ if e.status_code != HTTPStatus.REQUEST_TIMEOUT:+ raise+ file_infos = scanner.partial_results++ for file_info in flatten_files(file_infos):+ if not file_info.is_marimo_file or file_info.is_directory:+ continue+ absolute_path = str(Path(path) / file_info.path)+ notebooks[absolute_path] = MarimoPath(absolute_path)+ else:+ notebooks[str(path)] = MarimoPath(str(path))++ return [notebooks[k] for k in sorted(notebooks)]+++class SandboxVenvPool:+ def __init__(self) -> None:+ self._envs: dict[tuple[str, ...], tuple[str, str]] = {}++ def get_python(self, notebook_path: str) -> str:+ from marimo._cli.sandbox import (+ build_sandbox_venv,+ get_sandbox_requirements,+ )++ requirements = tuple(get_sandbox_requirements(notebook_path))+ existing = self._envs.get(requirements)+ if existing is not None:+ return existing[1]++ sandbox_dir, venv_python = build_sandbox_venv(notebook_path)+ self._envs[requirements] = (sandbox_dir, venv_python)+ return venv_python++ def close(self) -> None:+ from marimo._cli.sandbox import cleanup_sandbox_dir++ for sandbox_dir, _ in self._envs.values():+ cleanup_sandbox_dir(sandbox_dir)+ self._envs.clear()+++def run_python_subprocess(+ *,+ venv_python: str,+ script: str,+ payload: dict[str, Any],+ action: str,+) -> str:+ result = subprocess.run(+ [venv_python, "-c", script, json.dumps(payload)],+ check=False,+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ stderr = result.stderr.strip()+ raise click.ClickException(+ f"Failed to {action} in sandbox.\n\n"+ f"Command:\n\n {venv_python} -c <script>\n\n"+ f"Stderr:\n\n{stderr}"+ )+ return result.stdoutdiff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 5aebdf786c..df9128a11f 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -9,6 +9,7 @@ import clickfrom marimo._cli.errors import MarimoCLIMissingDependencyErrorfrom marimo._cli.export.cloudflare import create_cloudflare_files+from marimo._cli.export.session import sessionfrom marimo._cli.export.thumbnail import thumbnailfrom marimo._cli.help_formatter import ColoredCommand, ColoredGroupfrom marimo._cli.install_hints import get_playwright_chromium_setup_commands@@ -937,3 +938,4 @@ export.add_command(ipynb)export.add_command(pdf)export.add_command(html_wasm)export.add_command(thumbnail)+export.add_command(session)diff --git a/marimo/_cli/export/session.py b/marimo/_cli/export/session.pynew file mode 100644index 0000000000..10b995d041--- /dev/null+++ b/marimo/_cli/export/session.py@@ -0,0 +1,411 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import json+import sys+from collections import Counter+from pathlib import Path+from typing import TYPE_CHECKING, Any, Optional, cast++import click++from marimo._cli.errors import MarimoCLIMissingDependencyError+from marimo._cli.export._common import (+ SandboxVenvPool,+ collect_notebooks,+ is_multi_target,+ run_python_subprocess,+)+from marimo._cli.parse_args import parse_args+from marimo._cli.print import echo, green, red, yellow+from marimo._dependencies.dependencies import DependencyManager+from marimo._schemas.session import NotebookSessionV1+from marimo._server.export import run_app_until_completion+from marimo._server.file_router import AppFileRouter+from marimo._server.utils import asyncio_run+from marimo._session.state.serialize import (+ get_session_cache_file,+ serialize_session_view,+)+from marimo._utils.code import hash_code+from marimo._utils.marimo_path import MarimoPath+from marimo._utils.paths import maybe_make_dirs++if TYPE_CHECKING:+ from marimo._cli.sandbox import SandboxMode++_sandbox_message = (+ "Run the command in an isolated virtual environment using "+ "`uv run --isolated`. Requires `uv`."+)+++def _resolve_session_sandbox_mode(+ *,+ sandbox: bool | None,+ path_targets: list[Path],+ first_target: str,+) -> SandboxMode | None:+ from marimo._cli.sandbox import SandboxMode, resolve_sandbox_mode++ if is_multi_target(path_targets):+ if sandbox is None:+ return None+ return SandboxMode.MULTI if sandbox else None++ return resolve_sandbox_mode(sandbox=sandbox, name=first_target)+++async def _export_session_snapshot(+ marimo_path: MarimoPath,+ *,+ notebook_args: tuple[str, ...],+ venv_python: str | None = None,+) -> tuple[NotebookSessionV1, bool]:+ if venv_python is None:+ cli_args = parse_args(notebook_args) if notebook_args else {}++ file_router = AppFileRouter.from_filename(marimo_path)+ file_key = file_router.get_unique_file_key()+ if file_key is None:+ raise RuntimeError(+ "Expected a unique file key when exporting a single "+ f"notebook: {marimo_path.absolute_name}"+ )+ file_manager = file_router.get_file_manager(file_key)++ session_view, did_error = await run_app_until_completion(+ file_manager,+ cli_args=cli_args,+ argv=list(notebook_args),+ quiet=True,+ )+ session_snapshot = serialize_session_view(+ session_view,+ cell_ids=list(file_manager.app.cell_manager.cell_ids()),+ )+ return session_snapshot, did_error++ payload = {+ "path": marimo_path.absolute_name,+ "args": list(notebook_args),+ }+ return await asyncio.to_thread(+ _export_session_snapshot_in_subprocess,+ venv_python,+ payload,+ )+++def _export_session_snapshot_in_subprocess(+ venv_python: str, payload: dict[str, Any]+) -> tuple[NotebookSessionV1, bool]:+ script = r"""+import asyncio+import json+import sys++from marimo._cli.parse_args import parse_args+from marimo._server.export import run_app_until_completion+from marimo._server.file_router import AppFileRouter+from marimo._session.state.serialize import serialize_session_view+from marimo._utils.marimo_path import MarimoPath++payload = json.loads(sys.argv[1])+path = MarimoPath(payload["path"])+args = payload.get("args") or []++file_router = AppFileRouter.from_filename(path)+file_key = file_router.get_unique_file_key()+if file_key is None:+ raise RuntimeError("Expected a unique file key for session export.")+file_manager = file_router.get_file_manager(file_key)++cli_args = parse_args(tuple(args)) if args else {}+session_view, did_error = asyncio.run(+ run_app_until_completion(+ file_manager,+ cli_args=cli_args,+ argv=list(args),+ quiet=True,+ )+)+session_snapshot = serialize_session_view(+ session_view,+ cell_ids=list(file_manager.app.cell_manager.cell_ids()),+)++sys.stdout.write(+ json.dumps(+ {+ "session_snapshot": session_snapshot,+ "did_error": did_error,+ }+ )+)+"""++ output = run_python_subprocess(+ venv_python=venv_python,+ script=script,+ payload=payload,+ action="export session",+ )++ try:+ data = cast(dict[str, Any], json.loads(output))+ except json.JSONDecodeError as e:+ raise click.ClickException(+ "Failed to parse sandbox session export output.\n\n"+ f"Stdout:\n\n{output.strip()}"+ ) from e++ session_snapshot = data.get("session_snapshot")+ did_error = bool(data.get("did_error", False))+ if not isinstance(session_snapshot, dict):+ raise click.ClickException(+ "Sandbox session export returned an invalid payload."+ )++ return cast(NotebookSessionV1, session_snapshot), did_error+++async def _export_session_for_notebook(+ notebook: MarimoPath,+ *,+ force_overwrite: bool,+ notebook_args: tuple[str, ...],+ sandbox_pool: SandboxVenvPool | None,+) -> None:+ output = get_session_cache_file(notebook.path)+ if _maybe_skip_fresh_snapshot(notebook, force_overwrite=force_overwrite):+ return++ echo(f"Running {notebook.short_name}...")+ venv_python = (+ sandbox_pool.get_python(str(notebook.path))+ if sandbox_pool is not None+ else None+ )++ session_snapshot, did_error = await _export_session_snapshot(+ notebook,+ notebook_args=notebook_args,+ venv_python=venv_python,+ )++ maybe_make_dirs(output)+ output.write_text(json.dumps(session_snapshot, indent=2), encoding="utf-8")++ if did_error:+ raise click.ClickException(+ "Session export succeeded, but some cells failed to execute."+ )++ echo(green("ok") + f": {output}")+++def _hash_code_for_session_compare(code: str | None) -> str | None:+ if code is None or code == "":+ return None+ return hash_code(code)+++def _current_notebook_code_hashes(+ notebook: MarimoPath,+) -> tuple[str | None, ...]:+ file_router = AppFileRouter.from_filename(notebook)+ file_key = file_router.get_unique_file_key()+ if file_key is None:+ raise RuntimeError(+ "Expected a unique file key when checking staleness for "+ f"{notebook.absolute_name}"+ )+ file_manager = file_router.get_file_manager(file_key)+ return tuple(+ _hash_code_for_session_compare(cell_data.code)+ for cell_data in file_manager.app.cell_manager.cell_data()+ )+++def _is_session_snapshot_stale(output: Path, notebook: MarimoPath) -> bool:+ """Return True when a saved session should be regenerated.++ We treat a snapshot as stale if we cannot read it, if it is malformed, or+ if the notebook's current cell code-hash multiset does not match the snapshot.+ Code hashes are compared order-independently because notebook and+ session cell ordering can differ across code paths.+ """+ try:+ snapshot = cast(+ dict[str, Any], json.loads(output.read_text(encoding="utf-8"))+ )+ except (OSError, json.JSONDecodeError):+ return True++ metadata = snapshot.get("metadata")+ if not isinstance(metadata, dict):+ return True++ cells = snapshot.get("cells")+ if not isinstance(cells, list):+ return True++ try:+ current_hashes = _current_notebook_code_hashes(notebook)+ except (RuntimeError, ValueError, OSError, SyntaxError):+ return True++ notebook_hashes = Counter(current_hashes)++ session_hashes: Counter[str | None] = Counter()+ for cell in cells:+ if not isinstance(cell, dict):+ return True+ if "code_hash" not in cell:+ return True+ code_hash = cell["code_hash"]+ if code_hash is not None and not isinstance(code_hash, str):+ return True+ session_hashes[code_hash] += 1++ return notebook_hashes != session_hashes+++def _maybe_skip_fresh_snapshot(+ notebook: MarimoPath, *, force_overwrite: bool+) -> bool:+ output = get_session_cache_file(notebook.path)+ if force_overwrite or not output.exists():+ return False+ if _is_session_snapshot_stale(output, notebook):+ return False++ echo(+ yellow("skip") + f": {notebook.short_name} "+ "(up-to-date, use --force-overwrite if you want to re-export anyway)"+ )+ return True+++async def _export_sessions(+ *,+ notebooks: list[MarimoPath],+ force_overwrite: bool,+ notebook_args: tuple[str, ...],+ continue_on_error: bool,+ sandbox_mode: SandboxMode | None,+) -> None:+ from marimo._cli.sandbox import SandboxMode++ failures: list[tuple[MarimoPath, Exception]] = []+ use_per_notebook_sandbox = sandbox_mode is SandboxMode.MULTI++ if use_per_notebook_sandbox and not DependencyManager.which("uv"):+ raise MarimoCLIMissingDependencyError(+ "uv is required for --sandbox session export.",+ "uv",+ additional_tip="Install uv from https://github.com/astral-sh/uv",+ )++ sandbox_pool: SandboxVenvPool | None = (+ SandboxVenvPool() if use_per_notebook_sandbox else None+ )++ try:+ for notebook in notebooks:+ try:+ await _export_session_for_notebook(+ notebook,+ force_overwrite=force_overwrite,+ notebook_args=notebook_args,+ sandbox_pool=sandbox_pool,+ )+ except Exception as error:+ failures.append((notebook, error))+ echo(red("error") + f": {notebook.short_name}: {error}")+ if not continue_on_error:+ raise+ finally:+ if sandbox_pool is not None:+ sandbox_pool.close()++ if failures:+ raise click.ClickException(+ f"Failed to export sessions for {len(failures)} notebooks."+ )+++ "session",+ help=(+ "Execute a notebook or directory of notebooks and export session snapshots."+ ),+)+ "name",+ type=click.Path(+ exists=True, file_okay=True, dir_okay=True, path_type=Path+ ),+)+ "--sandbox/--no-sandbox",+ is_flag=True,+ default=None,+ type=bool,+ help=_sandbox_message,+)+ "--force-overwrite/--no-force-overwrite",+ default=False,+ help=(+ "Overwrite all existing session snapshots, even if they are "+ "already up-to-date."+ ),+)+ "--continue-on-error/--no-continue-on-error",+ default=True,+ help="Continue processing other notebooks if one notebook fails.",+)[email protected]("args", nargs=-1, type=click.UNPROCESSED)+def session(+ name: Path,+ sandbox: Optional[bool],+ force_overwrite: bool,+ continue_on_error: bool,+ args: tuple[str, ...],+) -> None:+ """Execute notebooks and export their session snapshots."""+ path_targets = [name]+ notebooks = collect_notebooks(path_targets)+ if not notebooks:+ raise click.ClickException("No marimo notebooks found.")++ sandbox_mode = _resolve_session_sandbox_mode(+ sandbox=sandbox,+ path_targets=path_targets,+ first_target=str(name),+ )++ from marimo._cli.sandbox import SandboxMode, run_in_sandbox++ if sandbox_mode is SandboxMode.SINGLE:+ notebook = notebooks[0]+ if _maybe_skip_fresh_snapshot(+ notebook, force_overwrite=force_overwrite+ ):+ return+ run_in_sandbox(sys.argv[1:], name=str(name))+ return++ asyncio_run(+ _export_sessions(+ notebooks=notebooks,+ force_overwrite=force_overwrite,+ notebook_args=args,+ continue_on_error=continue_on_error,+ sandbox_mode=sandbox_mode,+ )+ )diff --git a/marimo/_cli/export/thumbnail.py b/marimo/_cli/export/thumbnail.pyindex 693e2c2bb0..5759776c89 100644--- a/marimo/_cli/export/thumbnail.py+++ b/marimo/_cli/export/thumbnail.py@@ -2,9 +2,7 @@from __future__ import annotationsimport asyncio-import jsonimport os-import subprocessimport sysfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Optional@@ -12,22 +10,23 @@ from typing import TYPE_CHECKING, Any, Optionalimport clickfrom marimo._cli.errors import MarimoCLIMissingDependencyError+from marimo._cli.export._common import (+ SandboxVenvPool,+ collect_notebooks,+ is_multi_target,+ run_python_subprocess,+)from marimo._cli.install_hints import get_playwright_chromium_setup_commandsfrom marimo._cli.parse_args import parse_argsfrom marimo._cli.print import echo, green, red, yellowfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._server.export import run_app_then_export_as_htmlfrom marimo._server.export._html_asset_server import HtmlAssetServer-from marimo._server.file_router import flatten_files-from marimo._server.files.directory_scanner import DirectoryScannerfrom marimo._server.utils import asyncio_run-from marimo._utils.http import HTTPException, HTTPStatusfrom marimo._utils.marimo_path import MarimoPathfrom marimo._utils.paths import marimo_package_path, maybe_make_dirsif TYPE_CHECKING:- from collections.abc import Iterable-from marimo._cli.sandbox import SandboxMode@@ -53,34 +52,6 @@ def _split_paths_and_args(return paths, ()-def _collect_notebooks(paths: Iterable[Path]) -> list[MarimoPath]:- notebooks: dict[str, MarimoPath] = {}-- for path in paths:- if path.is_dir():- scanner = DirectoryScanner(str(path), include_markdown=True)- try:- file_infos = scanner.scan()- except HTTPException as e:- if e.status_code != HTTPStatus.REQUEST_TIMEOUT:- raise- # Match server behavior: use partial results on scan timeout.- file_infos = scanner.partial_results- for file_info in flatten_files(file_infos):- if not file_info.is_marimo_file or file_info.is_directory:- continue- absolute_path = str(Path(path) / file_info.path)- notebooks[absolute_path] = MarimoPath(absolute_path)- else:- notebooks[str(path)] = MarimoPath(str(path))-- return [notebooks[k] for k in sorted(notebooks)]---def _is_multi_target(paths: list[Path]) -> bool:- return len(paths) > 1 or any(path.is_dir() for path in paths)--def _sandbox_mode_from_env() -> SandboxMode | None:from marimo._cli.sandbox import SandboxMode@@ -111,7 +82,7 @@ def _resolve_thumbnail_sandbox_mode(if env_mode is not None:return env_mode- if _is_multi_target(path_targets):+ if is_multi_target(path_targets):if sandbox is None:return Nonereturn SandboxMode.MULTI if sandbox else None@@ -213,48 +184,12 @@ result = asyncio.run(sys.stdout.write(result.text)"""- result = subprocess.run(- [venv_python, "-c", script, json.dumps(payload)],- capture_output=True,- text=True,+ return run_python_subprocess(+ venv_python=venv_python,+ script=script,+ payload=payload,+ action="render notebook",)- if result.returncode != 0:- stderr = result.stderr.strip()- raise click.ClickException(- "Failed to render notebook in sandbox.\n\n"- f"Command:\n\n {venv_python} -c <script>\n\n"- f"Stderr:\n\n{stderr}"- )- return result.stdout---class _SandboxVenvPool:- def __init__(self) -> None:- self._envs: dict[tuple[str, ...], tuple[str, str]] = {}-- def get_python(self, notebook_path: str) -> str:- """Return a venv python path for the notebook's sandbox requirements."""- from marimo._cli.sandbox import (- build_sandbox_venv,- get_sandbox_requirements,- )-- requirements = tuple(get_sandbox_requirements(notebook_path))- existing = self._envs.get(requirements)- if existing is not None:- return existing[1]-- sandbox_dir, venv_python = build_sandbox_venv(notebook_path)- self._envs[requirements] = (sandbox_dir, venv_python)- return venv_python-- def close(self) -> None:- """Clean up any sandbox environments we created."""- from marimo._cli.sandbox import cleanup_sandbox_dir-- for sandbox_dir, _ in self._envs.values():- cleanup_sandbox_dir(sandbox_dir)- self._envs.clear()async def _generate_thumbnails(@@ -302,8 +237,8 @@ async def _generate_thumbnails(static_dir = marimo_package_path() / "_static"- sandbox_pool: _SandboxVenvPool | None = (- _SandboxVenvPool() if use_per_notebook_sandbox else None+ sandbox_pool: SandboxVenvPool | None = (+ SandboxVenvPool() if use_per_notebook_sandbox else None)try:with HtmlAssetServer(@@ -507,7 +442,7 @@ def thumbnail("""Generate thumbnails for one or more notebooks (or directories)."""paths, notebook_args = _split_paths_and_args(str(name), args)path_targets = [Path(p) for p in paths]- notebooks = _collect_notebooks(path_targets)+ notebooks = collect_notebooks(path_targets)if not notebooks:raise click.ClickException("No marimo notebooks found.")if output is not None and len(notebooks) > 1:diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex a2dbbeecf2..c2278110e1 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -18,6 +18,7 @@ from click.testing import CliRunnerfrom marimo._cli.export.commands import pdffrom marimo._dependencies.dependencies import DependencyManager+from marimo._session.state.serialize import get_session_cache_filefrom marimo._utils import async_pathfrom marimo._utils.platform import is_windowsfrom tests._server.templates.utils import normalize_index_html@@ -49,7 +50,12 @@ def _run_export() -> subprocess.CompletedProcess[bytes]:"""Helper to run marimo export commands."""cmd = ["marimo", "export", export_format, file, *extra_args]- return subprocess.run(cmd, capture_output=capture_output, input=input_data)+ return subprocess.run(+ cmd,+ check=False,+ capture_output=capture_output,+ input=input_data,+ )def _assert_success(p: subprocess.CompletedProcess[bytes]) -> None:@@ -1080,6 +1086,232 @@ class TestExportThumbnail:_assert_success(p)+class TestExportSession:+ @staticmethod+ def test_export_session(temp_marimo_file: str) -> None:+ p = _run_export("session", temp_marimo_file)+ _assert_success(p)++ session_file = get_session_cache_file(Path(temp_marimo_file))+ assert session_file.exists()+ data = json.loads(session_file.read_text(encoding="utf-8"))+ assert data["version"] == "1"+ assert len(data["cells"]) > 0++ @staticmethod+ def test_export_session_with_args(temp_marimo_file: str) -> None:+ p = _run_export("session", temp_marimo_file, "--", "--foo", "123")+ _assert_success(p)++ session_file = get_session_cache_file(Path(temp_marimo_file))+ assert session_file.exists()++ @staticmethod+ def test_export_session_default_skips_up_to_date(+ temp_marimo_file: str,+ ) -> None:+ p = _run_export("session", temp_marimo_file)+ _assert_success(p)++ session_file = get_session_cache_file(Path(temp_marimo_file))+ existing = json.loads(session_file.read_text(encoding="utf-8"))+ existing["custom"] = "keep-me"+ session_file.write_text(+ json.dumps(existing, indent=2), encoding="utf-8"+ )++ p = _run_export("session", temp_marimo_file)+ _assert_success(p)++ unchanged = json.loads(session_file.read_text(encoding="utf-8"))+ assert unchanged.get("custom") == "keep-me"+ assert b"skip" in p.stdout++ @staticmethod+ def test_export_session_force_overwrite_rewrites_up_to_date(+ temp_marimo_file: str,+ ) -> None:+ p = _run_export("session", temp_marimo_file)+ _assert_success(p)++ session_file = get_session_cache_file(Path(temp_marimo_file))+ existing = json.loads(session_file.read_text(encoding="utf-8"))+ existing["custom"] = "remove-me"+ session_file.write_text(+ json.dumps(existing, indent=2), encoding="utf-8"+ )++ p = _run_export("session", temp_marimo_file, "--force-overwrite")+ _assert_success(p)++ data = json.loads(session_file.read_text(encoding="utf-8"))+ assert data["version"] == "1"+ assert len(data["cells"]) > 0+ assert "custom" not in data++ @staticmethod+ def test_export_session_default_overwrites_stale(+ temp_marimo_file: str,+ ) -> None:+ p = _run_export("session", temp_marimo_file)+ _assert_success(p)++ notebook_path = Path(temp_marimo_file)+ session_file = get_session_cache_file(notebook_path)+ before = json.loads(session_file.read_text(encoding="utf-8"))++ notebook_path.write_text(+ notebook_path.read_text(encoding="utf-8").replace(+ "slider = mo.ui.slider(0, 10)",+ "slider = mo.ui.slider(0, 11)",+ ),+ encoding="utf-8",+ )++ p = _run_export("session", temp_marimo_file)+ _assert_success(p)++ after = json.loads(session_file.read_text(encoding="utf-8"))+ assert [c["code_hash"] for c in before["cells"]] != [+ c["code_hash"] for c in after["cells"]+ ]++ def test_export_session_directory_default_skips_up_to_date(+ self,+ tmp_path: Path,+ temp_marimo_file: str,+ ) -> None:+ notebook_dir = tmp_path / "notebooks"+ notebook_dir.mkdir()+ code = Path(temp_marimo_file).read_text(encoding="utf-8")+ first = notebook_dir / "first.py"+ second = notebook_dir / "second.py"+ first.write_text(code, encoding="utf-8")+ second.write_text(code, encoding="utf-8")++ p = _run_export("session", str(first))+ _assert_success(p)++ first_session = get_session_cache_file(first)+ existing = json.loads(first_session.read_text(encoding="utf-8"))+ existing["custom"] = "keep-me"+ first_session.write_text(+ json.dumps(existing, indent=2), encoding="utf-8"+ )++ p = _run_export("session", str(notebook_dir))+ _assert_success(p)++ second_session = get_session_cache_file(second)+ first_data = json.loads(first_session.read_text(encoding="utf-8"))+ assert first_data.get("custom") == "keep-me"+ assert second_session.exists()+ data = json.loads(second_session.read_text(encoding="utf-8"))+ assert data["version"] == "1"++ @staticmethod+ def test_export_session_ignores_second_positional_target(+ temp_marimo_file: str,+ temp_async_marimo_file: str,+ ) -> None:+ p = _run_export(+ "session",+ temp_marimo_file,+ temp_async_marimo_file,+ )+ _assert_success(p)++ first_session = get_session_cache_file(Path(temp_marimo_file))+ second_session = get_session_cache_file(Path(temp_async_marimo_file))+ assert first_session.exists()+ assert not second_session.exists()++ @staticmethod+ def test_export_session_directory(+ tmp_path: Path,+ temp_marimo_file: str,+ ) -> None:+ notebook_dir = tmp_path / "notebooks"+ notebook_dir.mkdir()+ code = Path(temp_marimo_file).read_text(encoding="utf-8")+ first = notebook_dir / "first.py"+ second = notebook_dir / "second.py"+ first.write_text(code, encoding="utf-8")+ second.write_text(code, encoding="utf-8")++ p = _run_export("session", str(notebook_dir))+ _assert_success(p)++ first_session = get_session_cache_file(first)+ second_session = get_session_cache_file(second)+ assert first_session.exists()+ assert second_session.exists()++ @staticmethod+ def test_export_session_with_errors_writes_snapshot(+ temp_marimo_file_with_errors: str,+ ) -> None:+ p = _run_export("session", temp_marimo_file_with_errors)+ _assert_failure(p)++ session_file = get_session_cache_file(+ Path(temp_marimo_file_with_errors)+ )+ assert session_file.exists()++ @staticmethod+ def test_export_session_default_skips_if_previous_snapshot_has_errors(+ temp_marimo_file_with_errors: str,+ ) -> None:+ session_file = get_session_cache_file(+ Path(temp_marimo_file_with_errors)+ )++ first = _run_export("session", temp_marimo_file_with_errors)+ _assert_failure(first)+ assert session_file.exists()++ existing = json.loads(session_file.read_text(encoding="utf-8"))+ existing["custom"] = "should-be-overwritten"+ session_file.write_text(+ json.dumps(existing, indent=2),+ encoding="utf-8",+ )++ second = _run_export("session", temp_marimo_file_with_errors)+ _assert_success(second)+ assert b"skip" in second.stdout+ unchanged = json.loads(session_file.read_text(encoding="utf-8"))+ assert unchanged.get("custom") == "should-be-overwritten"++ @staticmethod+ def test_export_session_continue_on_error_default(+ tmp_path: Path,+ temp_marimo_file: str,+ temp_marimo_file_with_errors: str,+ ) -> None:+ notebook_dir = tmp_path / "notebooks"+ notebook_dir.mkdir()+ good = notebook_dir / "good.py"+ bad = notebook_dir / "bad.py"+ good.write_text(+ Path(temp_marimo_file).read_text(encoding="utf-8"),+ encoding="utf-8",+ )+ bad.write_text(+ Path(temp_marimo_file_with_errors).read_text(encoding="utf-8"),+ encoding="utf-8",+ )++ p = _run_export("session", str(notebook_dir))+ _assert_failure(p)++ good_session = get_session_cache_file(good)+ bad_session = get_session_cache_file(bad)+ assert good_session.exists()+ assert bad_session.exists()++class TestClickArgsParsing:"""Tests below are technically testing Click more than Marimo. This was created as part of an investigation intodiff --git a/tests/_cli/test_cli_export_session.py b/tests/_cli/test_cli_export_session.pynew file mode 100644index 0000000000..df282475bc--- /dev/null+++ b/tests/_cli/test_cli_export_session.py@@ -0,0 +1,463 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+from typing import TYPE_CHECKING+from unittest.mock import AsyncMock, patch++import click+import pytest+from click.testing import CliRunner++import marimo._cli.export.session as session_module+from marimo._cli.sandbox import SandboxMode+from marimo._server.utils import asyncio_run+from marimo._session.state.serialize import get_session_cache_file+from marimo._version import __version__++if TYPE_CHECKING:+ from pathlib import Path+++def _write_notebook(path: Path) -> None:+ path.write_text(+ """+import marimo++app = marimo.App()++def _():+ return++if __name__ == "__main__":+ app.run()+""",+ encoding="utf-8",+ )+++def test_session_sandbox_single_runs_in_sandbox(tmp_path: Path) -> None:+ notebook = tmp_path / "notebook.py"+ _write_notebook(notebook)+ runner = CliRunner()+ export_sessions = AsyncMock()++ with (+ patch(+ "marimo._cli.sandbox.run_in_sandbox",+ return_value=0,+ ) as run_in_sandbox,+ patch(+ "marimo._cli.sandbox.resolve_sandbox_mode",+ return_value=SandboxMode.SINGLE,+ ) as resolve_sandbox_mode,+ patch.object(session_module, "_export_sessions", new=export_sessions),+ ):+ result = runner.invoke(+ session_module.session,+ [str(notebook), "--sandbox"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_called_once()+ resolve_sandbox_mode.assert_called_once()+ assert run_in_sandbox.call_args.kwargs["name"] == str(notebook)+ export_sessions.assert_not_called()+++def test_session_sandbox_single_skips_before_sandbox_when_fresh(+ tmp_path: Path,+) -> None:+ notebook = tmp_path / "notebook.py"+ _write_notebook(notebook)+ session_file = get_session_cache_file(notebook)+ session_file.parent.mkdir(parents=True, exist_ok=True)+ session_file.write_text("{}", encoding="utf-8")+ runner = CliRunner()++ with (+ patch(+ "marimo._cli.sandbox.resolve_sandbox_mode",+ return_value=SandboxMode.SINGLE,+ ),+ patch.object(+ session_module,+ "_is_session_snapshot_stale",+ return_value=False,+ ) as is_stale,+ patch("marimo._cli.sandbox.run_in_sandbox") as run_in_sandbox,+ ):+ result = runner.invoke(+ session_module.session,+ [str(notebook), "--sandbox"],+ )++ assert result.exit_code == 0, result.output+ is_stale.assert_called_once()+ run_in_sandbox.assert_not_called()+ assert "skip:" in result.output+++def test_session_sandbox_multi_uses_in_process_export(tmp_path: Path) -> None:+ notebook_dir = tmp_path / "notebooks"+ notebook_dir.mkdir()+ first = notebook_dir / "first.py"+ second = notebook_dir / "second.py"+ _write_notebook(first)+ _write_notebook(second)+ runner = CliRunner()+ export_sessions = AsyncMock()++ with (+ patch("marimo._cli.sandbox.run_in_sandbox") as run_in_sandbox,+ patch("marimo._cli.sandbox.resolve_sandbox_mode") as resolve_mode,+ patch.object(session_module, "_export_sessions", new=export_sessions),+ ):+ result = runner.invoke(+ session_module.session,+ [str(notebook_dir), "--sandbox"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_not_called()+ resolve_mode.assert_not_called()+ export_sessions.assert_called_once()+ assert (+ export_sessions.call_args.kwargs["sandbox_mode"] is SandboxMode.MULTI+ )+++def test_session_no_sandbox_uses_in_process_export(tmp_path: Path) -> None:+ notebook = tmp_path / "notebook.py"+ _write_notebook(notebook)+ runner = CliRunner()+ export_sessions = AsyncMock()++ with (+ patch("marimo._cli.sandbox.run_in_sandbox") as run_in_sandbox,+ patch(+ "marimo._cli.sandbox.resolve_sandbox_mode", return_value=None+ ) as resolve_mode,+ patch.object(session_module, "_export_sessions", new=export_sessions),+ ):+ result = runner.invoke(+ session_module.session,+ [str(notebook), "--no-sandbox"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_not_called()+ resolve_mode.assert_called_once()+ export_sessions.assert_called_once()+ assert export_sessions.call_args.kwargs["sandbox_mode"] is None+++def test_export_sessions_continue_on_error_processes_remaining(+ tmp_path: Path,+) -> None:+ first = tmp_path / "first.py"+ second = tmp_path / "second.py"+ third = tmp_path / "third.py"+ _write_notebook(first)+ _write_notebook(second)+ _write_notebook(third)+ notebooks = [+ session_module.MarimoPath(str(p)) for p in [first, second, third]+ ]++ called: list[str] = []++ async def fake_export(+ marimo_path: session_module.MarimoPath,+ *,+ notebook_args: tuple[str, ...],+ venv_python: str | None = None,+ ) -> tuple[dict[str, str], bool]:+ del notebook_args, venv_python+ called.append(marimo_path.short_name)+ if marimo_path.short_name == "second.py":+ raise click.ClickException("boom")+ return {"name": marimo_path.short_name}, False++ with (+ patch.object(+ session_module,+ "_export_session_snapshot",+ new=AsyncMock(side_effect=fake_export),+ ),+ pytest.raises(+ click.ClickException,+ match="Failed to export sessions for 1 notebooks",+ ),+ ):+ asyncio_run(+ session_module._export_sessions(+ notebooks=notebooks,+ force_overwrite=True,+ notebook_args=(),+ continue_on_error=True,+ sandbox_mode=None,+ )+ )++ assert called == ["first.py", "second.py", "third.py"]+ assert get_session_cache_file(first).exists()+ assert not get_session_cache_file(second).exists()+ assert get_session_cache_file(third).exists()+++def test_export_sessions_no_continue_on_error_stops_at_first_error(+ tmp_path: Path,+) -> None:+ first = tmp_path / "first.py"+ second = tmp_path / "second.py"+ third = tmp_path / "third.py"+ _write_notebook(first)+ _write_notebook(second)+ _write_notebook(third)+ notebooks = [+ session_module.MarimoPath(str(p)) for p in [first, second, third]+ ]++ called: list[str] = []++ async def fake_export(+ marimo_path: session_module.MarimoPath,+ *,+ notebook_args: tuple[str, ...],+ venv_python: str | None = None,+ ) -> tuple[dict[str, str], bool]:+ del notebook_args, venv_python+ called.append(marimo_path.short_name)+ if marimo_path.short_name == "first.py":+ raise click.ClickException("first failed")+ return {"name": marimo_path.short_name}, False++ with (+ patch.object(+ session_module,+ "_export_session_snapshot",+ new=AsyncMock(side_effect=fake_export),+ ),+ pytest.raises(click.ClickException, match="first failed"),+ ):+ asyncio_run(+ session_module._export_sessions(+ notebooks=notebooks,+ force_overwrite=True,+ notebook_args=(),+ continue_on_error=False,+ sandbox_mode=None,+ )+ )++ assert called == ["first.py"]+ assert not get_session_cache_file(first).exists()+ assert not get_session_cache_file(second).exists()+ assert not get_session_cache_file(third).exists()+++def test_export_session_snapshot_subprocess_invalid_json() -> None:+ with (+ patch.object(+ session_module, "run_python_subprocess", return_value="not json"+ ),+ pytest.raises(+ click.ClickException,+ match="Failed to parse sandbox session export output",+ ),+ ):+ session_module._export_session_snapshot_in_subprocess(+ "python",+ {"path": "notebook.py", "args": []},+ )+++class TestSessionSnapshotStaleness:+ @staticmethod+ def _write_snapshot(path: Path, payload: dict[str, object]) -> None:+ path.write_text(json.dumps(payload), encoding="utf-8")++ @staticmethod+ def _make_snapshot(+ code_hashes: list[str | None],+ ) -> dict[str, object]:+ return {+ "version": "1",+ "metadata": {"marimo_version": __version__},+ "cells": [+ {"code_hash": code_hash, "outputs": []}+ for code_hash in code_hashes+ ],+ }++ @staticmethod+ def test_is_session_snapshot_stale_false_when_snapshot_is_current(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(+ ["hash-b", "hash-a", None, "hash-a"]+ )+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=("hash-a", None, "hash-a", "hash-b"),+ ):+ assert (+ session_module._is_session_snapshot_stale(output, notebook)+ is False+ )++ @staticmethod+ def test_is_session_snapshot_stale_false_when_version_changes_only(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(["hash-a"])+ snapshot["metadata"] = {"marimo_version": "0.0.0"}+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=("hash-a",),+ ):+ assert (+ session_module._is_session_snapshot_stale(output, notebook)+ is False+ )++ @staticmethod+ def test_is_session_snapshot_stale_false_when_snapshot_has_errors_only(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(["hash-a"])+ snapshot["cells"] = [+ {+ "code_hash": "hash-a",+ "outputs": [{"type": "error", "msg": "boom"}],+ }+ ]+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=("hash-a",),+ ):+ assert (+ session_module._is_session_snapshot_stale(output, notebook)+ is False+ )++ @staticmethod+ @pytest.mark.parametrize(+ ("current_hashes", "snapshot_hashes"),+ [+ (("hash-a",), ["hash-a", "hash-b"]),+ (("hash-a",), ["hash-b"]),+ ],+ ids=[+ "cell-count-changed",+ "cell-code-changed",+ ],+ )+ def test_is_session_snapshot_stale_true_when_code_hashes_do_not_match(+ tmp_path: Path,+ current_hashes: tuple[str | None, ...],+ snapshot_hashes: list[str | None],+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(snapshot_hashes)+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=current_hashes,+ ):+ assert session_module._is_session_snapshot_stale(output, notebook)++ @staticmethod+ def test_is_session_snapshot_stale_true_when_hash_multiplicity_differs(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(["hash-a"])+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=("hash-a", "hash-a"),+ ):+ assert session_module._is_session_snapshot_stale(output, notebook)++ @staticmethod+ def test_is_session_snapshot_stale_true_when_cell_missing_code_hash(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(["hash-a"])+ snapshot["cells"] = [{"outputs": []}]+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=("hash-a",),+ ):+ assert session_module._is_session_snapshot_stale(output, notebook)++ @staticmethod+ def test_is_session_snapshot_stale_true_when_code_hash_has_wrong_type(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(["hash-a"])+ snapshot["cells"] = [{"code_hash": 1, "outputs": []}]+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ return_value=("hash-a",),+ ):+ assert session_module._is_session_snapshot_stale(output, notebook)++ @staticmethod+ def test_is_session_snapshot_stale_true_when_snapshot_is_unreadable(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ output.write_text("{ not valid json", encoding="utf-8")+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))+ assert session_module._is_session_snapshot_stale(output, notebook)++ @staticmethod+ def test_is_session_snapshot_stale_true_when_hash_lookup_fails(+ tmp_path: Path,+ ) -> None:+ output = tmp_path / "session.json"+ snapshot = TestSessionSnapshotStaleness._make_snapshot(["hash-a"])+ TestSessionSnapshotStaleness._write_snapshot(output, snapshot)+ notebook = session_module.MarimoPath(str(tmp_path / "notebook.py"))++ with patch.object(+ session_module,+ "_current_notebook_code_hashes",+ side_effect=RuntimeError("failed to inspect notebook"),+ ):+ assert session_module._is_session_snapshot_stale(output, notebook)