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.

fix: persistent loader save path (+ feat: test tweaks / json loader for interpretability) (#3595)

Dylan Madisetti658be291810e
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 2bdb0570c8..78bf11dec8 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -164,6 +164,8 @@ class App:
# deterministic and not dependent on the test itself.
# Set as a private attribute as not to pollute AppConfig or kwargs.
self._anonymous_file = False
+ # injection hook to rewrite cells for pytest
+ self._pytest_rewrite = False
# Filename is derived from the callsite of the app
self._filename: str | None = None
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index 8c71f51bc5..f830f22dad 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -93,7 +93,8 @@ class CellManager:
func,
cell_id=self.create_cell_id(),
anonymous_file=app._app._anonymous_file if app else False,
- test_rewrite=is_top_level_pytest,
+ test_rewrite=is_top_level_pytest
+ or (app is not None and app._app._pytest_rewrite),
)
cell._cell.configure(cell_config)
self._register_cell(cell, app=app)
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
index 854be200d9..31674737f0 100644
--- a/marimo/_runtime/state.py
+++ b/marimo/_runtime/state.py
@@ -27,6 +27,12 @@ def extract_name(key: str) -> str:
return key.split(":")[-1]
+def contextualize_name(key: str, context: Optional[str]) -> str:
+ if context is None:
+ return key
+ return f"{context}:{key}"
+
+
class StateRegistry:
def __init__(self) -> None:
# variable name -> state
@@ -45,8 +51,7 @@ class StateRegistry:
) -> None:
if name is None:
name = str(uuid4())
- if context is not None:
- name = f"{context}:{name}"
+ name = contextualize_name(name, context)
if id(state) in self._inv_states:
ref = next(iter(self._inv_states[id(state)]))
@@ -79,8 +84,22 @@ class StateRegistry:
self.register(lookup, variable)
def _delete(self, name: str, state_item: StateItem[T]) -> None:
- self._states.pop(name, None)
- self._inv_states.pop(state_item.id, None)
+ return self.delete(name, state_item.ref())
+
+ def delete(
+ self,
+ name: str,
+ state: Optional[State[T]] = None,
+ context: Optional[str] = None,
+ ) -> None:
+ name = contextualize_name(name, context)
+ saved_state = self._states.pop(name, None)
+ state_id = id(state)
+ if saved_state and state_id != saved_state.id:
+ self.delete(name, saved_state.ref())
+
+ if state and name in self._inv_states.get(state_id, set()):
+ del self._inv_states[state_id]
def retain_active_states(self, active_variables: set[str]) -> None:
"""Retains only the active states in the registry."""
@@ -107,8 +126,7 @@ class StateRegistry:
def lookup(
self, name: str, context: Optional[str] = None
) -> Optional[State[T]]:
- if context is not None:
- name = f"{context}:{name}"
+ name = contextualize_name(name, context)
if name in self._states:
return self._states[name].ref()
return None
diff --git a/marimo/_save/__init__.py b/marimo/_save/__init__.py
index 00fdd04c7d..5955b964a9 100644
--- a/marimo/_save/__init__.py
+++ b/marimo/_save/__init__.py
@@ -1,4 +1,5 @@
# Copyright 2024 Marimo. All rights reserved.
+from marimo._save.cache import MARIMO_CACHE_VERSION
from marimo._save.save import cache, lru_cache, persistent_cache
-__all__ = ["cache", "lru_cache", "persistent_cache"]
+__all__ = ["cache", "lru_cache", "persistent_cache", "MARIMO_CACHE_VERSION"]
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index 3f21d4508a..41f286abcb 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -13,6 +13,9 @@ from marimo._runtime.state import SetFunctor
if TYPE_CHECKING:
from marimo._ast.visitor import Name
+# NB. Increment on cache breaking changes.
+MARIMO_CACHE_VERSION: int = 1
+
CacheType = Literal[
"ContextExecutionPath",
"ContentAddressed",
@@ -32,7 +35,7 @@ CACHE_PREFIX: dict[CacheType, str] = {
}
ValidCacheSha = namedtuple("ValidCacheSha", ("sha", "cache_type"))
-MetaKey = Literal["return"]
+MetaKey = Literal["return", "version"]
# BaseException because "raise _ as e" is utilized.
@@ -94,6 +97,7 @@ class Cache:
if key not in get_args(MetaKey):
raise CacheException(f"Unexpected meta key: {key}")
self.meta[key] = value
+ self.meta["version"] = MARIMO_CACHE_VERSION
defs = {**globals(), **scope}
for ref in self.stateful_refs:
diff --git a/marimo/_save/loaders/__init__.py b/marimo/_save/loaders/__init__.py
index 801fe15741..fc1af57010 100644
--- a/marimo/_save/loaders/__init__.py
+++ b/marimo/_save/loaders/__init__.py
@@ -1,10 +1,22 @@
# Copyright 2024 Marimo. All rights reserved.
+from typing import Literal
+
+from marimo._save.loaders.json import JsonLoader
from marimo._save.loaders.loader import Loader, LoaderPartial, LoaderType
from marimo._save.loaders.memory import MemoryLoader
from marimo._save.loaders.pickle import PickleLoader
+LoaderKey = Literal["memory", "pickle", "json"]
+
+PERSISTENT_LOADERS: dict[LoaderKey, LoaderType] = {
+ "pickle": PickleLoader,
+ "json": JsonLoader,
+}
+
__all__ = [
+ "PERSISTENT_LOADERS",
"Loader",
+ "LoaderKey",
"LoaderPartial",
"LoaderType",
"MemoryLoader",
diff --git a/marimo/_save/loaders/json.py b/marimo/_save/loaders/json.py
new file mode 100644
index 0000000000..b412f2db0c
--- /dev/null
+++ b/marimo/_save/loaders/json.py
@@ -0,0 +1,35 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import dataclasses
+import json
+
+from marimo._save.cache import Cache, CacheType
+from marimo._save.loaders.loader import BasePersistenceLoader, LoaderError
+
+
+class JsonLoader(BasePersistenceLoader):
+ """Readable json loader for basic objects."""
+
+ def __init__(self, name: str, save_path: str) -> None:
+ super().__init__(name, "json", save_path)
+
+ def load_persistent_cache(
+ self, hashed_context: str, cache_type: CacheType
+ ) -> Cache:
+ with open(self.build_path(hashed_context, cache_type), "rb") as handle:
+ cache = json.load(handle)
+ # Handle unserializable stateful_refs
+ cache["stateful_refs"] = set(cache["stateful_refs"])
+ try:
+ return Cache(**cache)
+ except TypeError as e:
+ raise LoaderError(
+ "Invalid json object for cache restoration"
+ ) from e
+
+ def save_cache(self, cache: Cache) -> None:
+ with open(self.build_path(cache.hash, cache.cache_type), "w") as f:
+ dump = dataclasses.asdict(cache)
+ dump["stateful_refs"] = list(dump["stateful_refs"])
+ json.dump(dump, f, indent=4)
diff --git a/marimo/_save/loaders/loader.py b/marimo/_save/loaders/loader.py
index f5094d4872..bfa90f49a3 100644
--- a/marimo/_save/loaders/loader.py
+++ b/marimo/_save/loaders/loader.py
@@ -1,13 +1,20 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import os
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import TYPE_CHECKING, Any, TypeVar
+from typing import TYPE_CHECKING, Any, Type
from marimo._runtime.context import get_context
+from marimo._runtime.context.types import ContextNotInitializedError
+from marimo._runtime.runtime import notebook_dir
from marimo._runtime.state import State
-from marimo._save.cache import CACHE_PREFIX, Cache, CacheType
+from marimo._save.cache import (
+ CACHE_PREFIX,
+ Cache,
+ CacheType,
+)
if TYPE_CHECKING:
from marimo._ast.visitor import Name
@@ -22,7 +29,12 @@ INCONSISTENT_CACHE_BOILER_PLATE = (
)
-LoaderType = TypeVar("LoaderType", bound="Loader")
+class LoaderError(BaseException):
+ """Base exception such that it can be raised as context for other errors."""
+
+ def __init__(self, message: str) -> None:
+ self.message = "\n".join([message, INCONSISTENT_CACHE_BOILER_PLATE])
+ super().__init__(message)
class LoaderPartial:
@@ -50,7 +62,10 @@ class LoaderPartial:
def create_or_reconfigure(
self, name: str, context: str = "cache_partial"
) -> State[Loader]:
- ctx = get_context()
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ return State(self(name), _name=name, _context=context)
if ctx.state_registry is None:
return State(self(name), _name=name, _context=context)
@@ -58,6 +73,10 @@ class LoaderPartial:
name, context=context
)
if loader_state is None:
+ # There's a chance it's in the registry, but the reference is None.
+ # Delete the reference just in case, otherwise GC won't hold on to
+ # this instance either.
+ ctx.state_registry.delete(name, context=context)
loader = self(name)
# State creation automatically registers itself.
return State(loader, _name=name, _context=context)
@@ -113,17 +132,17 @@ class Loader(ABC):
)
loaded = self.load_cache(hashed_context, cache_type)
# TODO: Consider more robust verification
- assert loaded.hash == hashed_context, INCONSISTENT_CACHE_BOILER_PLATE
- assert set(defs | stateful_refs) == set(loaded.defs), (
- INCONSISTENT_CACHE_BOILER_PLATE
- )
+ if loaded.hash != hashed_context:
+ raise LoaderError("Hash mismatch in loaded cache.")
+ if (defs | stateful_refs) != set(loaded.defs):
+ raise LoaderError("Variable mismatch in loaded cache.")
self._hits += 1
return Cache(
loaded.defs,
hashed_context,
stateful_refs,
cache_type,
- True,
+ True, # hit
loaded.meta,
)
@@ -161,3 +180,54 @@ class Loader(ABC):
@abstractmethod
def save_cache(self, cache: Cache) -> None:
"""Save Cache"""
+
+
+class BasePersistenceLoader(Loader):
+ """Abstract base for cache written to disk."""
+
+ def __init__(
+ self, name: str, suffix: str, save_path: str | Path | None
+ ) -> None:
+ super().__init__(name)
+
+ self.name = name
+ # Setter takes care of this, not sure why mypy is complaining.
+ self.save_path = save_path # type: ignore
+ self.suffix = suffix
+
+ @property
+ def save_path(self) -> Path:
+ return self._save_path / self.name
+
+ @save_path.setter
+ def save_path(self, save_path: str | Path | None) -> None:
+ if save_path is None and (root := notebook_dir()) is not None:
+ save_path = str(root / "__marimo__" / "cache")
+ elif save_path is None:
+ # This can happen if the notebook file is unnamed.
+ save_path = os.path.join("__marimo__", "cache")
+ self._save_path = Path(save_path)
+ (self._save_path / self.name).mkdir(parents=True, exist_ok=True)
+
+ def build_path(self, hashed_context: str, cache_type: CacheType) -> Path:
+ prefix = CACHE_PREFIX.get(cache_type, "U_")
+ return self.save_path / f"{prefix}{hashed_context}.{self.suffix}"
+
+ def cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:
+ path = self.build_path(hashed_context, cache_type)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+ def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
+ try:
+ return self.load_persistent_cache(hashed_context, cache_type)
+ except FileNotFoundError as e:
+ raise LoaderError("Unexpected cache miss.") from e
+
+ @abstractmethod
+ def load_persistent_cache(
+ self, hashed_context: str, cache_type: CacheType
+ ) -> Cache:
+ """May throw FileNotFoundError"""
+
+
+LoaderType = Type[Loader]
diff --git a/marimo/_save/loaders/memory.py b/marimo/_save/loaders/memory.py
index de98b4251f..dad649ef7b 100644
--- a/marimo/_save/loaders/memory.py
+++ b/marimo/_save/loaders/memory.py
@@ -6,7 +6,7 @@ from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union
from marimo._save.cache import Cache, CacheType
-from marimo._save.loaders.loader import INCONSISTENT_CACHE_BOILER_PLATE, Loader
+from marimo._save.loaders.loader import Loader, LoaderError
if TYPE_CHECKING:
from pathlib import Path
@@ -54,9 +54,8 @@ class MemoryLoader(Loader):
return self._maybe_lock(lambda: key in self._cache)
def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
- assert self.cache_hit(hashed_context, cache_type), (
- INCONSISTENT_CACHE_BOILER_PLATE
- )
+ if not self.cache_hit(hashed_context, cache_type):
+ raise LoaderError("Unexpected cache miss.")
key = self.build_path(hashed_context, cache_type)
if self.is_lru:
assert isinstance(self._cache, OrderedDict)
diff --git a/marimo/_save/loaders/pickle.py b/marimo/_save/loaders/pickle.py
index a81bc10007..f88f19f603 100644
--- a/marimo/_save/loaders/pickle.py
+++ b/marimo/_save/loaders/pickle.py
@@ -1,41 +1,25 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
import pickle
-from pathlib import Path
-from marimo._save.cache import CACHE_PREFIX, Cache, CacheType
-from marimo._save.loaders.loader import INCONSISTENT_CACHE_BOILER_PLATE, Loader
+from marimo._save.cache import Cache, CacheType
+from marimo._save.loaders.loader import BasePersistenceLoader, LoaderError
-class PickleLoader(Loader):
+class PickleLoader(BasePersistenceLoader):
"""General loader for serializable objects."""
def __init__(self, name: str, save_path: str) -> None:
- super().__init__(name)
- self.name = name
- self.save_path = Path(save_path) / name
- self.save_path.mkdir(parents=True, exist_ok=True)
+ super().__init__(name, "pickle", save_path)
- def build_path(self, hashed_context: str, cache_type: CacheType) -> Path:
- prefix = CACHE_PREFIX.get(cache_type, "U_")
- return self.save_path / f"{prefix}{hashed_context}.pickle"
-
- def cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:
- path = self.build_path(hashed_context, cache_type)
- return os.path.exists(path) and os.path.getsize(path) > 0
-
- def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
- assert self.cache_hit(hashed_context, cache_type), (
- INCONSISTENT_CACHE_BOILER_PLATE
- )
+ def load_persistent_cache(
+ self, hashed_context: str, cache_type: CacheType
+ ) -> Cache:
with open(self.build_path(hashed_context, cache_type), "rb") as handle:
cache = pickle.load(handle)
- assert isinstance(cache, Cache), (
- f"Excepted cache object, got{type(cache)} ",
- INCONSISTENT_CACHE_BOILER_PLATE,
- )
+ if not isinstance(cache, Cache):
+ raise LoaderError(f"Excepted cache object, got{type(cache)}")
return cache
def save_cache(self, cache: Cache) -> None:
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 40aab29222..21df40784b 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -5,11 +5,9 @@ import ast
import functools
import inspect
import io
-import os
import sys
import traceback
from collections import abc
-from pathlib import Path
# NB: maxsize follows functools.cache, but renamed max_size outside of drop-in
# api.
@@ -27,7 +25,6 @@ from typing import (
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime.context import get_context
-from marimo._runtime.runtime import notebook_dir
from marimo._runtime.state import State
from marimo._save.ast import ARG_PREFIX, ExtractWithBlock, strip_function
from marimo._save.cache import Cache, CacheException
@@ -38,11 +35,12 @@ from marimo._save.hash import (
content_cache_attempt_from_base,
)
from marimo._save.loaders import (
+ PERSISTENT_LOADERS,
Loader,
+ LoaderKey,
LoaderPartial,
LoaderType,
MemoryLoader,
- PickleLoader,
)
from marimo._utils.variables import is_mangled_local, unmangle_local
@@ -287,10 +285,13 @@ class _cache_context(object):
_filename, lineno, function_name, _code = frame
if function_name == "<module>":
ctx = get_context()
- assert ctx.execution_context is not None, (
- "Could not resolve context for cache.",
- f"{UNEXPECTED_FAILURE_BOILERPLATE}",
- )
+ if ctx.execution_context is None:
+ raise CacheException(
+ (
+ "Could not resolve context for cache."
+ f"{UNEXPECTED_FAILURE_BOILERPLATE}"
+ ),
+ )
graph = ctx.graph
cell_id = ctx.cell_id or ctx.execution_context.cell_id
pre_module, save_module = ExtractWithBlock(lineno - 1).visit(
@@ -339,7 +340,7 @@ class _cache_context(object):
sys.settrace(self._old_trace) # Clear to previous set trace.
if not self._entered_trace:
raise CacheException(
- (f"Unexpected block format{UNEXPECTED_FAILURE_BOILERPLATE}")
+ (f"Unexpected block format {UNEXPECTED_FAILURE_BOILERPLATE}")
)
# Backfill the loaded values into global scope.
@@ -352,15 +353,17 @@ class _cache_context(object):
# NB: exception is a type.
if exception:
assert not isinstance(instance, SkipWithBlock), (
- f"Cache was not correctly set{UNEXPECTED_FAILURE_BOILERPLATE}"
+ f"Cache was not correctly set {UNEXPECTED_FAILURE_BOILERPLATE}"
)
if isinstance(instance, BaseException):
raise instance from CacheException("Failure during save.")
raise exception
# Fill the cache object and save.
- assert self._cache is not None, UNEXPECTED_FAILURE_BOILERPLATE
- assert self._frame is not None, UNEXPECTED_FAILURE_BOILERPLATE
+ if self._cache is None or self._frame is None:
+ raise CacheException(
+ f"Cache was not correctly set {UNEXPECTED_FAILURE_BOILERPLATE}"
+ )
self._cache.update(self._frame.f_locals)
try:
@@ -493,7 +496,7 @@ def _invoke_context(
def cache(
fn: Optional[Callable[..., Any]] = None,
pin_modules: bool = False,
- loader: LoaderPartial | LoaderType = MemoryLoader, # type: ignore[assignment]
+ loader: LoaderPartial | LoaderType = MemoryLoader,
) -> _cache_call: ...
@@ -501,7 +504,7 @@ def cache(
def cache(
name: str,
pin_modules: bool = False,
- loader: LoaderPartial | Loader | LoaderType = MemoryLoader, # type: ignore[assignment]
+ loader: LoaderPartial | Loader | LoaderType = MemoryLoader,
) -> _cache_context: ...
@@ -665,12 +668,15 @@ def lru_cache( # type: ignore[misc]
"for lru_cache, use mo.cache instead."
)
- return cache( # type: ignore[no-any-return, call-overload]
- arg,
- *args,
- loader=MemoryLoader.partial(max_size=maxsize),
- _frame_offset=2,
- **kwargs,
+ return cast(
+ Union[_cache_call, _cache_context],
+ cache( # type: ignore[call-overload]
+ arg,
+ *args,
+ loader=MemoryLoader.partial(max_size=maxsize),
+ _frame_offset=2,
+ **kwargs,
+ ),
)
@@ -678,6 +684,7 @@ def lru_cache( # type: ignore[misc]
def persistent_cache(
name: str,
save_path: str | None = None,
+ method: LoaderKey = "pickle",
pin_modules: bool = False,
) -> _cache_context: ...
@@ -686,6 +693,7 @@ def persistent_cache(
def persistent_cache(
fn: Optional[Callable[..., Any]] = None,
save_path: str | None = None,
+ method: LoaderKey = "pickle",
pin_modules: bool = False,
) -> _cache_call: ...
@@ -693,6 +701,7 @@ def persistent_cache(
def persistent_cache( # type: ignore[misc]
name: Union[str, Optional[Callable[..., Any]]] = None,
save_path: str | None = None,
+ method: LoaderKey = "pickle",
*args: Any,
_internal_interface_not_for_external_use: None = None,
**kwargs: Any,
@@ -737,6 +746,8 @@ def persistent_cache( # type: ignore[misc]
invalidate the cache, change the name.
- `save_path`: the folder in which to save the cache, defaults to
`__marimo__/cache` in the directory of the notebook file
+ - `method`: the serialization method to use, current options are "json",
+ and "pickle" (default).
- `pin_modules`: if True, the cache will be invalidated if module versions
differ between runs, defaults to False.
@@ -770,6 +781,8 @@ def persistent_cache( # type: ignore[misc]
- `fn`: the wrapped function if no settings are passed.
- `save_path`: the folder in which to save the cache, defaults to
`__marimo__/cache` in the directory of the notebook file
+ - `method`: the serialization method to use, current options are "json",
+ and "pickle" (default).
- `pin_modules`: if True, the cache will be invalidated if module versions
differ between runs, defaults to False.
"""
@@ -782,22 +795,23 @@ def persistent_cache( # type: ignore[misc]
"loader is not a valid argument "
"for persistent_cache, use mo.cache instead."
)
-
- if save_path is None and (root := notebook_dir()) is not None:
- save_path = str(root / "__marimo__" / "cache")
- elif save_path is None:
- # This can happen if the notebook file is unnamed.
- save_path = os.path.join("__marimo__", "cache")
-
- loader = PickleLoader.partial(save_path=Path(save_path))
+ if method not in PERSISTENT_LOADERS:
+ raise ValueError(
+ f"Invalid method {method}, expected one of "
+ f"{PERSISTENT_LOADERS.keys()}"
+ )
+ loader = PERSISTENT_LOADERS[method].partial(save_path=save_path)
# Injection hook for testing
if "_loader" in kwargs:
loader = kwargs.pop("_loader")
- return cache( # type: ignore[no-any-return, call-overload]
- arg,
- *args,
- loader=loader,
- _frame_offset=2,
- **kwargs,
+ return cast(
+ Union[_cache_call, _cache_context],
+ cache( # type: ignore[call-overload]
+ arg,
+ *args,
+ loader=loader,
+ _frame_offset=2,
+ **kwargs,
+ ),
)
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index beb28806b0..a3a536403b 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -14,10 +14,7 @@ from tests.conftest import ExecReqProvider
class TestScriptCache:
@staticmethod
- def test_cache_miss() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_miss(app) -> None:
@app.cell
def one() -> tuple[int]:
# Check top level import
@@ -33,13 +30,8 @@ class TestScriptCache:
assert not cache._loader._loaded
return X, Y, persistent_cache
- app.run()
-
@staticmethod
- def test_cache_hit() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_hit(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -56,13 +48,8 @@ class TestScriptCache:
assert cache._loader._loaded
return X, Y, persistent_cache
- app.run()
-
@staticmethod
- def test_cache_loader_api() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_loader_api(app) -> None:
@app.cell
def one() -> tuple[int]:
from tests._save.mocks import MockLoader
@@ -76,13 +63,8 @@ class TestScriptCache:
assert cache._loader._loaded
return X, Y
- app.run()
-
@staticmethod
- def test_cache_hit_whitespace() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_hit_whitespace(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -102,13 +84,8 @@ class TestScriptCache:
assert cache._loader._loaded
return X, Y, persistent_cache
- app.run()
-
@staticmethod
- def test_cache_linebreak() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_linebreak(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -125,13 +102,8 @@ class TestScriptCache:
assert b == [8]
assert cache._cache.defs == {"b": [8]}
- app.run()
-
@staticmethod
- def test_cache_if_block_and_break() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_if_block_and_break(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -148,13 +120,8 @@ class TestScriptCache:
# fmt: on
assert b == [7]
- app.run()
-
@staticmethod
- def test_cache_if_block() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_if_block(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -167,13 +134,8 @@ class TestScriptCache:
b = 8
assert b == 8
- app.run()
-
@staticmethod
- def test_cache_else_block() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_else_block(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -188,10 +150,7 @@ class TestScriptCache:
assert b == 8
@staticmethod
- def test_cache_elif_block() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_elif_block(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -205,13 +164,8 @@ class TestScriptCache:
b = 8
assert b == 8
- app.run()
-
@staticmethod
- def test_cache_with_block() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_with_block(app) -> None:
@app.cell
def one() -> tuple[int]:
from contextlib import contextmanager
@@ -230,13 +184,8 @@ class TestScriptCache:
b = 8
assert b == 8
- app.run()
-
@staticmethod
- def test_cache_with_block_inner() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_cache_with_block_inner(app) -> None:
@app.cell
def one() -> tuple[int]:
from contextlib import contextmanager
@@ -255,13 +204,12 @@ class TestScriptCache:
b = 8
assert b == 8
- app.run()
-
@staticmethod
def test_cache_same_line_fails() -> None:
+ from marimo._save.ast import BlockException
+
app = App()
app._anonymous_file = True
- from marimo._save.ast import BlockException
@app.cell
def one() -> tuple[int]:
@@ -281,9 +229,10 @@ class TestScriptCache:
@staticmethod
def test_cache_in_fn_fails() -> None:
+ from marimo._save.ast import BlockException
+
app = App()
app._anonymous_file = True
- from marimo._save.ast import BlockException
@app.cell
def one() -> tuple[int]:
@@ -927,6 +876,8 @@ class TestCacheDecorator:
async def test_full_scope_utilized(
self, k: Kernel, exec_req: ExecReqProvider
) -> None:
+ # This is not completely obvious, but @cache needs to know what frame it
+ # is on so it can get locals or globals.
await k.run(
[
exec_req.get(
@@ -1075,10 +1026,7 @@ class TestCacheDecorator:
} == {0}
@staticmethod
- def test_object_content_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_object_execution_hash(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1108,13 +1056,8 @@ class TestCacheDecorator:
assert f.base_block.execution_refs == {"ns"}
return
- app.run()
-
@staticmethod
- def test_execution_hash_same_block() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_execution_hash_same_block(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1155,13 +1098,8 @@ class TestCacheDecorator:
)
return
- app.run()
-
@staticmethod
- def test_execution_hash_diff_block() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_execution_hash_diff_block(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1194,13 +1132,8 @@ class TestCacheDecorator:
assert f.base_block.execution_refs == {"ns", "z"}
return
- app.run()
-
@staticmethod
- def test_content_hash_define_after() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_content_hash_define_after(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1237,8 +1170,6 @@ class TestCacheDecorator:
assert f.base_block.missing == {"ns"}, f.base_block.missing
return
- app.run()
-
@staticmethod
def test_execution_hash_same_block_fails() -> None:
app = App()
@@ -1283,10 +1214,7 @@ class TestCacheDecorator:
app.run()
@staticmethod
- def test_unused_args() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_unused_args(app) -> None:
@app.cell
def __():
import random
@@ -1313,13 +1241,8 @@ class TestCacheDecorator:
assert a != g("world")
return
- app.run()
-
@staticmethod
- def test_shadowed_state() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_shadowed_state(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1342,13 +1265,8 @@ class TestCacheDecorator:
assert v == 3
return
- app.run()
-
@staticmethod
- def test_shadowed_state_redefined() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_shadowed_state_redefined(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1373,13 +1291,8 @@ class TestCacheDecorator:
assert v == 3
return
- app.run()
-
@staticmethod
- def test_internal_shadowed() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_internal_shadowed(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1413,13 +1326,8 @@ class TestCacheDecorator:
assert h(state1) == 111
assert h.hits == 1
- app.run()
-
@staticmethod
- def test_transitive_shadowed_state_passes() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_transitive_shadowed_state_passes(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1454,13 +1362,8 @@ class TestCacheDecorator:
assert g(state1) == 111
assert g.hits == 1
- app.run()
-
@staticmethod
- def test_shadowed_state_mismatch() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_shadowed_state_mismatch(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1495,13 +1398,8 @@ class TestCacheDecorator:
assert state() == 3
return
- app.run()
-
@staticmethod
- def test_shadowed_ui() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_shadowed_ui(app) -> None:
@app.cell
def __():
import marimo as mo
@@ -1524,4 +1422,75 @@ class TestCacheDecorator:
assert v == 3
return
- app.run()
+
+class TestPersistentCache:
+ async def test_pickle_context(
+ self, k: Kernel, exec_req: ExecReqProvider, tmp_path
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("""
+ import marimo as mo
+ import os
+ from pathlib import Path
+ pc = mo.persistent_cache
+ """),
+ exec_req.get(
+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'
+ ),
+ exec_req.get("""
+ assert not os.path.exists(tmp_path_fixture / "basic")
+ with pc("basic", save_path=tmp_path_fixture) as cache:
+ _b = 1
+ assert _b == 1
+ assert not cache._cache.hit
+ assert cache._cache.meta["version"] == mo._save.MARIMO_CACHE_VERSION
+ assert os.path.exists(tmp_path_fixture / "basic" / f"P_{cache._cache.hash}.pickle")
+ """),
+ exec_req.get("""
+ with pc("basic", save_path=tmp_path_fixture) as cache_2:
+ _b = 1
+ assert _b == 1
+ assert cache_2._cache.hit
+ assert cache._cache.hash == cache_2._cache.hash
+ assert os.path.exists(tmp_path_fixture / "basic" / f"P_{cache._cache.hash}.pickle")
+ """),
+ ]
+ )
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
+
+ async def test_json_context(
+ self, k: Kernel, exec_req: ExecReqProvider, tmp_path
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("""
+ import marimo as mo
+ import os
+ from pathlib import Path
+ pc = mo.persistent_cache
+ """),
+ exec_req.get(
+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'
+ ),
+ exec_req.get("""
+ assert not os.path.exists(tmp_path_fixture / "json")
+ with pc("json", save_path=tmp_path_fixture, method="json") as json_cache:
+ _b = 1
+ assert _b == 1
+ assert not json_cache._cache.hit
+ assert os.path.exists(tmp_path_fixture / "json" / f"P_{json_cache._cache.hash}.json")
+ """),
+ exec_req.get("""
+ with pc("json", save_path=tmp_path_fixture, method="json") as json_cache_2:
+ _b = 1
+ assert _b == 1
+ assert json_cache_2._cache.hit
+ assert json_cache._cache.hash == json_cache_2._cache.hash
+ assert os.path.exists(tmp_path_fixture / "json" / f"P_{json_cache._cache.hash}.json")
+ """),
+ ]
+ )
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index 5de2bc4690..298e030d07 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -6,16 +6,12 @@ from typing import Any
import pytest
-from marimo._ast.app import App
from marimo._dependencies.dependencies import DependencyManager
class TestHash:
@staticmethod
- def test_pure_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_pure_hash(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -27,13 +23,8 @@ class TestHash:
assert cache._cache.cache_type == "Pure"
return Y, Z
- app.run()
-
@staticmethod
- def test_content_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_content_hash(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -45,17 +36,12 @@ class TestHash:
assert cache._cache.cache_type == "ContentAddressed"
return (Y,)
- app.run()
-
# Note: Hash may change based on byte code, so pin to particular version
@staticmethod
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_content_reproducibility() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_content_reproducibility(app) -> None:
@app.cell
def load() -> tuple[Any]:
from marimo._save.save import persistent_cache
@@ -94,13 +80,8 @@ class TestHash:
Z = 11
return (Z,)
- app.run()
-
@staticmethod
- def test_execution_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_execution_hash(app) -> None:
@app.cell
def one() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -113,15 +94,13 @@ class TestHash:
assert cache._cache.cache_type == "ContextExecutionPath"
return (Y,)
- app.run()
-
@staticmethod
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_execution_reproducibility() -> None:
- app = App()
- app._anonymous_file = True
+ def test_execution_reproducibility(app) -> None:
+ # Rewrite changes the AST, breaking the hash
+ app._pytest_rewrite = False
@app.cell
def load() -> tuple[int]:
@@ -170,17 +149,15 @@ class TestHash:
Z = 11
return (Z,)
- app.run()
-
@staticmethod
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_execution_reproducibility_different_cell_order() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_execution_reproducibility_different_cell_order(app) -> None:
# NB. load is last for cell order difference.
+ # Rewrite changes the AST, breaking the hash
+ app._pytest_rewrite = False
+
@app.cell
def one(persistent_cache, MockLoader, shared) -> tuple[int]:
_a = [1, object()]
@@ -228,13 +205,8 @@ class TestHash:
shared = [None, object()]
return persistent_cache, MockLoader, shared
- app.run()
-
@staticmethod
- def test_transitive_content_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_transitive_content_hash(app) -> None:
@app.cell
def load() -> tuple[int]:
from marimo._save.save import persistent_cache
@@ -251,13 +223,8 @@ class TestHash:
assert cache._cache.cache_type == "ContentAddressed"
return (Y,)
- app.run()
-
@staticmethod
- def test_function_ui_content_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_function_ui_content_hash(app) -> None:
@app.cell
def load() -> tuple[Any]:
import marimo as mo
@@ -287,13 +254,8 @@ class TestHash:
assert cache2._cache.hash != cache._cache.hash
return (cache2,)
- app.run()
-
@staticmethod
- def test_function_state_content_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_function_state_content_hash(app) -> None:
@app.cell
def load() -> tuple[Any]:
import marimo as mo
@@ -327,13 +289,8 @@ class TestHash:
assert cache2._cache.hash != cache._cache.hash
return (cache2,)
- app.run()
-
@staticmethod
- def test_function_state_content_hash_distinct() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_function_state_content_hash_distinct(app) -> None:
@app.cell
def load() -> tuple[Any]:
import marimo as mo
@@ -352,13 +309,8 @@ class TestHash:
assert "State" in b, b
return a, b
- app.run()
-
@staticmethod
- def test_transitive_execution_path_when_state_dependent() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_transitive_execution_path_when_state_dependent(app) -> None:
@app.cell
def load() -> tuple[Any]:
import marimo as mo
@@ -394,13 +346,8 @@ class TestHash:
assert cache2._cache.hash != cache._cache.hash
return (cache2,)
- app.run()
-
@staticmethod
- def test_version_pinning() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_version_pinning(app) -> None:
@app.cell
def load() -> tuple[Any]:
import marimo as mo
@@ -432,8 +379,6 @@ class TestHash:
assert cache2._cache.hash != cache._cache.hash
return (cache2,)
- app.run()
-
class TestDataHash:
@staticmethod
@@ -446,10 +391,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_numpy_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_numpy_hash(app) -> None:
@app.cell
def load() -> tuple[Any]:
import numpy as np
@@ -492,8 +434,6 @@ class TestDataHash:
assert one == two
assert one == 512
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("jax"),
@@ -504,10 +444,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_jax_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_jax_hash(app) -> None:
@app.cell
def load() -> tuple[Any]:
from jax import numpy as np
@@ -550,8 +487,6 @@ class TestDataHash:
assert one == two
assert one == 512
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("torch"),
@@ -562,10 +497,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_torch_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_torch_hash(app) -> None:
@app.cell
def load() -> tuple[Any]:
import torch
@@ -612,8 +544,6 @@ class TestDataHash:
assert one == two
assert one == 512
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("torch"),
@@ -624,11 +554,9 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_torch_device_hash() -> None:
+ def test_torch_device_hash(app) -> None:
# Utilizing the "meta" device should give similar cross device behavior
# as gpu.
- app = App()
- app._anonymous_file = True
@app.cell
def load() -> tuple[Any]:
@@ -657,8 +585,6 @@ class TestDataHash:
)
return (one,)
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("skbio"),
@@ -669,10 +595,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_skibio_hash() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_skibio_hash(app) -> None:
@app.cell
def load() -> tuple[Any]:
from copy import copy
@@ -701,8 +624,6 @@ class TestDataHash:
)
return (one,)
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("pandas"),
@@ -713,10 +634,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_dataframe() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_dataframe(app) -> None:
@app.cell
def load() -> tuple[Any]:
import numpy as np
@@ -770,8 +688,6 @@ class TestDataHash:
assert one == two
assert one == 14
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("pandas"),
@@ -782,10 +698,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_dataframe_object() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_dataframe_object(app) -> None:
@app.cell
def load() -> tuple[Any]:
import numpy as np
@@ -817,8 +730,6 @@ class TestDataHash:
)
return (one,)
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("polars"),
@@ -829,10 +740,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_polars_dataframe() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_polars_dataframe(app) -> None:
@app.cell
def load() -> tuple[Any]:
import polars as pl
@@ -881,8 +789,6 @@ class TestDataHash:
assert one == two
assert one == 14
- app.run()
-
@staticmethod
@pytest.mark.skipif(
not DependencyManager.has("polars"),
@@ -891,10 +797,7 @@ class TestDataHash:
@pytest.mark.skipif(
"sys.version_info < (3, 12) or sys.version_info >= (3, 13)"
)
- def test_polars_object() -> None:
- app = App()
- app._anonymous_file = True
-
+ def test_polars_object(app) -> None:
@app.cell
def load() -> tuple[Any]:
import polars as pl
@@ -923,5 +826,3 @@ class TestDataHash:
)
assert _A == 28
return (two,)
-
- app.run()
diff --git a/tests/conftest.py b/tests/conftest.py
index e43b22a90c..8d2bdfcb7c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any, Generator
import pytest
from _pytest import runner
-from marimo._ast.app import CellManager
+from marimo._ast.app import App, CellManager
from marimo._ast.cell import CellId_t
from marimo._config.config import DEFAULT_CONFIG
from marimo._messaging.mimetypes import KnownMimeType
@@ -558,6 +558,19 @@ def mo_fixture() -> ModuleType:
return mo
+# Sets some non-public attributes on App and runs it.
+def app() -> Generator[App, None, None]:
+ app = App()
+ # Needed for consistent stack trace paths.
+ app._anonymous_file = True
+ # Provides verbose traceback on assertion errors. Note it does alter the
+ # cell AST.
+ app._pytest_rewrite = True
+ yield app
+ app.run()
+
+
# A pytest hook to fail when raw marimo cells are not collected.
@pytest.hookimpl
def pytest_make_collect_report(collector):