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: marimo cache dir (#10836)

Dylan Madisetti068c9ecf3d3d
diff --git a/docs/guides/expensive_notebooks.md b/docs/guides/expensive_notebooks.md
index 8988a7302e..91f351f56d 100644
--- a/docs/guides/expensive_notebooks.md
+++ b/docs/guides/expensive_notebooks.md
@@ -188,6 +188,20 @@ def compute_embedding(data: str, embedding_dimension: int, model: str) -> np.nda
See our [guide on caching](../api/caching.md) for details, including how the cache
key is constructed, and limitations.
+/// tip
+
+Use the `marimo cache` command group to see and reclaim the disk space
+used by [`mo.persistent_cache`][marimo.persistent_cache].
+
+```bash
+marimo cache dir notebook.py
+```
+
+Run `marimo cache dir ./dir` to print cache directories resolved
+from the given folder.
+
+///
+
## Lazy-load expensive UIs
Lazily render UI elements that are expensive to compute using
diff --git a/marimo/_cli/cache/__init__.py b/marimo/_cli/cache/__init__.py
new file mode 100644
index 0000000000..32e3c3b3b4
--- /dev/null
+++ b/marimo/_cli/cache/__init__.py
@@ -0,0 +1,2 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
diff --git a/marimo/_cli/cache/commands.py b/marimo/_cli/cache/commands.py
new file mode 100644
index 0000000000..22fd8bd3b9
--- /dev/null
+++ b/marimo/_cli/cache/commands.py
@@ -0,0 +1,125 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+
+from marimo import _loggers
+from marimo._cli.errors import MarimoCLIError
+from marimo._cli.help_formatter import ColoredGroup
+
+LOGGER = _loggers.marimo_logger()
+
+path_argument = click.argument(
+ "path",
+ required=False,
+ default=".",
+ type=click.Path(exists=True, path_type=Path),
+)
+
+recursive_option = click.option(
+ "-r",
+ "--recursive",
+ is_flag=True,
+ default=False,
+ help=(
+ "Search a directory PATH recursively for cache directories, "
+ "skipping dot-folders."
+ ),
+)
+
+
+def format_dir(cache_dir: Path) -> str:
+ if cache_dir.is_dir():
+ return str(cache_dir)
+ if cache_dir.exists():
+ return f"{cache_dir} (not a directory)"
+ return f"{cache_dir} (does not exist)"
+
+
+def resolve_cache_dirs_or_error(path: Path, recursive: bool) -> list[Path]:
+ """Resolve PATH, reporting a resolution failure as a CLI error."""
+ from marimo._save.cache_dirs import CacheDirError, resolve_cache_dirs
+
+ try:
+ cache_dirs = resolve_cache_dirs(path, recursive=recursive)
+ except CacheDirError as e:
+ raise MarimoCLIError(str(e)) from e
+ configured = _configured_store_dirs(path, cache_dirs)
+ if configured is None:
+ return cache_dirs
+ return configured
+
+
+def _configured_store_dirs(
+ path: Path, cache_dirs: list[Path]
+) -> list[Path] | None:
+ """Directories of the store configuration, or `None`."""
+ from marimo._save.stores import (
+ cache_store_is_untrusted,
+ configured_cache_store,
+ )
+ from marimo._save.stores.file import FileStore
+ from marimo._save.stores.tiered import TieredStore
+
+ try:
+ store = configured_cache_store(current_path=str(path))
+ if store is None:
+ return None
+ untrusted = cache_store_is_untrusted(current_path=str(path))
+ except Exception:
+ LOGGER.warning("Could not read the cache store from the config")
+ return None
+
+ tiers = store.stores if isinstance(store, TieredStore) else [store]
+ directories: list[Path] = list(cache_dirs) if untrusted else []
+ for tier in tiers:
+ if isinstance(tier, FileStore) and tier.uses_default_path:
+ directories.extend(cache_dirs)
+ else:
+ directories.extend(tier.local_dirs())
+ return list(dict.fromkeys(directories))
+
+
+ cls=ColoredGroup,
+ help="""Inspect and clean up the on-disk cache.
+
+These commands work on the `__marimo__/cache/` directories written by marimo's
+caching (`mo.persistent_cache`).
+""",
+)
+def cache() -> None:
+ pass
+
+
+ name="dir",
+ help="""Print the cache directories for the directory of the argument.
+
+A blank argument defaults to the current directory, otherwise the provided
+argument should be a notebook file or directory. A notebook path resolves to the
+cache directory used by a given notebook. A directory resolves within that
+directory, as if a notebook ran there. With `-r`/`--recursive`, the directory is
+instead searched recursively for `cache` directories, skipping dot-folders.
+
+Example usage:
+
+ marimo cache dir
+
+ marimo cache dir notebook.py
+
+ marimo cache dir -r notebooks/
+""",
+)
+@path_argument
+@recursive_option
+def cache_dir(path: Path, recursive: bool) -> None:
+ cache_dirs = resolve_cache_dirs_or_error(path, recursive)
+ if not cache_dirs:
+ click.echo("No cache directories found.")
+ return
+
+ for cache_directory in cache_dirs:
+ click.echo(format_dir(cache_directory))
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 85c9b8e979..3e2739ae31 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -17,6 +17,7 @@ from click.core import ParameterSource
import marimo._cli.cli_validators as validators
from marimo import _loggers
from marimo._ast import codegen
+from marimo._cli.cache.commands import cache
from marimo._cli.config.commands import config
from marimo._cli.convert.commands import convert
from marimo._cli.development.commands import development
@@ -1602,6 +1603,7 @@ def check(
main.command()(convert)
main.add_command(export)
+main.add_command(cache)
main.add_command(config)
main.add_command(development)
main.add_command(pair)
diff --git a/marimo/_save/cache_dirs.py b/marimo/_save/cache_dirs.py
new file mode 100644
index 0000000000..81fec0ec9d
--- /dev/null
+++ b/marimo/_save/cache_dirs.py
@@ -0,0 +1,150 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Discovery of the on-disk cache directories that a path resolves to.
+
+Pure and kernel-free so the CLI can import it without starting a runtime.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from marimo import _loggers
+from marimo._utils.paths import (
+ MARIMO_DIR_NAME,
+ normalize_path,
+ notebook_output_dir,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+LOGGER = _loggers.marimo_logger()
+
+CACHE_DIR_NAME = "cache"
+
+# Statuses that still describe a marimo notebook; "empty" and "invalid" do not.
+_NOTEBOOK_STATUSES = frozenset({"valid", "has_warnings", "has_errors"})
+
+
+class CacheDirError(Exception):
+ """Base class for cache-directory resolution failures."""
+
+
+class NotANotebookError(CacheDirError):
+ """Raised when a path names a file that is not a marimo notebook."""
+
+
+def notebook_cache_dir(notebook_path: Path) -> Path:
+ """Return the cache directory belonging to `notebook_path`.
+
+ The directory need not exist. `sys.pycache_prefix` moves it away from the
+ notebook, so a caller must run under the same prefix as the kernel that
+ wrote the cache.
+ """
+ parent = normalize_path(notebook_path).parent
+ return notebook_output_dir(parent) / CACHE_DIR_NAME
+
+
+def directory_cache_dir(directory: Path) -> Path:
+ """Return the cache directory for a notebook run in `directory`.
+
+ The directory need not exist. A cache directory resolves to itself.
+ """
+ directory = normalize_path(directory)
+ if _is_cache_dir(directory):
+ return directory
+ # Resolve through a notebook inside the directory. A directory name with
+ # a suffix, such as "data.v2", reads as a file until it exists on disk,
+ # and a file's cache sits one directory up.
+ return notebook_output_dir(directory / "notebook.py") / CACHE_DIR_NAME
+
+
+def resolve_cache_dirs(path: Path, recursive: bool = False) -> list[Path]:
+ """Return the cache directories that `path` resolves to, absolute.
+
+ A notebook file resolves to the single cache directory beside it. A
+ directory resolves to the cache directory for a notebook run there.
+ Both are listed whether or not they exist yet, so a caller can report
+ an absent cache rather than nothing at all.
+
+ With `recursive`, a directory is instead searched for existing
+ `__marimo__/cache` directories, skipping dot-folders. The search can
+ come back empty.
+
+ Either way a directory that is itself a cache directory resolves to
+ itself, so the output of one call can be fed back into another.
+
+ Raises:
+ FileNotFoundError: If `path` does not exist.
+ NotANotebookError: If `path` is neither a directory nor a marimo
+ notebook file.
+ """
+ if path.is_dir():
+ if recursive:
+ return _walk_cache_dirs(path)
+ return [directory_cache_dir(path)]
+ if not path.exists():
+ raise FileNotFoundError(f"No such file or directory: {path}")
+ if not path.is_file():
+ # Reading a pipe or a device as notebook text can block for good.
+ raise NotANotebookError(f"{path} is not a notebook file.")
+ _validate_notebook(path)
+ return [notebook_cache_dir(path)]
+
+
+def _walk_cache_dirs(root: Path) -> list[Path]:
+ # Normalize first: the search recognizes a cache directory by the names of
+ # its own path components, which a relative path such as "." lacks.
+ root = normalize_path(root)
+ found = set(_cache_dirs_under(root))
+ # sys.pycache_prefix moves caches out of the tree they belong to, so the
+ # mirrored copy of `root` holds the caches written for it. Without a
+ # prefix the mirror is `root` itself.
+ mirrored = notebook_output_dir(root).parent
+ if mirrored != root and mirrored.is_dir():
+ found.update(_cache_dirs_under(mirrored))
+ return sorted(found)
+
+
+def _is_cache_dir(path: Path) -> bool:
+ return path.name == CACHE_DIR_NAME and path.parent.name == MARIMO_DIR_NAME
+
+
+def _cache_dirs_under(root: Path) -> Iterator[Path]:
+ """Yield the existing cache directories at or below `root`."""
+ if _is_cache_dir(root):
+ yield root
+ return
+ for dirpath, dirnames, _filenames in os.walk(
+ root, onerror=_log_walk_error
+ ):
+ dirnames[:] = [name for name in dirnames if not name.startswith(".")]
+ if Path(dirpath).name != MARIMO_DIR_NAME:
+ continue
+ if CACHE_DIR_NAME in dirnames:
+ # A cache directory holds no nested cache directories, and can be
+ # large.
+ dirnames.remove(CACHE_DIR_NAME)
+ yield Path(dirpath) / CACHE_DIR_NAME
+
+
+def _log_walk_error(error: OSError) -> None:
+ # os.walk swallows these by default, and an unreadable subtree then
+ # reads as holding no caches.
+ LOGGER.warning("Skipping %s: %s", error.filename, error)
+
+
+def _validate_notebook(path: Path) -> None:
+ from marimo._ast.load import get_notebook_status
+
+ try:
+ status = get_notebook_status(str(path)).status
+ except Exception as e:
+ # Keep the cause in the message. Only the message reaches the CLI,
+ # and the cause holds what actually went wrong, such as the list of
+ # extensions marimo can read.
+ raise NotANotebookError(f"{path} is not a marimo notebook: {e}") from e
+ if status not in _NOTEBOOK_STATUSES:
+ raise NotANotebookError(f"{path} is not a marimo notebook.")
diff --git a/marimo/_save/loaders/lazy.py b/marimo/_save/loaders/lazy.py
index 3f99da329c..6b128843a0 100644
--- a/marimo/_save/loaders/lazy.py
+++ b/marimo/_save/loaders/lazy.py
@@ -501,6 +501,9 @@ class LazyStore(Store):
def export_keys(self) -> list[str]:
return sorted(self._written_keys | self._touched_keys)
+ def local_dirs(self) -> list[Path]:
+ return self._inner.local_dirs()
+
class WasmLazyStore(LazyStore):
"""WASM store: writes to a shared in-session `DictStore`; reads fall
diff --git a/marimo/_save/stores/__init__.py b/marimo/_save/stores/__init__.py
index 123e5583b8..ba282b4403 100644
--- a/marimo/_save/stores/__init__.py
+++ b/marimo/_save/stores/__init__.py
@@ -48,6 +48,22 @@ def get_store(current_path: str | None = None) -> Store:
return _get_store_from_config(_store_config(config))
+def configured_cache_store(current_path: str | None = None) -> Store | None:
+ """The store `cache.store` configures, or `None` when it is unset.
+
+ Unlike `get_store`, an absent configuration returns `None` rather than
+ the default store, so a caller can tell an explicit choice apart from
+ the default.
+ """
+ from marimo._config.manager import get_default_config_manager
+
+ config = get_default_config_manager(current_path=current_path).get_config()
+ store_config = _store_config(config)
+ if store_config is None:
+ return None
+ return _get_store_from_config(store_config)
+
+
def cache_store_is_untrusted(current_path: str | None = None) -> bool:
"""Whether `cache.store` came from a layer that travels with the code."""
# NB. only the overrides are inspected, because a store can reach the user
@@ -106,5 +122,6 @@ __all__ = [
"StoreKey",
"StoreType",
"TieredStore",
+ "configured_cache_store",
"get_store",
]
diff --git a/marimo/_save/stores/file.py b/marimo/_save/stores/file.py
index 2adc31d742..16c1449c3b 100644
--- a/marimo/_save/stores/file.py
+++ b/marimo/_save/stores/file.py
@@ -49,23 +49,36 @@ class FileStore(Store):
self._resolved_save_path: Path | None = (
Path(save_path) if save_path is not None else None
)
+ self._path_given = save_path is not None
self._initialized = False
+ @property
+ def uses_default_path(self) -> bool:
+ """Whether the store was given no `save_path` of its own.
+
+ Such a store writes beside the notebook, wherever that turns out to
+ be, rather than to a directory the configuration named.
+ """
+ return not self._path_given
+
@property
def save_path(self) -> Path:
if self._resolved_save_path is None:
self._resolved_save_path = self._default_save_path()
return self._resolved_save_path
- def _default_save_path(self) -> Path:
+ def _default_target(self) -> Path:
+ """Where a store given no `save_path` writes, before it is probed."""
root = notebook_dir()
if root is None:
return FALLBACK_SAVE_PATH
+ # `sys.pycache_prefix` can move the target out of the notebook's
+ # directory.
+ return notebook_output_dir(root) / "cache"
- # Probe the write target, which `sys.pycache_prefix` can move out of
- # the notebook's directory.
- target = notebook_output_dir(root) / "cache"
- if _writable_dir(target):
+ def _default_save_path(self) -> Path:
+ target = self._default_target()
+ if target == FALLBACK_SAVE_PATH or _writable_dir(target):
return target
LOGGER.warning(
@@ -78,6 +91,14 @@ class FileStore(Store):
def _init_save_path(self) -> None:
self.save_path.mkdir(parents=True, exist_ok=True)
+ def local_dirs(self) -> list[Path]:
+ # The default target is reported unprobed. Resolving it creates
+ # directories, and asking a store where it keeps its entries must not
+ # create any.
+ if self._resolved_save_path is not None:
+ return [self._resolved_save_path]
+ return [self._default_target()]
+
def get(self, key: str) -> bytes | None:
if not self._initialized:
self._init_save_path()
diff --git a/marimo/_save/stores/store.py b/marimo/_save/stores/store.py
index b0c156a56a..ac8424a623 100644
--- a/marimo/_save/stores/store.py
+++ b/marimo/_save/stores/store.py
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator
+ from pathlib import Path
class Store(ABC):
@@ -26,6 +27,15 @@ class Store(ABC):
del key
return False
+ def local_dirs(self) -> list[Path]:
+ """Every local directory this store keeps its entries in.
+
+ Lets a caller find the disk a cache occupies without knowing which
+ store it writes through. One `put` can write to several directories,
+ and a remote store writes to none. Defaults to none.
+ """
+ return []
+
def get_batch(
self, keys: Iterable[str]
) -> Iterator[tuple[str, bytes | None]]:
diff --git a/marimo/_save/stores/tiered.py b/marimo/_save/stores/tiered.py
index 122d7833fd..36a20d9e7d 100644
--- a/marimo/_save/stores/tiered.py
+++ b/marimo/_save/stores/tiered.py
@@ -1,9 +1,14 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from typing import TYPE_CHECKING
+
from marimo import _loggers
from marimo._save.stores.store import Store
+if TYPE_CHECKING:
+ from pathlib import Path
+
LOGGER = _loggers.marimo_logger()
@@ -62,6 +67,14 @@ class TieredStore(Store):
return False
+ def local_dirs(self) -> list[Path]:
+ """Every tier that keeps entries on this filesystem."""
+ return [
+ directory
+ for store in self.stores
+ for directory in store.local_dirs()
+ ]
+
def _update_preceding_stores(
self, key: str, value: bytes, found_index: int
) -> None:
diff --git a/tests/_cli/conftest.py b/tests/_cli/conftest.py
new file mode 100644
index 0000000000..7a3f1b514c
--- /dev/null
+++ b/tests/_cli/conftest.py
@@ -0,0 +1,25 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+
+
[email protected](autouse=True)
+def _no_configured_store(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Pin the default cache resolution.
+
+ A developer's own marimo.toml can pick a cache store, which replaces
+ resolution for every cache command under test.
+ """
+ from marimo._save import stores
+
+ monkeypatch.setattr(
+ stores,
+ "configured_cache_store",
+ lambda current_path=None: None, # noqa: ARG005
+ )
+ monkeypatch.setattr(
+ stores,
+ "cache_store_is_untrusted",
+ lambda current_path=None: False, # noqa: ARG005
+ )
diff --git a/tests/_cli/test_cli_cache.py b/tests/_cli/test_cli_cache.py
new file mode 100644
index 0000000000..d2f85ed617
--- /dev/null
+++ b/tests/_cli/test_cli_cache.py
@@ -0,0 +1,165 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""CLI tests for the marimo cache command group."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from click.testing import CliRunner
+
+from marimo._cli.cache.commands import cache
+from marimo._cli.cli import main
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ import pytest
+
+NOTEBOOK = """
+import marimo
+
+app = marimo.App()
+
+
+def _():
+ x = 1
+ return (x,)
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+
+
+def make_cache_dir(root: Path, *parts: str) -> Path:
+ cache_dir = root.joinpath(*parts, "__marimo__", "cache")
+ cache_dir.mkdir(parents=True)
+ return cache_dir
+
+
+def test_cache_group_is_registered_and_documented() -> None:
+ # A hidden group drops out of `marimo --help` and out of the generated
+ # CLI documentation.
+ assert main.commands["cache"] is cache
+ assert not cache.hidden
+
+
+def test_dir_prints_the_directorys_own_cache_directory(tmp_path: Path) -> None:
+ own = make_cache_dir(tmp_path)
+ make_cache_dir(tmp_path, "nested")
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output.splitlines() == [str(own)]
+
+
+def test_dir_recursive_prints_every_cache_directory(tmp_path: Path) -> None:
+ first = make_cache_dir(tmp_path, "a")
+ second = make_cache_dir(tmp_path, "b", "deeper")
+
+ result = CliRunner().invoke(main, ["cache", "dir", "-r", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output.splitlines() == [str(first), str(second)]
+
+
+def test_dir_defaults_to_current_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ cache_dir = make_cache_dir(tmp_path)
+ monkeypatch.chdir(tmp_path)
+
+ result = CliRunner().invoke(main, ["cache", "dir"])
+
+ assert result.exit_code == 0, result.output
+ assert result.output.splitlines() == [str(cache_dir)]
+
+
+def test_dir_marks_a_cache_directory_that_does_not_exist(
+ tmp_path: Path,
+) -> None:
+ result = CliRunner().invoke(main, ["cache", "dir", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ expected = tmp_path / "__marimo__" / "cache"
+ assert result.output == f"{expected} (does not exist)\n"
+
+
+def test_dir_recursive_reports_no_cache_directories(tmp_path: Path) -> None:
+ result = CliRunner().invoke(
+ main, ["cache", "dir", "--recursive", str(tmp_path)]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert result.output == "No cache directories found.\n"
+
+
+def test_dir_notebook_path(tmp_path: Path) -> None:
+ notebook = tmp_path / "nb.py"
+ notebook.write_text(NOTEBOOK)
+ cache_dir = tmp_path / "__marimo__" / "cache"
+ cache_dir.mkdir(parents=True)
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(notebook)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output == f"{cache_dir}\n"
+
+
+def test_dir_recursive_notebook_path(tmp_path: Path) -> None:
+ # A notebook names one cache directory, so there is nothing to search and
+ # -r neither errors nor changes the answer.
+ notebook = tmp_path / "nb.py"
+ notebook.write_text(NOTEBOOK)
+ cache_dir = make_cache_dir(tmp_path)
+ make_cache_dir(tmp_path, "nested")
+
+ result = CliRunner().invoke(main, ["cache", "dir", "-r", str(notebook)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output == f"{cache_dir}\n"
+
+
+def test_dir_notebook_without_a_cache_directory(tmp_path: Path) -> None:
+ notebook = tmp_path / "nb.py"
+ notebook.write_text(NOTEBOOK)
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(notebook)])
+
+ assert result.exit_code == 0, result.output
+ expected = tmp_path / "__marimo__" / "cache"
+ assert result.output == f"{expected} (does not exist)\n"
+
+
+def test_dir_rejects_a_file_that_is_not_a_notebook(tmp_path: Path) -> None:
+ script = tmp_path / "script.py"
+ script.write_text("print('hello')\n")
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(script)])
+
+ assert result.exit_code == 1
+ assert "is not a marimo notebook" in result.stderr
+
+
+def test_dir_rejects_a_missing_path(tmp_path: Path) -> None:
+ result = CliRunner().invoke(
+ main, ["cache", "dir", str(tmp_path / "absent")]
+ )
+
+ assert result.exit_code == 2
+ assert "does not exist" in result.stderr
+
+
+def test_dir_marks_a_file_in_the_way_of_the_cache_directory(
+ tmp_path: Path,
+) -> None:
+ (tmp_path / "__marimo__").mkdir()
+ blocker = tmp_path / "__marimo__" / "cache"
+ blocker.write_text("")
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output == f"{blocker} (not a directory)\n"
diff --git a/tests/_cli/test_cli_cache_store.py b/tests/_cli/test_cli_cache_store.py
new file mode 100644
index 0000000000..78a0f46e12
--- /dev/null
+++ b/tests/_cli/test_cli_cache_store.py
@@ -0,0 +1,130 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""The cache commands act on the store the configuration picks."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from click.testing import CliRunner
+
+from marimo._cli.cli import main
+from tests._cli.test_cli_cache import NOTEBOOK, make_cache_dir
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ import pytest
+
+ from marimo._save.stores import Store
+
+
+def configure_store(monkeypatch: pytest.MonkeyPatch, store_dir: Path) -> None:
+ """Configure `store_dir` as the cache store, as marimo.toml would."""
+ from marimo._save.stores.file import FileStore
+
+ configure(monkeypatch, FileStore(save_path=str(store_dir)))
+
+
+def configure(monkeypatch: pytest.MonkeyPatch, store: Store) -> None:
+ from marimo._save import stores
+
+ monkeypatch.setattr(
+ stores,
+ "configured_cache_store",
+ lambda current_path=None: store, # noqa: ARG005
+ )
+
+
+def test_dir_prints_the_configured_store(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A `cache.store` entry replaces resolution. The kernel writes there,
+ so the commands act there."""
+ notebook = tmp_path / "nb.py"
+ notebook.write_text(NOTEBOOK)
+ make_cache_dir(tmp_path)
+ store_dir = tmp_path / "elsewhere"
+ store_dir.mkdir()
+ configure_store(monkeypatch, store_dir)
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(notebook)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output == f"{store_dir}\n"
+
+
+def test_dir_keeps_path_for_a_file_store_without_a_save_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A file store given no location writes beside the notebook, as the
+ default does. Outside a kernel it cannot say where that is."""
+ from marimo._save.stores.file import FileStore
+ from marimo._save.stores.tiered import TieredStore
+
+ notebook = tmp_path / "nb.py"
+ notebook.write_text(NOTEBOOK)
+ cache_dir = make_cache_dir(tmp_path)
+ store_dir = tmp_path / "elsewhere"
+ store_dir.mkdir()
+ configure(
+ monkeypatch,
+ TieredStore([FileStore(), FileStore(save_path=str(store_dir))]),
+ )
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(notebook)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output.splitlines() == [str(cache_dir), str(store_dir)]
+
+
+def test_dir_keeps_path_beside_a_store_the_default_method_distrusts(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A store set by a pyproject or the notebook header is ignored by the
+ default cache method, so the notebook\x27s entries can sit in either
+ place."""
+ from marimo._save import stores
+
+ notebook = tmp_path / "nb.py"
+ notebook.write_text(NOTEBOOK)
+ cache_dir = make_cache_dir(tmp_path)
+ store_dir = tmp_path / "elsewhere"
+ store_dir.mkdir()
+ configure_store(monkeypatch, store_dir)
+ monkeypatch.setattr(
+ stores,
+ "cache_store_is_untrusted",
+ lambda current_path=None: True, # noqa: ARG005
+ )
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(notebook)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output.splitlines() == [str(cache_dir), str(store_dir)]
+
+
+def test_dir_reports_nothing_for_a_store_with_no_local_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from marimo._save.stores.store import Store
+
+ class Remote(Store):
+ def get(self, key: str) -> bytes | None:
+ del key
+ return None
+
+ def put(self, key: str, value: bytes) -> bool:
+ del key, value
+ return True
+
+ def hit(self, key: str) -> bool:
+ del key
+ return False
+
+ make_cache_dir(tmp_path)
+ configure(monkeypatch, Remote())
+
+ result = CliRunner().invoke(main, ["cache", "dir", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ assert result.output == "No cache directories found.\n"
diff --git a/tests/_save/stores/test_file.py b/tests/_save/stores/test_file.py
index ee7856c7ff..d4919de72a 100644
--- a/tests/_save/stores/test_file.py
+++ b/tests/_save/stores/test_file.py
@@ -127,3 +127,22 @@ class TestDefaultSavePath:
assert path == Path("__marimo__", "cache")
assert caplog.text == ""
+
+ def test_local_dirs_does_not_resolve_the_default_path(self) -> None:
+ """Asking where entries live creates nothing and probes nothing."""
+ store = FileStore()
+
+ directories = store.local_dirs()
+
+ assert store._resolved_save_path is None
+ # Outside a kernel the notebook directory reads as the working one.
+ assert directories == [Path.cwd() / "__marimo__" / "cache"]
+
+ def test_local_dirs_reports_the_configured_path(self, tmp_path) -> None:
+ store = FileStore(tmp_path / "test_store")
+ assert store.local_dirs() == [tmp_path / "test_store"]
+ assert not (tmp_path / "test_store").exists()
+
+ def test_a_store_knows_whether_it_was_given_a_path(self, tmp_path) -> None:
+ assert FileStore().uses_default_path
+ assert not FileStore(tmp_path / "test_store").uses_default_path
diff --git a/tests/_save/stores/test_store_config.py b/tests/_save/stores/test_store_config.py
index 90e69268ac..a42798bb02 100644
--- a/tests/_save/stores/test_store_config.py
+++ b/tests/_save/stores/test_store_config.py
@@ -105,6 +105,42 @@ class TestGetStore:
assert isinstance(store, DEFAULT_STORE)
+class TestConfiguredCacheStore:
+ """configured_cache_store tells an explicit store apart from the default."""
+
+ def _store_for(self, monkeypatch, config) -> object:
+ from marimo._save import stores as stores_mod
+
+ class _Mgr:
+ def get_config(self):
+ return config
+
+ monkeypatch.setattr(
+ "marimo._config.manager.get_default_config_manager",
+ lambda **_kwargs: _Mgr(),
+ )
+ return stores_mod.configured_cache_store()
+
+ def test_a_configured_store_is_returned(self, monkeypatch) -> None:
+ store = self._store_for(
+ monkeypatch,
+ {
+ "cache": {
+ "store": {"type": "file", "args": {"save_path": "/tmp/a"}}
+ }
+ },
+ )
+ assert isinstance(store, FileStore)
+ assert store.save_path.as_posix() == "/tmp/a"
+
+ def test_an_unset_store_is_none(self, monkeypatch) -> None:
+ assert self._store_for(monkeypatch, {}) is None
+ assert (
+ self._store_for(monkeypatch, {"cache": {"verification": "on"}})
+ is None
+ )
+
+
class TestCacheStoreProvenance:
"""cache_store_is_untrusted flags a store set by a project/script layer."""
diff --git a/tests/_save/test_cache_dirs.py b/tests/_save/test_cache_dirs.py
new file mode 100644
index 0000000000..8a82322072
--- /dev/null
+++ b/tests/_save/test_cache_dirs.py
@@ -0,0 +1,289 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import logging
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from marimo import _loggers
+from marimo._save.cache_dirs import (
+ NotANotebookError,
+ directory_cache_dir,
+ notebook_cache_dir,
+ resolve_cache_dirs,
+)
+
+NOTEBOOK = """
+import marimo
+
+app = marimo.App()
+
+
+def _():
+ x = 1
+ return (x,)
+
+
+if __name__ == "__main__":
+ app.run()
+"""
+
+
+def write_notebook(path: Path) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(NOTEBOOK)
+ return path
+
+
+def make_cache_dir(root: Path, *parts: str) -> Path:
+ cache_dir = root.joinpath(*parts, "__marimo__", "cache")
+ cache_dir.mkdir(parents=True)
+ return cache_dir
+
+
+def test_resolve_directory_takes_its_own_cache_dir(tmp_path: Path) -> None:
+ # Nested caches belong to their own directories, not to this one.
+ make_cache_dir(tmp_path, "a")
+ own = make_cache_dir(tmp_path)
+
+ assert resolve_cache_dirs(tmp_path) == [own]
+
+
+def test_resolve_directory_lists_its_cache_dir_before_it_exists(
+ tmp_path: Path,
+) -> None:
+ resolved = resolve_cache_dirs(tmp_path)
+
+ assert resolved == [tmp_path / "__marimo__" / "cache"]
+ assert not resolved[0].exists()
+
+
+def test_resolve_recursive_finds_nested_cache_dirs(tmp_path: Path) -> None:
+ nested = make_cache_dir(tmp_path, "b", "deeper")
+ top = make_cache_dir(tmp_path, "a")
+ # A __marimo__ directory without a cache directory is not a hit.
+ tmp_path.joinpath("c", "__marimo__").mkdir(parents=True)
+
+ assert resolve_cache_dirs(tmp_path, recursive=True) == [top, nested]
+
+
+def test_resolve_recursive_skips_dot_folders(tmp_path: Path) -> None:
+ make_cache_dir(tmp_path, ".venv", "lib")
+ kept = make_cache_dir(tmp_path, "notebooks")
+
+ assert resolve_cache_dirs(tmp_path, recursive=True) == [kept]
+
+
+def test_resolve_recursive_dot_folder_given_explicitly(tmp_path: Path) -> None:
+ hidden = make_cache_dir(tmp_path, ".hidden")
+
+ assert resolve_cache_dirs(tmp_path / ".hidden", recursive=True) == [hidden]
+
+
+def test_resolve_recursive_directory_without_caches(tmp_path: Path) -> None:
+ assert resolve_cache_dirs(tmp_path, recursive=True) == []
+
+
[email protected]("recursive", [False, True])
+def test_resolve_a_cache_directory_itself(
+ tmp_path: Path, recursive: bool
+) -> None:
+ # A resolved directory has to resolve to itself, so that a path printed by
+ # `marimo cache dir` can be handed back to another cache command.
+ cache_dir = make_cache_dir(tmp_path, "notebooks")
+
+ assert resolve_cache_dirs(cache_dir, recursive=recursive) == [cache_dir]
+
+
[email protected]("recursive", [False, True])
+def test_resolve_an_ordinary_directory_named_cache(
+ tmp_path: Path, recursive: bool
+) -> None:
+ # Only a "cache" directory under __marimo__ is a cache directory. One a
+ # project happens to name "cache" owns a cache directory like any other.
+ plain = tmp_path / "cache"
+ own = make_cache_dir(plain)
+
+ assert resolve_cache_dirs(plain, recursive=recursive) == [own]
+
+
+def test_resolve_recursive_marimo_directory_itself(tmp_path: Path) -> None:
+ cache_dir = make_cache_dir(tmp_path, "notebooks")
+
+ assert resolve_cache_dirs(cache_dir.parent, recursive=True) == [cache_dir]
+
+
+def test_resolve_relative_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.chdir(tmp_path)
+
+ assert resolve_cache_dirs(Path(".")) == [
+ Path.cwd() / "__marimo__" / "cache"
+ ]
+
+
+def test_resolve_recursive_relative_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ make_cache_dir(tmp_path, "notebooks")
+ monkeypatch.chdir(tmp_path)
+
+ assert resolve_cache_dirs(Path("."), recursive=True) == [
+ Path.cwd() / "notebooks" / "__marimo__" / "cache"
+ ]
+
+
+def test_resolve_relative_cache_directory(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ cache_dir = make_cache_dir(tmp_path, "notebooks")
+ monkeypatch.chdir(cache_dir)
+
+ assert resolve_cache_dirs(Path(".")) == [Path.cwd()]
+
+
+ sys.platform == "win32", reason="chmod does not restrict reads on Windows"
+)
+def test_resolve_recursive_warns_about_an_unreadable_subtree(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ unreadable = tmp_path / "locked"
+ unreadable.mkdir()
+ unreadable.chmod(0o000)
+ if os.access(unreadable, os.R_OK): # running as root
+ unreadable.chmod(0o755)
+ pytest.skip("chmod does not restrict reads for this user")
+ monkeypatch.setattr(_loggers.marimo_logger(), "propagate", True)
+
+ try:
+ with caplog.at_level(logging.WARNING):
+ assert resolve_cache_dirs(tmp_path, recursive=True) == []
+ finally:
+ unreadable.chmod(0o755)
+
+ assert str(unreadable) in caplog.text
+
+
+def test_resolve_notebook_lists_its_dir_before_it_exists(
+ tmp_path: Path,
+) -> None:
+ notebook = write_notebook(tmp_path / "nb.py")
+
+ resolved = resolve_cache_dirs(notebook)
+
+ assert resolved == [tmp_path / "__marimo__" / "cache"]
+ assert not resolved[0].exists()
+
+
+def test_resolve_notebook_relative_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ write_notebook(tmp_path / "nb.py")
+ monkeypatch.chdir(tmp_path)
+
+ assert resolve_cache_dirs(Path("nb.py")) == [
+ Path.cwd() / "__marimo__" / "cache"
+ ]
+
+
+def test_resolve_notebook_honors_pycache_prefix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ prefix = tmp_path / "pycache"
+ monkeypatch.setattr(sys, "pycache_prefix", str(prefix))
+ notebook = write_notebook(tmp_path / "notebooks" / "nb.py")
+
+ expected = prefix.joinpath(
+ *notebook.parent.parts[1:], "__marimo__", "cache"
+ )
+ assert resolve_cache_dirs(notebook) == [expected]
+ assert notebook_cache_dir(notebook) == expected
+
+
+def test_resolve_directory_honors_pycache_prefix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Under a prefix a notebook's cache lives in the mirrored tree, so a
+ # directory has to report the same directory the notebook does.
+ prefix = tmp_path / "pycache"
+ monkeypatch.setattr(sys, "pycache_prefix", str(prefix))
+ notebook = write_notebook(tmp_path / "notebooks" / "nb.py")
+ mirrored = prefix.joinpath(
+ *notebook.parent.parts[1:], "__marimo__", "cache"
+ )
+
+ assert resolve_cache_dirs(notebook.parent) == [mirrored]
+ assert resolve_cache_dirs(notebook) == [mirrored]
+
+
+def test_directory_cache_dir_for_a_directory_that_does_not_exist(
+ tmp_path: Path,
+) -> None:
+ # A suffix makes a name look like a file, and a directory that is still to
+ # be created cannot be told apart from one by asking the filesystem.
+ absent = tmp_path / "data.v2"
+
+ assert directory_cache_dir(absent) == absent / "__marimo__" / "cache"
+
+
+def test_resolve_recursive_honors_pycache_prefix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ prefix = tmp_path / "pycache"
+ monkeypatch.setattr(sys, "pycache_prefix", str(prefix))
+ notebook = write_notebook(tmp_path / "notebooks" / "nb.py")
+ mirrored = prefix.joinpath(
+ *notebook.parent.parts[1:], "__marimo__", "cache"
+ )
+ mirrored.mkdir(parents=True)
+
+ assert resolve_cache_dirs(notebook.parent, recursive=True) == [mirrored]
+
+
+def test_resolve_rejects_plain_python_script(tmp_path: Path) -> None:
+ script = tmp_path / "script.py"
+ script.write_text("print('hello')\n")
+
+ with pytest.raises(NotANotebookError):
+ resolve_cache_dirs(script)
+
+
+def test_resolve_rejects_empty_file(tmp_path: Path) -> None:
+ empty = tmp_path / "empty.py"
+ empty.write_text("")
+
+ with pytest.raises(NotANotebookError):
+ resolve_cache_dirs(empty)
+
+
+def test_resolve_rejects_unsupported_file_type(tmp_path: Path) -> None:
+ data = tmp_path / "data.csv"
+ data.write_text("a,b\n1,2\n")
+
+ with pytest.raises(NotANotebookError):
+ resolve_cache_dirs(data)
+
+
+def test_resolve_missing_path(tmp_path: Path) -> None:
+ with pytest.raises(FileNotFoundError):
+ resolve_cache_dirs(tmp_path / "absent.py")
+
+
[email protected](not hasattr(os, "mkfifo"), reason="needs named pipes")
+def test_resolve_rejects_a_file_that_cannot_be_read_as_text(
+ tmp_path: Path,
+) -> None:
+ # Reading a pipe with no writer never returns, so it is refused unread.
+ pipe = tmp_path / "pipe.py"
+ os.mkfifo(pipe)
+
+ with pytest.raises(NotANotebookError, match="not a notebook file"):
+ resolve_cache_dirs(pipe)