Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: consider PEP 723 metadata in session staleness logic (#8547)

Péter Gyarmatib363e8900674
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.md
index 157570fc6d..a3f7028dce 100644
--- a/docs/guides/exporting.md
+++ b/docs/guides/exporting.md
@@ -157,7 +157,7 @@ Pass CLI args through to notebooks with `--`:
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).
+By default, marimo only rewrites session snapshots when they are stale (for example, when notebook code changes or PEP 723 script metadata changes).
Up-to-date snapshots are skipped.
To force rewriting all snapshots, even when they are up-to-date:
diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.ts
index f6fa73e08e..3751c00e62 100644
--- a/frontend/src/core/cells/__tests__/session.test.ts
+++ b/frontend/src/core/cells/__tests__/session.test.ts
@@ -70,7 +70,7 @@ describe("notebookStateFromSession", () => {
cells: SessionCell[],
): api.Session["NotebookSessionV1"] => ({
version: "1",
- metadata: { marimo_version: "1" },
+ metadata: { marimo_version: "1", script_metadata_hash: null },
cells,
});
diff --git a/marimo/_cli/export/session.py b/marimo/_cli/export/session.py
index 10b995d041..a06b6f798c 100644
--- a/marimo/_cli/export/session.py
+++ b/marimo/_cli/export/session.py
@@ -4,7 +4,6 @@ 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
@@ -22,15 +21,15 @@ 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.export._session_cache import (
+ is_session_snapshot_stale,
+ serialize_session_snapshot,
+ write_session_snapshot,
+)
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._session.state.serialize import get_session_cache_file
from marimo._utils.marimo_path import MarimoPath
-from marimo._utils.paths import maybe_make_dirs
if TYPE_CHECKING:
from marimo._cli.sandbox import SandboxMode
@@ -80,9 +79,11 @@ async def _export_session_snapshot(
cli_args=cli_args,
argv=list(notebook_args),
quiet=True,
+ persist_session=False,
)
- session_snapshot = serialize_session_view(
+ session_snapshot = serialize_session_snapshot(
session_view,
+ notebook_path=marimo_path.absolute_name,
cell_ids=list(file_manager.app.cell_manager.cell_ids()),
)
return session_snapshot, did_error
@@ -109,7 +110,7 @@ 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._server.export._session_cache import serialize_session_snapshot
from marimo._utils.marimo_path import MarimoPath
payload = json.loads(sys.argv[1])
@@ -129,10 +130,12 @@ session_view, did_error = asyncio.run(
cli_args=cli_args,
argv=list(args),
quiet=True,
+ persist_session=False,
)
)
-session_snapshot = serialize_session_view(
+session_snapshot = serialize_session_snapshot(
session_view,
+ notebook_path=path.absolute_name,
cell_ids=list(file_manager.app.cell_manager.cell_ids()),
)
@@ -195,8 +198,10 @@ async def _export_session_for_notebook(
venv_python=venv_python,
)
- maybe_make_dirs(output)
- output.write_text(json.dumps(session_snapshot, indent=2), encoding="utf-8")
+ output = write_session_snapshot(
+ notebook_path=notebook.path,
+ snapshot=session_snapshot,
+ )
if did_error:
raise click.ClickException(
@@ -206,80 +211,13 @@ async def _export_session_for_notebook(
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):
+ if is_session_snapshot_stale(output, notebook):
return False
echo(
diff --git a/marimo/_schemas/generated/session.yaml b/marimo/_schemas/generated/session.yaml
index 4917b59244..2670a1e866 100644
--- a/marimo/_schemas/generated/session.yaml
+++ b/marimo/_schemas/generated/session.yaml
@@ -64,8 +64,12 @@ components:
marimo_version:
nullable: true
type: string
+ script_metadata_hash:
+ nullable: true
+ type: string
required:
- marimo_version
+ - script_metadata_hash
type: object
NotebookSessionV1:
properties:
diff --git a/marimo/_schemas/session.py b/marimo/_schemas/session.py
index afbfa32feb..6c664e2add 100644
--- a/marimo/_schemas/session.py
+++ b/marimo/_schemas/session.py
@@ -82,6 +82,7 @@ class NotebookSessionMetadata(BaseDict):
"""Metadata about the notebook"""
marimo_version: Optional[str]
+ script_metadata_hash: Optional[str]
# We don't need to store AppConfig
# since that exists in the notebook.py itself
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 60d44603cd..c5f542b48d 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -414,6 +414,7 @@ async def run_app_until_completion(
cli_args: SerializedCLIArgs,
argv: list[str] | None,
quiet: bool = False,
+ persist_session: bool = True,
) -> tuple[SessionView, bool]:
from marimo._session.consumer import SessionConsumer
from marimo._session.events import SessionEventBus
@@ -535,6 +536,25 @@ async def run_app_until_completion(
# Hack: yield to give the session view a chance to process the incoming
# console operations.
await asyncio.sleep(0.1)
+
+ if persist_session:
+ from marimo._server.export._session_cache import (
+ persist_session_view_to_cache,
+ )
+
+ try:
+ persist_session_view_to_cache(
+ view=session.session_view,
+ notebook_path=file_manager.path,
+ cell_ids=file_manager.app.cell_manager.cell_ids(),
+ )
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to persist session snapshot for %s: %s",
+ file_manager.path,
+ e,
+ )
+
# Stop distributor, terminate kernel process, etc -- all information is
# captured by the session view.
session.close()
diff --git a/marimo/_server/export/_session_cache.py b/marimo/_server/export/_session_cache.py
new file mode 100644
index 0000000000..4b74b5a35f
--- /dev/null
+++ b/marimo/_server/export/_session_cache.py
@@ -0,0 +1,150 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+from collections import Counter
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from marimo._server.file_router import AppFileRouter
+from marimo._session.state.serialize import (
+ get_session_cache_file,
+ serialize_session_view,
+)
+from marimo._utils.code import hash_code
+from marimo._utils.inline_script_metadata import (
+ script_metadata_hash_from_filename,
+)
+from marimo._utils.marimo_path import MarimoPath
+from marimo._utils.paths import maybe_make_dirs
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from marimo._schemas.session import NotebookSessionV1
+ from marimo._session.state.session_view import SessionView
+ from marimo._types.ids import CellId_t
+
+
+def get_script_metadata_hash(path: str | Path | None) -> str | None:
+ if path is None:
+ return None
+ return script_metadata_hash_from_filename(str(path))
+
+
+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 serialize_session_snapshot(
+ view: SessionView,
+ *,
+ notebook_path: str | Path | None,
+ cell_ids: Iterable[CellId_t] | None = None,
+) -> NotebookSessionV1:
+ return serialize_session_view(
+ view,
+ cell_ids=cell_ids,
+ script_metadata_hash=get_script_metadata_hash(notebook_path),
+ )
+
+
+def write_session_snapshot(
+ *,
+ notebook_path: str | Path,
+ snapshot: NotebookSessionV1,
+) -> Path:
+ output = get_session_cache_file(Path(notebook_path))
+ maybe_make_dirs(output)
+ output.write_text(json.dumps(snapshot, indent=2), encoding="utf-8")
+ return output
+
+
+def persist_session_view_to_cache(
+ *,
+ view: SessionView,
+ notebook_path: str | Path | None,
+ cell_ids: Iterable[CellId_t] | None = None,
+) -> Path | None:
+ if notebook_path is None:
+ return None
+ snapshot = serialize_session_snapshot(
+ view,
+ notebook_path=notebook_path,
+ cell_ids=cell_ids,
+ )
+ return write_session_snapshot(
+ notebook_path=notebook_path, snapshot=snapshot
+ )
+
+
+def is_session_snapshot_stale(output: Path, notebook: MarimoPath) -> bool:
+ """Return True when a saved session should be regenerated.
+
+ A snapshot is stale if it is unreadable, malformed, missing the
+ script metadata hash, or if either the current code-hash multiset or the
+ current script metadata hash differs from the snapshot.
+ """
+ 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
+ if "script_metadata_hash" not in metadata:
+ return True
+
+ session_script_hash = metadata["script_metadata_hash"]
+ if session_script_hash is not None and not isinstance(
+ session_script_hash, str
+ ):
+ return True
+ if session_script_hash != get_script_metadata_hash(notebook.absolute_name):
+ 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
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.py
index 095433a29f..44c6492452 100644
--- a/marimo/_session/extensions/extensions.py
+++ b/marimo/_session/extensions/extensions.py
@@ -132,6 +132,9 @@ class CachingExtension(SessionExtension, SessionEventListener):
event_bus.subscribe(self)
self.event_bus = event_bus
+ from marimo._utils.inline_script_metadata import (
+ script_metadata_hash_from_filename,
+ )
from marimo._version import __version__
LOGGER.debug("Syncing session view from cache")
@@ -148,7 +151,14 @@ class CachingExtension(SessionExtension, SessionEventListener):
)
cell_ids = tuple(app.cell_manager.cell_ids())
key = SessionCacheKey(
- codes=codes, marimo_version=__version__, cell_ids=cell_ids
+ codes=codes,
+ marimo_version=__version__,
+ cell_ids=cell_ids,
+ script_metadata_hash=script_metadata_hash_from_filename(
+ session.app_file_manager.path
+ )
+ if session.app_file_manager.path is not None
+ else None,
)
session.session_view = self.session_cache_manager.read_session_view(
key
diff --git a/marimo/_session/state/serialize.py b/marimo/_session/state/serialize.py
index eed0278168..d2c42e35da 100644
--- a/marimo/_session/state/serialize.py
+++ b/marimo/_session/state/serialize.py
@@ -77,7 +77,9 @@ def _normalize_error(error: Union[MarimoError, dict[str, Any]]) -> ErrorOutput:
def serialize_session_view(
- view: SessionView, cell_ids: Iterable[CellId_t] | None = None
+ view: SessionView,
+ cell_ids: Iterable[CellId_t] | None = None,
+ script_metadata_hash: str | None = None,
) -> NotebookSessionV1:
"""Convert a SessionView to a NotebookSession schema.
@@ -168,7 +170,10 @@ def serialize_session_view(
return NotebookSessionV1(
version=VERSION,
- metadata=NotebookSessionMetadata(marimo_version=__version__),
+ metadata=NotebookSessionMetadata(
+ marimo_version=__version__,
+ script_metadata_hash=script_metadata_hash,
+ ),
cells=cells,
)
@@ -364,6 +369,16 @@ def _hash_code(code: Optional[str]) -> Optional[str]:
return hash_code(code)
+def _script_metadata_hash(path: Path | str | None) -> str | None:
+ if path is None:
+ return None
+ from marimo._utils.inline_script_metadata import (
+ script_metadata_hash_from_filename,
+ )
+
+ return script_metadata_hash_from_filename(str(path))
+
+
class SessionCacheWriter(AsyncBackgroundTask):
"""Periodically writes a SessionView to a file."""
@@ -372,9 +387,11 @@ class SessionCacheWriter(AsyncBackgroundTask):
session_view: SessionView,
path: Path,
interval: float,
+ notebook_path: Path | None = None,
) -> None:
super().__init__()
self.session_view = session_view
+ self.notebook_path = notebook_path
# Windows does not support our async path implementation
self.path: AsyncPath | Path = path
if os.name != "nt":
@@ -398,7 +415,12 @@ class SessionCacheWriter(AsyncBackgroundTask):
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)
+ data = serialize_session_view(
+ self.session_view,
+ script_metadata_hash=_script_metadata_hash(
+ self.notebook_path
+ ),
+ )
if isinstance(self.path, AsyncPath):
await self.path.write_text(json.dumps(data, indent=2))
else:
@@ -417,6 +439,7 @@ class SessionCacheKey:
codes: tuple[str | None, ...]
marimo_version: str
cell_ids: tuple[CellId_t, ...]
+ script_metadata_hash: str | None = None
class SessionCacheManager:
@@ -441,12 +464,14 @@ class SessionCacheManager:
if self.path is None:
return
- cache_file = get_session_cache_file(Path(self.path))
+ notebook_path = Path(self.path)
+ cache_file = get_session_cache_file(notebook_path)
self.session_cache_writer = SessionCacheWriter(
session_view=self.session_view,
path=cache_file,
interval=self.interval,
+ notebook_path=notebook_path,
)
self.session_cache_writer.start()
@@ -467,15 +492,19 @@ class SessionCacheManager:
def is_cache_hit(
self, notebook_session: NotebookSessionV1, key: SessionCacheKey
) -> bool:
+ metadata = notebook_session.get("metadata")
+ if not isinstance(metadata, dict):
+ return False
if (len(key.codes) != len(notebook_session["cells"])) or any(
_hash_code(code) != cell["code_hash"]
for code, cell in zip(key.codes, notebook_session["cells"])
):
return False
- if (
- key.marimo_version
- != notebook_session["metadata"]["marimo_version"]
- ):
+ if key.marimo_version != metadata.get("marimo_version"):
+ return False
+ if "script_metadata_hash" not in metadata:
+ return False
+ if metadata.get("script_metadata_hash") != key.script_metadata_hash:
return False
return True
diff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.py
index 78bf3d8b51..90be5414dd 100644
--- a/marimo/_utils/inline_script_metadata.py
+++ b/marimo/_utils/inline_script_metadata.py
@@ -1,12 +1,14 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import json
import re
from pathlib import Path
from typing import Any, cast
from marimo import _loggers
from marimo._cli.files.file_path import FileContentReader
+from marimo._utils.code import hash_code
from marimo._utils.paths import normalize_path
from marimo._utils.scripts import read_pyproject_from_script
@@ -247,3 +249,16 @@ def has_marimo_in_script_metadata(filepath: str) -> bool | None:
dependencies = project.get("dependencies", [])
return any(is_marimo_dependency(dep) for dep in dependencies)
+
+
+def script_metadata_hash_from_filename(name: str) -> str | None:
+ project = _get_pyproject_from_filename(name)
+ if project is None:
+ return None
+ serialized = json.dumps(
+ project,
+ sort_keys=True,
+ separators=(",", ":"),
+ ensure_ascii=False,
+ )
+ return hash_code(serialized)
diff --git a/packages/openapi/src/session.ts b/packages/openapi/src/session.ts
index f4fb701de1..5163351569 100644
--- a/packages/openapi/src/session.ts
+++ b/packages/openapi/src/session.ts
@@ -35,6 +35,7 @@ export interface components {
};
NotebookSessionMetadata: {
marimo_version: string | null;
+ script_metadata_hash: string | null;
};
NotebookSessionV1: {
cells: components["schemas"]["Cell"][];
diff --git a/tests/_cli/test_cli_export_session.py b/tests/_cli/test_cli_export_session.py
index df282475bc..02007d3881 100644
--- a/tests/_cli/test_cli_export_session.py
+++ b/tests/_cli/test_cli_export_session.py
@@ -1,7 +1,6 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-import json
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, patch
@@ -13,7 +12,6 @@ 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
@@ -83,7 +81,7 @@ def test_session_sandbox_single_skips_before_sandbox_when_fresh(
),
patch.object(
session_module,
- "_is_session_snapshot_stale",
+ "is_session_snapshot_stale",
return_value=False,
) as is_stale,
patch("marimo._cli.sandbox.run_in_sandbox") as run_in_sandbox,
@@ -272,192 +270,3 @@ def test_export_session_snapshot_subprocess_invalid_json() -> None:
"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)
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index d7c9be1ef4..27cde8fecf 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -25,6 +25,7 @@ from marimo._server.export import (
from marimo._server.export.exporter import Exporter
from marimo._server.models.export import ExportAsHTMLRequest
from marimo._session.notebook import AppFileManager
+from marimo._session.state.serialize import get_session_cache_file
from marimo._session.state.session_view import SessionView
from marimo._utils.marimo_path import MarimoPath
from tests.mocks import delete_lines_with_files, snapshotter
@@ -107,6 +108,40 @@ async def test_run_until_completion_with_stop() -> None:
)
+async def test_run_until_completion_persists_session_snapshot(
+ tmp_path: Path,
+) -> None:
+ notebook = tmp_path / "notebook.py"
+ notebook.write_text(
+ """
+import marimo
+
+app = marimo.App()
+
+def _():
+ return
+
+if __name__ == "__main__":
+ app.run()
+""",
+ encoding="utf-8",
+ )
+ file_manager = AppFileManager(str(notebook))
+
+ _, did_error = await run_app_until_completion(
+ file_manager,
+ cli_args={},
+ argv=None,
+ )
+ assert did_error is False
+
+ session_file = get_session_cache_file(notebook)
+ assert session_file.exists()
+ data = json.loads(session_file.read_text(encoding="utf-8"))
+ assert "script_metadata_hash" in data["metadata"]
+
+
@pytest.mark.skipif(
sys.version_info >= (3, 13), reason="3.13 has different stack trace format"
)
diff --git a/tests/_server/export/test_session_cache.py b/tests/_server/export/test_session_cache.py
new file mode 100644
index 0000000000..739ef16d1b
--- /dev/null
+++ b/tests/_server/export/test_session_cache.py
@@ -0,0 +1,277 @@
+from __future__ import annotations
+
+import json
+from typing import Any, cast
+from unittest.mock import patch
+
+from marimo._server.export import _session_cache
+from marimo._session.state.session_view import SessionView
+from marimo._utils.marimo_path import MarimoPath
+from marimo._version import __version__
+
+
+def _write_snapshot(path: str, payload: dict[str, object]) -> None:
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(json.dumps(payload))
+
+
+def _make_snapshot(
+ *,
+ code_hashes: list[str | None],
+ script_metadata_hash: str | None = "meta-hash",
+) -> dict[str, object]:
+ metadata: dict[str, str | None] = {"marimo_version": __version__}
+ if script_metadata_hash is not None:
+ metadata["script_metadata_hash"] = script_metadata_hash
+ return {
+ "version": "1",
+ "metadata": metadata,
+ "cells": [
+ {"code_hash": code_hash, "outputs": []}
+ for code_hash in code_hashes
+ ],
+ }
+
+
+def test_is_session_snapshot_stale_false_when_snapshot_is_current(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(code_hashes=["hash-b", "hash-a", None, "hash-a"])
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a", None, "hash-a", "hash-b"),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ),
+ ):
+ assert (
+ _session_cache.is_session_snapshot_stale(output, notebook) is False
+ )
+
+
+def test_is_session_snapshot_stale_true_when_script_metadata_hash_missing(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(
+ code_hashes=["hash-a"],
+ script_metadata_hash=None,
+ )
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a",),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value=None,
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_script_metadata_hash_mismatch(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(
+ code_hashes=["hash-a"],
+ script_metadata_hash="old",
+ )
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a",),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="new",
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_code_hashes_do_not_match(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(code_hashes=["hash-a", "hash-b"])
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a",),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_hash_multiplicity_differs(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(code_hashes=["hash-a"])
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a", "hash-a"),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_cell_missing_code_hash(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(code_hashes=["hash-a"])
+ snapshot["cells"] = [{"outputs": []}]
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a",),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_code_hash_has_wrong_type(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(code_hashes=["hash-a"])
+ snapshot["cells"] = [{"code_hash": 1, "outputs": []}]
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ return_value=("hash-a",),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_snapshot_is_unreadable(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ output.write_text("{ not valid json", encoding="utf-8")
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_is_session_snapshot_stale_true_when_hash_lookup_fails(
+ tmp_path,
+) -> None:
+ output = tmp_path / "session.json"
+ snapshot = _make_snapshot(code_hashes=["hash-a"])
+ _write_snapshot(str(output), snapshot)
+ notebook = MarimoPath(str(tmp_path / "notebook.py"))
+
+ with (
+ patch.object(
+ _session_cache,
+ "current_notebook_code_hashes",
+ side_effect=RuntimeError("failed to inspect notebook"),
+ ),
+ patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ),
+ ):
+ assert _session_cache.is_session_snapshot_stale(output, notebook)
+
+
+def test_serialize_session_snapshot_includes_script_metadata_hash() -> None:
+ view = SessionView()
+ with patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ):
+ snapshot = _session_cache.serialize_session_snapshot(
+ view,
+ notebook_path="notebook.py",
+ cell_ids=(),
+ )
+
+ metadata = snapshot["metadata"]
+ assert metadata["script_metadata_hash"] == "meta-hash"
+
+
+def test_persist_session_view_to_cache_writes_under_marimo_dir(
+ tmp_path,
+) -> None:
+ notebook = tmp_path / "notebook.py"
+ notebook.write_text("import marimo\n", encoding="utf-8")
+
+ view = SessionView()
+ with patch.object(
+ _session_cache,
+ "get_script_metadata_hash",
+ return_value="meta-hash",
+ ):
+ output = _session_cache.persist_session_view_to_cache(
+ view=view,
+ notebook_path=notebook,
+ cell_ids=(),
+ )
+
+ assert output is not None
+ assert output == tmp_path / "__marimo__" / "session" / "notebook.py.json"
+ data = cast(dict[str, Any], json.loads(output.read_text(encoding="utf-8")))
+ assert data["metadata"]["script_metadata_hash"] == "meta-hash"
diff --git a/tests/_session/state/snapshots/basic_session.json b/tests/_session/state/snapshots/basic_session.json
index d781fc00d1..19d5739034 100644
--- a/tests/_session/state/snapshots/basic_session.json
+++ b/tests/_session/state/snapshots/basic_session.json
@@ -1,7 +1,8 @@
{
"version": "1",
"metadata": {
- "marimo_version": "0.0.0"
+ "marimo_version": "0.0.0",
+ "script_metadata_hash": null
},
"cells": [
{
diff --git a/tests/_session/state/snapshots/console_session.json b/tests/_session/state/snapshots/console_session.json
index 465bf47294..0e54cfa179 100644
--- a/tests/_session/state/snapshots/console_session.json
+++ b/tests/_session/state/snapshots/console_session.json
@@ -1,7 +1,8 @@
{
"version": "1",
"metadata": {
- "marimo_version": "0.0.0"
+ "marimo_version": "0.0.0",
+ "script_metadata_hash": null
},
"cells": [
{
diff --git a/tests/_session/state/snapshots/error_session.json b/tests/_session/state/snapshots/error_session.json
index 92edcb03ab..2c05bfe707 100644
--- a/tests/_session/state/snapshots/error_session.json
+++ b/tests/_session/state/snapshots/error_session.json
@@ -1,7 +1,8 @@
{
"version": "1",
"metadata": {
- "marimo_version": "0.0.0"
+ "marimo_version": "0.0.0",
+ "script_metadata_hash": null
},
"cells": [
{
diff --git a/tests/_session/state/snapshots/mime_bundle_session.json b/tests/_session/state/snapshots/mime_bundle_session.json
index e9cd3445bd..7420a993ab 100644
--- a/tests/_session/state/snapshots/mime_bundle_session.json
+++ b/tests/_session/state/snapshots/mime_bundle_session.json
@@ -1,7 +1,8 @@
{
"version": "1",
"metadata": {
- "marimo_version": "0.0.0"
+ "marimo_version": "0.0.0",
+ "script_metadata_hash": null
},
"cells": [
{
diff --git a/tests/_session/state/snapshots/mixed_error_session.json b/tests/_session/state/snapshots/mixed_error_session.json
index 500eae5ad5..711dcc6edd 100644
--- a/tests/_session/state/snapshots/mixed_error_session.json
+++ b/tests/_session/state/snapshots/mixed_error_session.json
@@ -1,7 +1,8 @@
{
"version": "1",
"metadata": {
- "marimo_version": "0.0.0"
+ "marimo_version": "0.0.0",
+ "script_metadata_hash": null
},
"cells": [
{
diff --git a/tests/_session/state/test_serialize_session.py b/tests/_session/state/test_serialize_session.py
index dbac17d9f2..3d81128625 100644
--- a/tests/_session/state/test_serialize_session.py
+++ b/tests/_session/state/test_serialize_session.py
@@ -1004,6 +1004,37 @@ class TestSessionCacheManager:
)
assert not loaded_view.cell_notifications
+ async def test_read_session_view_cache_miss_script_metadata_hash(
+ self, session_view: SessionView
+ ):
+ """Test reading session view from cache file."""
+ view = session_view
+ view.add_control_request(
+ ExecuteCellsCommand(cell_ids=["1", "2"], codes=["a", "b"])
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "notebook.py"
+ cache_file = get_session_cache_file(path)
+ cache_file.parent.mkdir(parents=True)
+
+ data = serialize_session_view(view, script_metadata_hash="old")
+ cache_file.write_text(json.dumps(data))
+
+ manager = SessionCacheManager(SessionView(), path, 0.1)
+ loaded_view = manager.read_session_view(
+ SessionCacheKey(
+ codes=(
+ "a",
+ "b",
+ ),
+ marimo_version=__version__,
+ cell_ids=("1", "2"),
+ script_metadata_hash="new",
+ )
+ )
+ assert not loaded_view.cell_notifications
+
async def test_read_session_view_cache_hit(
self, session_view: SessionView
):
diff --git a/tests/_utils/test_inline_script_metadata.py b/tests/_utils/test_inline_script_metadata.py
index e6191dd563..eb6c6eff7b 100644
--- a/tests/_utils/test_inline_script_metadata.py
+++ b/tests/_utils/test_inline_script_metadata.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
import pytest
from marimo._utils.inline_script_metadata import (
@@ -7,10 +9,14 @@ from marimo._utils.inline_script_metadata import (
_pyproject_toml_to_requirements_txt,
has_marimo_in_script_metadata,
is_marimo_dependency,
+ script_metadata_hash_from_filename,
)
from marimo._utils.platform import is_windows
from marimo._utils.scripts import read_pyproject_from_script
+if TYPE_CHECKING:
+ from pathlib import Path
+
def test_get_dependencies():
SCRIPT = """
@@ -361,3 +367,68 @@ def test_has_marimo_in_script_metadata(tmp_path):
# None: non-.py file
assert has_marimo_in_script_metadata(str(tmp_path / "test.md")) is None
+
+
+def test_script_metadata_hash_from_filename_none_without_metadata(
+ tmp_path: Path,
+) -> None:
+ notebook = tmp_path / "no_metadata.py"
+ notebook.write_text("import marimo\n", encoding="utf-8")
+ assert script_metadata_hash_from_filename(str(notebook)) is None
+
+
+def test_script_metadata_hash_from_filename_ignores_formatting(
+ tmp_path: Path,
+) -> None:
+ first = tmp_path / "first.py"
+ first.write_text(
+ """
+# /// script
+# dependencies = [
+# "numpy",
+# "marimo>=0.20.0",
+# ]
+# requires-python = ">=3.11"
+# ///
+""",
+ encoding="utf-8",
+ )
+ second = tmp_path / "second.py"
+ second.write_text(
+ """
+# /// script
+# requires-python = ">=3.11"
+# dependencies = ["numpy", "marimo>=0.20.0"]
+# ///
+""",
+ encoding="utf-8",
+ )
+ assert script_metadata_hash_from_filename(
+ str(first)
+ ) == script_metadata_hash_from_filename(str(second))
+
+
+def test_script_metadata_hash_from_filename_changes_with_dependencies(
+ tmp_path: Path,
+) -> None:
+ first = tmp_path / "first.py"
+ first.write_text(
+ """
+# /// script
+# dependencies = ["numpy"]
+# ///
+""",
+ encoding="utf-8",
+ )
+ second = tmp_path / "second.py"
+ second.write_text(
+ """
+# /// script
+# dependencies = ["pandas"]
+# ///
+""",
+ encoding="utf-8",
+ )
+ assert script_metadata_hash_from_filename(
+ str(first)
+ ) != script_metadata_hash_from_filename(str(second))