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(export): bundle session caches into html-wasm --execute output (#9897)

Dylan Madisetti503b7f433ca1
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index f40d03bd52..e5f122e51a 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -1004,6 +1004,7 @@ def html_wasm(
show_code=show_code,
cli_args=cli_args,
argv=list(args),
+ cache_export_dir=out_dir,
)
)
@@ -1042,9 +1043,9 @@ def html_wasm(
create_cloudflare_files(parse_title(name), out_dir)
outfile = out_dir / filename
- return watch_and_export(
- MarimoPath(name), outfile, watch, export_callback, force
- )
+ # NB. with --execute, the callback also bundles session caches into the
+ # export's public/cache/.
+ watch_and_export(MarimoPath(name), outfile, watch, export_callback, force)
export.add_command(html)
diff --git a/marimo/_runtime/callbacks/__init__.py b/marimo/_runtime/callbacks/__init__.py
index d8c14b9c32..2f2d270db5 100644
--- a/marimo/_runtime/callbacks/__init__.py
+++ b/marimo/_runtime/callbacks/__init__.py
@@ -1,7 +1,10 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-from marimo._runtime.callbacks.cache import CacheCallbacks
+from marimo._runtime.callbacks.cache import (
+ CacheCallbacks,
+ cache_cells_enabled,
+)
from marimo._runtime.callbacks.datasets import DatasetCallbacks
from marimo._runtime.callbacks.external_storage import (
ExternalStorageCallbacks,
@@ -23,4 +26,5 @@ __all__ = [
"SecretsCallbacks",
"SqlCallbacks",
"SupportsTeardown",
+ "cache_cells_enabled",
]
diff --git a/marimo/_runtime/callbacks/cache.py b/marimo/_runtime/callbacks/cache.py
index 3037082a6a..29591a84e5 100644
--- a/marimo/_runtime/callbacks/cache.py
+++ b/marimo/_runtime/callbacks/cache.py
@@ -1,7 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from marimo._messaging.notification import (
CacheClearedNotification,
@@ -11,24 +11,51 @@ from marimo._messaging.notification_utils import broadcast_notification
from marimo._runtime.commands import ClearCacheCommand, GetCacheInfoCommand
if TYPE_CHECKING:
+ from collections.abc import Callable, Mapping
+ from typing import Any
+
+ from marimo._config.config import MarimoConfig
from marimo._runtime.callbacks.protocol import GlobalsView
from marimo._runtime.request_router import RequestRouter
+def cache_cells_enabled(user_config: MarimoConfig) -> bool:
+ """Whether `[tool.marimo.runtime] cache_cells` is on (default `False`)."""
+ runtime = cast("Mapping[str, Any]", user_config.get("runtime", {}))
+ return bool(runtime.get("cache_cells", False))
+
+
class CacheCallbacks:
- def __init__(self, scope: GlobalsView):
+ def __init__(
+ self,
+ scope: GlobalsView,
+ *,
+ caching_enabled: Callable[[], bool] | None = None,
+ notebook_filename: str | None = None,
+ ) -> None:
self._scope = scope
+ # NB. read live at teardown — the config can change mid-session.
+ self._caching_enabled = caching_enabled or (lambda: False)
+ self._notebook_filename = notebook_filename
def register(self, router: RequestRouter) -> None:
router.register(ClearCacheCommand, self.clear_cache)
router.register(GetCacheInfoCommand, self.get_cache_info)
def teardown(self) -> None:
- """Flush pending cache writes so blobs are durable before teardown."""
- from marimo._save.loaders import flush_active_caches
+ """Flush pending cache writes; publish an export manifest if caching."""
+ from marimo._save.loaders import (
+ dump_cache_manifests,
+ flush_active_caches,
+ )
+ from marimo._save.stores.file import export_manifest_name
- # NB. loaders dispatch blob writes to background threads; join them.
+ # NB. flush unconditionally (durability); joins background blob writes.
flush_active_caches()
+ # NB. manifest only when cell caching is on (html-wasm --execute), else
+ # a normal session would litter cache dirs with manifests.
+ if self._caching_enabled():
+ dump_cache_manifests(export_manifest_name(self._notebook_filename))
async def clear_cache(self, request: ClearCacheCommand) -> None:
del request
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index c5a9535223..b03a535213 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -97,6 +97,7 @@ from marimo._runtime.callbacks import (
SecretsCallbacks,
SqlCallbacks,
SupportsTeardown,
+ cache_cells_enabled,
)
from marimo._runtime.commands import (
AppMetadata,
@@ -491,7 +492,11 @@ class Kernel:
self.datasets_callbacks = DatasetCallbacks(self)
self.packages_callbacks = PackagesCallbacks(self)
self.sql_callbacks = SqlCallbacks(self)
- self.cache_callbacks = CacheCallbacks(self)
+ self.cache_callbacks = CacheCallbacks(
+ self,
+ caching_enabled=lambda: cache_cells_enabled(self.user_config),
+ notebook_filename=app_metadata.filename,
+ )
self.external_storage_callbacks = ExternalStorageCallbacks(self)
self._callbacks: list[KernelCallback] = [
self.secrets_callbacks,
diff --git a/marimo/_save/loaders/__init__.py b/marimo/_save/loaders/__init__.py
index 2e2de7af7a..445bc0eeb3 100644
--- a/marimo/_save/loaders/__init__.py
+++ b/marimo/_save/loaders/__init__.py
@@ -8,6 +8,7 @@ from marimo._save.loaders.json import JsonLoader
from marimo._save.loaders.lazy import (
LazyLoader,
WasmLazyLoader,
+ dump_cache_manifests,
flush_active_caches,
)
from marimo._save.loaders.loader import (
@@ -63,6 +64,7 @@ __all__ = [
"MemoryLoader",
"PickleLoader",
"WasmLazyLoader",
+ "dump_cache_manifests",
"flush_active_caches",
"resolve_loader",
]
diff --git a/marimo/_save/loaders/lazy.py b/marimo/_save/loaders/lazy.py
index 48fbdd1163..24ede1ef40 100644
--- a/marimo/_save/loaders/lazy.py
+++ b/marimo/_save/loaders/lazy.py
@@ -250,6 +250,47 @@ def flush_active_caches() -> None:
LazyLoader.flush_all()
+def dump_cache_manifests(manifest_name: str) -> None:
+ """Write this session's produced keys into each file-backed cache dir.
+
+ An out-of-process exporter (`html-wasm --execute`) reads `manifest_name` to
+ discover what to bundle. In-memory stores (the WASM `DictStore`) are skipped
+ — nothing on disk. The loop only matters for multi-cache-block notebooks.
+ """
+ loaders = LazyLoader.active_loaders()
+ keys = LazyLoader.export_keys()
+ seen: set[Path] = set()
+ for loader in loaders:
+ store = loader.store
+ inner = store._inner if isinstance(store, LazyStore) else None
+ if not isinstance(inner, FileStore):
+ continue
+ cache_dir = inner.save_path
+ if cache_dir in seen:
+ continue
+ seen.add(cache_dir)
+ _write_export_manifest(cache_dir, manifest_name, keys)
+
+
+def _write_export_manifest(
+ cache_dir: Path, manifest_name: str, keys: list[str]
+) -> None:
+ """Atomically (re)write the export manifest in `cache_dir`."""
+ import json
+ import os
+
+ # NB. temp file + os.replace so a reader never sees a half-written
+ # manifest, and a mid-write kill leaves the previous one intact.
+
+ try:
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ tmp = cache_dir / f"{manifest_name}.{os.getpid()}.tmp"
+ tmp.write_text(json.dumps(keys))
+ os.replace(tmp, cache_dir / manifest_name)
+ except OSError as e:
+ LOGGER.warning("Failed to write cache export manifest: %s", e)
+
+
class LazyStore(Store):
"""Native store for `LazyLoader`.
@@ -425,6 +466,20 @@ class LazyLoader(BasePersistenceLoader):
for loader in cls.active_loaders():
loader.flush()
+ @classmethod
+ def export_keys(cls) -> list[str]:
+ """Keys this session produced, merged across every active loader.
+
+ Flush first if the result must reflect pending background writes.
+ """
+ return sorted(
+ {
+ key
+ for loader in cls.active_loaders()
+ for key in loader.store.export_keys()
+ }
+ )
+
@classmethod
def active_loaders(cls) -> list[LazyLoader]:
"""Loaders the current session has created (for flush/export)."""
diff --git a/marimo/_save/stores/file.py b/marimo/_save/stores/file.py
index a567c480ed..5aeb2cc4e5 100644
--- a/marimo/_save/stores/file.py
+++ b/marimo/_save/stores/file.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import re
from pathlib import Path
from marimo._runtime.runtime import notebook_dir
@@ -8,6 +9,18 @@ from marimo._save.stores.store import Store
from marimo._utils.paths import notebook_output_dir
+def export_manifest_name(notebook_filename: str | None) -> str:
+ """Export-manifest filename for a notebook, from its filename stem.
+
+ Kernel and exporter derive it identically so they agree on the file. A
+ dotfile so it can't collide with a cache key. NB. only the stem is used, so
+ two same-named notebooks writing to a shared cache dir would collide.
+ """
+ stem = Path(notebook_filename).stem if notebook_filename else "notebook"
+ slug = re.sub(r"[^0-9A-Za-z._-]+", "-", stem).strip("-") or "notebook"
+ return f".{slug}-export.json"
+
+
def _valid_path(path: Path) -> bool:
return path.exists() and path.stat().st_size > 0
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 7e860ebbd8..9d7c7111a8 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -6,7 +6,8 @@ import os
import sys
from dataclasses import dataclass, replace
from functools import cached_property
-from typing import TYPE_CHECKING, Literal, cast
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Literal, cast
from marimo import _loggers
from marimo._ast.app import InternalApp
@@ -32,7 +33,10 @@ from marimo._messaging.notification import (
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
from marimo._output.hypertext import patch_html_for_non_interactive_output
-from marimo._runtime.commands import AppMetadata, SerializedCLIArgs
+from marimo._runtime.commands import (
+ AppMetadata,
+ SerializedCLIArgs,
+)
from marimo._runtime.patches import extract_docstring_from_header
from marimo._schemas.serialization import NotebookSerialization
from marimo._server.export._status import emit_pdf_export_status
@@ -370,6 +374,67 @@ async def run_app_then_export_as_html(
)
+def bundle_cache_export(notebook_path: MarimoPath, out_dir: Path) -> None:
+ """Copy an executed session's cached blobs into `<out_dir>/public/cache/`.
+
+ Reads the per-notebook export manifest the kernel wrote next to the blobs,
+ and copies exactly those entries — where the browser store fetches them.
+ No manifest (caching off, no caches, or a kernel killed before it flushed)
+ means nothing to bundle: the export still works, the browser recomputes.
+ """
+ import json
+ import shutil
+ from pathlib import PurePosixPath
+
+ manifest_file = _cache_export_manifest_path(notebook_path)
+ cache_src = manifest_file.parent
+ if not manifest_file.exists():
+ echo("No caches to bundle.")
+ return
+ try:
+ keys: list[str] = json.loads(manifest_file.read_text())
+ except (OSError, ValueError) as e:
+ LOGGER.warning("Failed to read cache export manifest: %s", e)
+ return
+
+ cache_dst = out_dir / "public" / "cache"
+ copied = 0
+ for key in keys:
+ if not isinstance(key, str):
+ LOGGER.warning("Skipping non-string cache manifest key: %r", key)
+ continue
+ # A stale/tampered manifest key could otherwise escape the cache dir.
+ rel = PurePosixPath(key)
+ if rel.is_absolute() or ".." in rel.parts:
+ LOGGER.warning("Skipping unsafe cache manifest key: %r", key)
+ continue
+ src_file = cache_src / key
+ if not src_file.is_file():
+ continue
+ try:
+ dst_file = cache_dst / key
+ dst_file.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src_file, dst_file)
+ copied += 1
+ except OSError as e:
+ LOGGER.warning("Failed to bundle cache file %s: %s", key, e)
+ echo(f"Bundled {copied} cache files into {cache_dst}.")
+
+
+def _cache_export_manifest_path(notebook_path: MarimoPath) -> Path:
+ """Path of the export manifest for `notebook_path`.
+
+ Derived identically to the executing kernel's (see `export_manifest_name`)
+ so the exporter reads exactly the file the run wrote.
+ """
+ from marimo._save.stores.file import export_manifest_name
+ from marimo._utils.paths import notebook_output_dir
+
+ absolute = notebook_path.absolute_name
+ cache_dir = notebook_output_dir(Path(absolute).parent) / "cache"
+ return cache_dir / export_manifest_name(absolute)
+
+
async def run_app_then_export_as_wasm(
path: MarimoPath,
mode: Literal["edit", "run"],
@@ -378,8 +443,14 @@ async def run_app_then_export_as_wasm(
argv: list[str],
*,
asset_url: str | None = None,
+ cache_export_dir: Path | None = None,
) -> ExportResult:
- """Execute notebook and export as WASM HTML with embedded session."""
+ """Execute notebook and export as WASM HTML with embedded session.
+
+ When `cache_export_dir` is set, the caches this run produced are bundled
+ into `<cache_export_dir>/public/cache/` so the exported notebook ships
+ them and skips recomputation in the browser.
+ """
from marimo._session.state.serialize import (
serialize_notebook,
serialize_session_view,
@@ -392,11 +463,31 @@ async def run_app_then_export_as_wasm(
resolved = config.get_config()
display_config = resolved["display"]
+ from marimo._runtime.callbacks.cache import cache_cells_enabled
+
+ # Caching is opt-in: bundle caches only when the notebook enables
+ # `cache_cells`. Otherwise export runs fully live, so no cell's output
+ # (console included) is served from a warm cache and skips execution.
+ cache_dir = (
+ cache_export_dir
+ if cache_export_dir is not None and cache_cells_enabled(resolved)
+ else None
+ )
+
+ if cache_dir is not None:
+ # NB. drop a prior run's manifest so we never bundle a stale key set.
+ _cache_export_manifest_path(path).unlink(missing_ok=True)
+
session_view, did_error = await run_app_until_completion(
file_manager,
cli_args,
argv=argv,
+ cache_export=cache_dir is not None,
)
+ if cache_dir is not None:
+ # NB. the run joined the kernel, which wrote the manifest on shutdown,
+ # so it's on disk to read now.
+ bundle_cache_export(path, cache_dir)
session_snapshot = serialize_session_view(
session_view,
@@ -494,6 +585,7 @@ async def run_app_until_completion(
argv: list[str] | None,
quiet: bool = False,
persist_session: bool = True,
+ cache_export: bool = False,
) -> tuple[SessionView, bool]:
from marimo._session.consumer import SessionConsumer
from marimo._session.events import SessionEventBus
@@ -558,22 +650,21 @@ async def run_app_until_completion(
def connection_state(self) -> ConnectionState:
return ConnectionState.OPEN
+ runtime_overrides: dict[str, Any] = {
+ "on_cell_change": "autorun",
+ "auto_instantiate": True,
+ "auto_reload": "off",
+ "watcher_on_save": "lazy",
+ }
+ if cache_export:
+ # Cache every executed cell so the export can bundle the results;
+ # this same flag gates the kernel's export-manifest dump on teardown.
+ runtime_overrides["cache_cells"] = True
config_manager = get_default_config_manager(
current_path=file_manager.path
).with_overrides(
- {
- "runtime": cast(
- RuntimeConfig,
- {
- "on_cell_change": "autorun",
- "auto_instantiate": True,
- "auto_reload": "off",
- "watcher_on_save": "lazy",
- # We cast because we don't want to override the other
- # config values
- },
- ),
- }
+ # We cast because we don't want to override the other config values.
+ {"runtime": cast(RuntimeConfig, runtime_overrides)}
)
# Create a session
diff --git a/marimo/_session/managers/kernel.py b/marimo/_session/managers/kernel.py
index 7da4397c3f..b00e272a4e 100644
--- a/marimo/_session/managers/kernel.py
+++ b/marimo/_session/managers/kernel.py
@@ -256,11 +256,15 @@ class KernelManagerImpl(KernelManager):
)
return
- # Otherwise, we have something that is `ProcessLike`
- if self.profile_path is not None and self.kernel_task.is_alive():
+ # Otherwise, we have something that is `ProcessLike`.
+ # Request a clean shutdown first so the kernel can flush pending
+ # work (e.g. LazyLoader cache writes) before we kill it.
+ if self.kernel_task.is_alive():
self.queue_manager.put_control_request(
commands.StopKernelCommand()
)
+
+ if self.profile_path is not None and self.kernel_task.is_alive():
# Hack: Wait for kernel to exit and write out profile;
# joining the process hangs, but not sure why.
print_(
@@ -273,6 +277,9 @@ class KernelManagerImpl(KernelManager):
time.sleep(1)
self.queue_manager.close_queues()
+ # Give the kernel time for a clean shutdown (flush caches, etc.)
+ if self.kernel_task.is_alive():
+ self.kernel_task.join(timeout=5)
try:
try_kill_process_and_group(self.kernel_task)
except ProcessLookupError:
diff --git a/tests/_cli/test_export_cache_bundle.py b/tests/_cli/test_export_cache_bundle.py
new file mode 100644
index 0000000000..da13e2be28
--- /dev/null
+++ b/tests/_cli/test_export_cache_bundle.py
@@ -0,0 +1,149 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""`bundle_cache_export` — bundling an executed export's caches.
+
+When cell caching is enabled, the executed kernel flushes its caches on
+shutdown and writes a per-notebook export manifest next to the blobs in
+`__marimo__/cache/`; the export reads that manifest and copies exactly those
+files into `<out_dir>/public/cache/`. These tests exercise the copy against a
+synthetic `__marimo__/cache` tree; no kernel run required.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING
+
+from marimo._save.stores.file import export_manifest_name
+from marimo._server.export import bundle_cache_export
+from marimo._utils.marimo_path import MarimoPath
+from marimo._utils.paths import notebook_output_dir
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+
+def _notebook(tmp_path: Path) -> MarimoPath:
+ nb = tmp_path / "nb.py"
+ nb.write_text("import marimo\napp = marimo.App()\n")
+ return MarimoPath(str(nb))
+
+
+def _cache_dir(tmp_path: Path) -> Path:
+ cache = notebook_output_dir(tmp_path) / "cache"
+ cache.mkdir(parents=True)
+ return cache
+
+
+def _write_manifest(
+ cache: Path, notebook: MarimoPath, keys: list[str]
+) -> None:
+ name = export_manifest_name(notebook.absolute_name)
+ (cache / name).write_text(json.dumps(keys))
+
+
+def test_no_manifest_is_a_noop(tmp_path: Path) -> None:
+ _cache_dir(tmp_path) # cache dir exists, but no manifest was written
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(_notebook(tmp_path), out_dir)
+ assert not (out_dir / "public" / "cache").exists()
+
+
+def test_keys_copied(tmp_path: Path) -> None:
+ cache = _cache_dir(tmp_path)
+ nb = _notebook(tmp_path)
+ (cache / "lazy").mkdir()
+ (cache / "lazy" / "E_abc.jsonl").write_bytes(b"manifest-line\n")
+ (cache / "lazy" / "blob.npy").write_bytes(b"\x93NUMPY")
+ _write_manifest(cache, nb, ["lazy/E_abc.jsonl", "lazy/blob.npy"])
+
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(nb, out_dir)
+
+ dst = out_dir / "public" / "cache"
+ assert (dst / "lazy" / "E_abc.jsonl").read_bytes() == b"manifest-line\n"
+ assert (dst / "lazy" / "blob.npy").read_bytes() == b"\x93NUMPY"
+
+
+def test_missing_listed_file_skipped(tmp_path: Path) -> None:
+ cache = _cache_dir(tmp_path)
+ nb = _notebook(tmp_path)
+ (cache / "present.bin").write_bytes(b"ok")
+ _write_manifest(cache, nb, ["present.bin", "evicted.bin"])
+
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(nb, out_dir)
+
+ dst = out_dir / "public" / "cache"
+ assert (dst / "present.bin").exists()
+ assert not (dst / "evicted.bin").exists()
+
+
+def test_keys_outside_session_not_bundled(tmp_path: Path) -> None:
+ """Only manifest-listed keys ship — other cache files on disk stay."""
+ cache = _cache_dir(tmp_path)
+ nb = _notebook(tmp_path)
+ (cache / "mine.bin").write_bytes(b"mine")
+ (cache / "other.bin").write_bytes(b"other-session")
+ _write_manifest(cache, nb, ["mine.bin"])
+
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(nb, out_dir)
+
+ dst = out_dir / "public" / "cache"
+ assert (dst / "mine.bin").exists()
+ assert not (dst / "other.bin").exists()
+
+
+def test_corrupt_manifest_is_a_noop(tmp_path: Path) -> None:
+ cache = _cache_dir(tmp_path)
+ nb = _notebook(tmp_path)
+ (cache / "mine.bin").write_bytes(b"mine")
+ name = export_manifest_name(nb.absolute_name)
+ (cache / name).write_text("not json{")
+
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(nb, out_dir)
+
+ assert not (out_dir / "public" / "cache").exists()
+
+
+def test_non_string_key_skipped(tmp_path: Path) -> None:
+ """A non-string manifest key is skipped, not fatal to the whole bundle."""
+ cache = _cache_dir(tmp_path)
+ nb = _notebook(tmp_path)
+ (cache / "ok.bin").write_bytes(b"ok")
+ name = export_manifest_name(nb.absolute_name)
+ # Hand-write the manifest: a stale/tampered file may hold non-string keys.
+ (cache / name).write_text(json.dumps([123, "ok.bin"]))
+
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(nb, out_dir)
+
+ dst = out_dir / "public" / "cache"
+ assert (dst / "ok.bin").read_bytes() == b"ok"
+ assert list(dst.rglob("*")) == [dst / "ok.bin"]
+
+
+def test_path_traversal_key_rejected(tmp_path: Path) -> None:
+ """A tampered/stale manifest key can't escape the cache dir."""
+ cache = _cache_dir(tmp_path)
+ nb = _notebook(tmp_path)
+ secret = tmp_path / "secret.txt"
+ secret.write_bytes(b"top secret")
+ (cache / "ok.bin").write_bytes(b"ok")
+ _write_manifest(cache, nb, ["../secret.txt", "/etc/hosts", "ok.bin"])
+
+ out_dir = tmp_path / "dist"
+ out_dir.mkdir()
+ bundle_cache_export(nb, out_dir)
+
+ dst = out_dir / "public" / "cache"
+ assert (dst / "ok.bin").exists()
+ assert not (dst / ".." / "secret.txt").exists()
+ assert list(dst.rglob("*")) == [dst / "ok.bin"]
diff --git a/tests/_save/loaders/test_cache_export.py b/tests/_save/loaders/test_cache_export.py
new file mode 100644
index 0000000000..3fc6ddc9ef
--- /dev/null
+++ b/tests/_save/loaders/test_cache_export.py
@@ -0,0 +1,113 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Export-cache plumbing: manifest dump, gate, and name derivation.
+
+The end-to-end path (cell caching populates the store, kernel dumps the
+manifest on shutdown, exporter bundles it) is exercised once the cache_cells
+lifecycle lands. These unit tests cover the pieces in isolation.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING
+from unittest.mock import MagicMock
+
+from marimo._runtime.callbacks.cache import (
+ CacheCallbacks,
+ cache_cells_enabled,
+)
+from marimo._save.loaders import dump_cache_manifests
+from marimo._save.loaders.lazy import LazyLoader, LazyStore, _cache_state
+from marimo._save.stores.file import FileStore, export_manifest_name
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ import pytest
+
+
+def _clear_loaders() -> None:
+ _cache_state().active_lazy_loaders.clear()
+
+
+def test_export_manifest_name_is_per_notebook() -> None:
+ assert export_manifest_name("dir/my nb.py") == ".my-nb-export.json"
+ assert export_manifest_name("a/foo.py") != export_manifest_name("a/bar.py")
+ # No filename → deterministic fallback, still a hidden json dotfile.
+ name = export_manifest_name(None)
+ assert name.startswith(".")
+ assert name.endswith("-export.json")
+
+
+def test_dump_cache_manifests_writes_keys(tmp_path: Path) -> None:
+ _clear_loaders()
+ store = LazyStore(FileStore(save_path=str(tmp_path)))
+ LazyLoader("blk", store=store)
+ store.put("blk/hash/a.pickle", b"x")
+ store.put("blk/hash/return.pickle", b"y")
+ try:
+ dump_cache_manifests(export_manifest_name("nb.py"))
+ finally:
+ _clear_loaders()
+
+ manifest = tmp_path / export_manifest_name("nb.py")
+ assert manifest.exists()
+ assert set(json.loads(manifest.read_text())) == {
+ "blk/hash/a.pickle",
+ "blk/hash/return.pickle",
+ }
+
+
+def test_dump_cache_manifests_skips_non_file_stores(tmp_path: Path) -> None:
+ """In-memory (WASM) stores have nothing on disk — no manifest written."""
+ from marimo._save.stores.dict_store import DictStore
+
+ _clear_loaders()
+ store = LazyStore(DictStore())
+ LazyLoader("blk", store=store)
+ store.put("k", b"x")
+ try:
+ dump_cache_manifests(export_manifest_name("nb.py"))
+ finally:
+ _clear_loaders()
+
+ assert not (tmp_path / export_manifest_name("nb.py")).exists()
+
+
+def test_cache_cells_enabled_reads_config() -> None:
+ assert cache_cells_enabled({"runtime": {"cache_cells": True}}) is True
+ assert cache_cells_enabled({"runtime": {"cache_cells": False}}) is False
+ assert cache_cells_enabled({"runtime": {}}) is False
+ assert cache_cells_enabled({}) is False
+
+
+def test_teardown_dumps_only_when_caching_enabled(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import marimo._save.loaders as loaders_pkg
+
+ dumped: list[str] = []
+ flushed: list[bool] = []
+ monkeypatch.setattr(
+ loaders_pkg, "dump_cache_manifests", lambda name: dumped.append(name)
+ )
+ monkeypatch.setattr(
+ loaders_pkg, "flush_active_caches", lambda: flushed.append(True)
+ )
+
+ on = CacheCallbacks(
+ MagicMock(), caching_enabled=lambda: True, notebook_filename="nb.py"
+ )
+ on.teardown()
+ assert flushed == [True]
+ assert dumped == [export_manifest_name("nb.py")]
+
+ dumped.clear()
+ flushed.clear()
+ off = CacheCallbacks(
+ MagicMock(), caching_enabled=lambda: False, notebook_filename="nb.py"
+ )
+ off.teardown()
+ # Flush still runs (durability); the manifest dump does not.
+ assert flushed == [True]
+ assert dumped == []