A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: configurable marimo store cache (#4147)
Dylan Madisetti88865d3b91e1
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex ff2331e476..1b2f3802f5 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -146,6 +146,7 @@ def create_kernel_context(from marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.state import StateRegistryfrom marimo._runtime.virtual_file import VirtualFileRegistry+ from marimo._save.stores import get_storereturn KernelRuntimeContext(_kernel=kernel,@@ -154,6 +155,7 @@ def create_kernel_context(ui_element_registry=UIElementRegistry(),state_registry=StateRegistry(),function_registry=FunctionRegistry(),+ cache_store=get_store(),cell_lifecycle_registry=CellLifecycleRegistry(),app_kernel_runner_registry=AppKernelRunnerRegistry(),virtual_file_registry=VirtualFileRegistry(),diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.pyindex 244c3ac2e9..ba556e1682 100644--- a/marimo/_runtime/context/script_context.py+++ b/marimo/_runtime/context/script_context.py@@ -136,12 +136,14 @@ def initialize_script_context(Must be called exactly once for each client thread."""from marimo._runtime.virtual_file import VirtualFileRegistry+ from marimo._save.stores import get_storeruntime_context = ScriptRuntimeContext(_app=app,ui_element_registry=UIElementRegistry(),state_registry=StateRegistry(),function_registry=FunctionRegistry(),+ cache_store=get_store(),cell_lifecycle_registry=CellLifecycleRegistry(),app_kernel_runner_registry=AppKernelRunnerRegistry(),virtual_file_registry=VirtualFileRegistry(),diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.pyindex 56a9390e93..6293ba5a2d 100644--- a/marimo/_runtime/context/types.py+++ b/marimo/_runtime/context/types.py@@ -30,6 +30,7 @@ if TYPE_CHECKING:from marimo._runtime.params import CLIArgs, QueryParamsfrom marimo._runtime.state import State, StateRegistryfrom marimo._runtime.virtual_file import VirtualFileRegistry+ from marimo._save.stores import Storefrom marimo._types.ids import CellId_t@@ -74,6 +75,7 @@ class RuntimeContext(abc.ABC):virtual_file_registry: VirtualFileRegistryvirtual_files_supported: boolapp_kernel_runner_registry: AppKernelRunnerRegistry+ cache_store: Store# stream, stdout, stderr are _not_ owned by the contextstream: Streamstdout: Stdout | Nonediff --git a/marimo/_save/cache.py b/marimo/_save/cache.pyindex 41f286abcb..f7219adcb0 100644--- a/marimo/_save/cache.py+++ b/marimo/_save/cache.py@@ -12,9 +12,10 @@ from marimo._runtime.state import SetFunctorif TYPE_CHECKING:from marimo._ast.visitor import Name+ from marimo._save.hash import HashKey# NB. Increment on cache breaking changes.-MARIMO_CACHE_VERSION: int = 1+MARIMO_CACHE_VERSION: int = 2CacheType = Literal["ContextExecutionPath",@@ -47,8 +48,8 @@ class CacheException(BaseException):class Cache:defs: dict[Name, Any]hash: str- stateful_refs: set[str]cache_type: CacheType+ stateful_refs: set[str]hit: bool# meta corresponds to internally used data, kept as a dictionary to allow# for backwards pickle compatibility with future entries.@@ -133,3 +134,35 @@ class Cache:for var, value in self.defs.items()if var not in self.stateful_refs}++ @property+ def key(self) -> HashKey:+ from marimo._save.hash import HashKey++ return HashKey(hash=self.hash, cache_type=self.cache_type)++ @classmethod+ def empty(+ cls, *, key: HashKey, defs: set[str], stateful_refs: set[str]+ ) -> Cache:+ return Cache(+ defs={d: None for d in defs},+ hash=key.hash,+ cache_type=key.cache_type,+ stateful_refs=stateful_refs,+ hit=False,+ meta={},+ )++ @classmethod+ def new(+ cls, *, loaded: Cache, key: HashKey, stateful_refs: set[str]+ ) -> Cache:+ return Cache(+ defs=loaded.defs,+ hash=key.hash,+ cache_type=key.cache_type,+ stateful_refs=stateful_refs,+ hit=True,+ meta=loaded.meta,+ )diff --git a/marimo/_save/hash.py b/marimo/_save/hash.pyindex ae46aede01..47d3afc596 100644--- a/marimo/_save/hash.py+++ b/marimo/_save/hash.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport astimport base64+import dataclassesimport hashlibimport inspectimport struct@@ -290,6 +291,12 @@ def get_and_update_context_from_scope(return None+class HashKey:+ hash: str+ cache_type: CacheType++class BlockHasher:def __init__(self,@@ -359,6 +366,7 @@ class BlockHasher:)self._hash: Optional[str] = None+ self._exe_hash: Optional[str] = Noneself.graph = graphself.cell_id = cell_idself.pin_modules = pin_modules@@ -427,6 +435,9 @@ class BlockHasher:self.hash_and_verify_context_refs(refs, context)self.context_refs -= refs | self.content_refs | self.execution_refs+ # Hold on to execution_path refs before content update.+ self.exe_alg = self.hash_alg.copy()+# Now run the content hash on the content refs.if apply_content_hash:self._apply_content_hash(content_serialization)@@ -435,7 +446,10 @@ class BlockHasher:# Finally, utilize the unrun block itself, and clean up.self.cache_type = cache_type- self.hash_alg.update(hash_raw_module(module, hash_type))+ module_hash = hash_raw_module(module, hash_type)+ self.hash_alg.update(module_hash)+ # Update execution path without content data.+ self.exe_alg.update(module_hash)@staticmethoddef from_parent(@@ -454,7 +468,9 @@ class BlockHasher:block.defs = set(parent.defs)block.stateful_refs = set(parent.stateful_refs)block.hash_alg = parent.hash_alg.copy()+ block.exe_alg = parent.exe_alg.copy()block._hash = None+ block._exe_hash = parent._exe_hash # The exe hash is the sameblock.cache_type = parent.cache_typeblock.content_refs = set(parent.content_refs)block.execution_refs = set(parent.execution_refs)@@ -472,9 +488,27 @@ class BlockHasher:)return self._hash+ @property+ def exe_hash(self) -> str:+ if self._exe_hash is None:+ assert self.exe_alg is not None, "Hash algorithm not initialized."+ self._exe_hash = (+ base64.urlsafe_b64encode(self.exe_alg.digest())+ .decode("utf-8")+ .strip("=")+ )+ return self._exe_hash+def __hash__(self) -> int:return hash(self.hash)+ @property+ def key(self) -> HashKey:+ return HashKey(+ hash=self.hash,+ cache_type=self.cache_type,+ )+def _apply_content_hash(self, content_serialization: dict[Name, bytes]) -> None:@@ -900,9 +934,8 @@ def cache_attempt_from_hash(return loader.cache_attempt(hasher.defs,- hasher.hash,+ hasher.key,hasher.stateful_refs,- hasher.cache_type,)@@ -989,7 +1022,6 @@ def content_cache_attempt_from_base(return loader.cache_attempt(hasher.defs,- hasher.hash,+ hasher.key,stateful_refs,- hasher.cache_type,)diff --git a/marimo/_save/loaders/__init__.py b/marimo/_save/loaders/__init__.pyindex fc1af57010..62bfaba0fb 100644--- a/marimo/_save/loaders/__init__.py+++ b/marimo/_save/loaders/__init__.py@@ -2,7 +2,12 @@from typing import Literalfrom marimo._save.loaders.json import JsonLoader-from marimo._save.loaders.loader import Loader, LoaderPartial, LoaderType+from marimo._save.loaders.loader import (+ BasePersistenceLoader,+ Loader,+ LoaderPartial,+ LoaderType,+)from marimo._save.loaders.memory import MemoryLoaderfrom marimo._save.loaders.pickle import PickleLoader@@ -17,6 +22,7 @@ __all__ = ["PERSISTENT_LOADERS","Loader","LoaderKey",+ "BasePersistenceLoader","LoaderPartial","LoaderType","MemoryLoader",diff --git a/marimo/_save/loaders/json.py b/marimo/_save/loaders/json.pyindex b412f2db0c..56513d5092 100644--- a/marimo/_save/loaders/json.py+++ b/marimo/_save/loaders/json.py@@ -3,33 +3,33 @@ from __future__ import annotationsimport dataclassesimport json+from typing import Any-from marimo._save.cache import Cache, CacheType+from marimo._save.cache import Cache+from marimo._save.hash import HashKeyfrom marimo._save.loaders.loader import BasePersistenceLoader, LoaderErrorclass JsonLoader(BasePersistenceLoader):"""Readable json loader for basic objects."""- def __init__(self, name: str, save_path: str) -> None:- super().__init__(name, "json", save_path)+ def __init__(self, name: str, save_path: str, **kwargs: Any) -> None:+ super().__init__(name, "json", save_path, **kwargs)- 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 restore_cache(self, key: HashKey, blob: bytes) -> Cache:+ del key+ cache = json.loads(blob)+ # Handle unserializable stateful_refs+ cache["stateful_refs"] = set(cache["stateful_refs"])+ try:+ hash_key = cache.pop("key", {})+ return Cache(**hash_key, **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)+ def to_blob(self, cache: Cache) -> bytes:+ dump = dataclasses.asdict(cache)+ dump["stateful_refs"] = list(dump["stateful_refs"])+ return json.dumps(dump, indent=4).encode("utf-8")diff --git a/marimo/_save/loaders/loader.py b/marimo/_save/loaders/loader.pyindex cf2ca3a687..624b1b5658 100644--- a/marimo/_save/loaders/loader.py+++ b/marimo/_save/loaders/loader.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport osfrom abc import ABC, abstractmethodfrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Optionalfrom marimo._runtime.context import get_contextfrom marimo._runtime.context.types import ContextNotInitializedError@@ -13,11 +13,12 @@ from marimo._runtime.state import Statefrom marimo._save.cache import (CACHE_PREFIX,Cache,- CacheType,)+from marimo._save.stores import DEFAULT_STORE, Storeif TYPE_CHECKING:from marimo._ast.visitor import Name+ from marimo._save.hash import HashKeyINCONSISTENT_CACHE_BOILER_PLATE = ("The cache state does not match "@@ -110,40 +111,29 @@ class Loader(ABC):self.name = nameself._hits = 0- def build_path(self, hashed_context: str, cache_type: CacheType) -> Path:- prefix = CACHE_PREFIX.get(cache_type, "U_")- return Path(f"{prefix}{hashed_context}")+ def build_path(self, key: HashKey) -> Path:+ prefix = CACHE_PREFIX.get(key.cache_type, "U_")+ return Path(f"{prefix}{key.hash}")def cache_attempt(self,defs: set[Name],- hashed_context: str,+ key: HashKey,stateful_refs: set[Name],- cache_type: CacheType,) -> Cache:- if not self.cache_hit(hashed_context, cache_type):- return Cache(- {d: None for d in defs},- hashed_context,- stateful_refs,- cache_type,- False,- {},- )- loaded = self.load_cache(hashed_context, cache_type)+ loaded = self.load_cache(key)+ if not loaded:+ return Cache.empty(defs=defs, key=key, stateful_refs=stateful_refs)# TODO: Consider more robust verification- if loaded.hash != hashed_context:+ if loaded.hash != key.hash: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, # hit- loaded.meta,+ return Cache.new(+ loaded=loaded,+ key=key,+ stateful_refs=stateful_refs,)@property@@ -162,19 +152,19 @@ class Loader(ABC):return cache(*args, loader=cls, **kwargs) # type: ignore@abstractmethod- def cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:+ def cache_hit(self, key: HashKey) -> bool:"""Check if cache has been hit given a result hash.Args:- hashed_context: The hash of the result context- cache_type: The type of cache to check for+ key: The hash of the result context, and the hash type, and the+ execution hash.Returns:bool: Whether the cache has been hit"""@abstractmethod- def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:+ def load_cache(self, key: HashKey) -> Optional[Cache]:"""Load Cache"""@abstractmethod@@ -186,10 +176,22 @@ class BasePersistenceLoader(Loader):"""Abstract base for cache written to disk."""def __init__(- self, name: str, suffix: str, save_path: str | Path | None+ self,+ name: str,+ suffix: str,+ save_path: str | Path | None,+ store: Optional[Store] = None,) -> None:super().__init__(name)+ if store is not None:+ self.store = store+ else:+ try:+ self.store = get_context().cache_store+ except ContextNotInitializedError:+ self.store = DEFAULT_STORE()+self.name = name# Setter takes care of this, not sure why mypy is complaining.self.save_path = save_path # type: ignore@@ -209,25 +211,32 @@ class BasePersistenceLoader(Loader):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 build_path(self, key: HashKey) -> Path:+ prefix = CACHE_PREFIX.get(key.cache_type, "U_")+ return self.save_path / f"{prefix}{key.hash}.{self.suffix}"++ def cache_hit(self, key: HashKey) -> bool:+ return self.store.hit(key, self)- 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 save_cache(self, cache: Cache) -> None:+ return self.store.put(cache, self)- def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:+ def load_cache(self, key: HashKey) -> Optional[Cache]:try:- return self.load_persistent_cache(hashed_context, cache_type)+ blob: Optional[bytes] = self.store.get(key, self)+ if not blob:+ return None+ return self.restore_cache(key, blob)except FileNotFoundError as e:raise LoaderError("Unexpected cache miss.") from e@abstractmethod- def load_persistent_cache(- self, hashed_context: str, cache_type: CacheType- ) -> Cache:+ def restore_cache(self, key: HashKey, blob: bytes) -> Cache:"""May throw FileNotFoundError"""+ @abstractmethod+ def to_blob(self, cache: Cache) -> Optional[bytes]:+ """Convert cache to bytes"""+LoaderType = type[Loader]diff --git a/marimo/_save/loaders/memory.py b/marimo/_save/loaders/memory.pyindex dad649ef7b..4f78e3e896 100644--- a/marimo/_save/loaders/memory.py+++ b/marimo/_save/loaders/memory.py@@ -5,12 +5,14 @@ import threadingfrom collections import OrderedDictfrom typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union-from marimo._save.cache import Cache, CacheType-from marimo._save.loaders.loader import Loader, LoaderError+from marimo._save.cache import Cache+from marimo._save.loaders.loader import Loaderif TYPE_CHECKING:from pathlib import Path+ from marimo._save.hash import HashKey+T = TypeVar("T")@@ -49,33 +51,33 @@ class MemoryLoader(Loader):else:return fn()- def cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:- key = self.build_path(hashed_context, cache_type)- return self._maybe_lock(lambda: key in self._cache)+ def cache_hit(self, key: HashKey) -> bool:+ path = self.build_path(key)+ return self._maybe_lock(lambda: path in self._cache)- def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:- if not self.cache_hit(hashed_context, cache_type):- raise LoaderError("Unexpected cache miss.")- key = self.build_path(hashed_context, cache_type)+ def load_cache(self, key: HashKey) -> Optional[Cache]:+ if not self.cache_hit(key):+ return None+ path = self.build_path(key)if self.is_lru:assert isinstance(self._cache, OrderedDict)assert self._cache_lock is not Nonewith self._cache_lock:- self._cache.move_to_end(key)- return self._cache[key]+ self._cache.move_to_end(path)+ return self._cache[path]def save_cache(self, cache: Cache) -> None:- key = self.build_path(cache.hash, cache.cache_type)+ path = self.build_path(cache.key)# LRUif self.is_lru:assert isinstance(self._cache, OrderedDict)assert self._cache_lock is not Nonewith self._cache_lock:- self._cache[key] = cache- self._cache.move_to_end(key)+ self._cache[path] = cache+ self._cache.move_to_end(path)if len(self._cache) > self.max_size:self._cache.popitem(last=False)- self._cache[key] = cache+ self._cache[path] = cachedef resize(self, max_size: int) -> None:if not self.is_lru:diff --git a/marimo/_save/loaders/pickle.py b/marimo/_save/loaders/pickle.pyindex f88f19f603..38a8e71dfe 100644--- a/marimo/_save/loaders/pickle.py+++ b/marimo/_save/loaders/pickle.py@@ -2,26 +2,27 @@from __future__ import annotationsimport pickle+from typing import TYPE_CHECKING, Any-from marimo._save.cache import Cache, CacheType+from marimo._save.cache import Cachefrom marimo._save.loaders.loader import BasePersistenceLoader, LoaderError+if TYPE_CHECKING:+ from marimo._save.hash import HashKey+class PickleLoader(BasePersistenceLoader):"""General loader for serializable objects."""- def __init__(self, name: str, save_path: str) -> None:- super().__init__(name, "pickle", 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 = pickle.load(handle)- if not isinstance(cache, Cache):- raise LoaderError(f"Excepted cache object, got{type(cache)}")- return cache-- def save_cache(self, cache: Cache) -> None:- with open(self.build_path(cache.hash, cache.cache_type), "wb") as f:- pickle.dump(cache, f, protocol=pickle.HIGHEST_PROTOCOL)+ def __init__(self, name: str, save_path: str, **kwargs: Any) -> None:+ super().__init__(name, "pickle", save_path, **kwargs)++ def restore_cache(self, key: HashKey, blob: bytes) -> Cache:+ del key+ cache = pickle.loads(blob)+ if not isinstance(cache, Cache):+ raise LoaderError(f"Excepted cache object, got{type(cache)}")+ return cache++ def to_blob(self, cache: Cache) -> bytes:+ return pickle.dumps(cache, protocol=pickle.HIGHEST_PROTOCOL)diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 64d82eefcf..eb856a4898 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -62,6 +62,7 @@ if TYPE_CHECKING:from types import FrameType, TracebackTypefrom marimo._runtime.dataflow import DirectedGraph+ from marimo._save.stores import Storeclass _cache_call:@@ -232,6 +233,10 @@ class _cache_context(SkipContext):self.hash_type = hash_typeself._loader = loader+ @property+ def hit(self) -> bool:+ return self._cache is not None and self._cache.hit+def trace(self, with_frame: FrameType) -> None:# General flow is as follows:# 1) Follow the stack trace backwards to the first instance of a@@ -674,6 +679,7 @@ def persistent_cache( # type: ignore[misc]name: Union[str, Optional[Callable[..., Any]]] = None,save_path: str | None = None,method: LoaderKey = "pickle",+ store: Optional[Store] = None,*args: Any,_internal_interface_not_for_external_use: None = None,**kwargs: Any,@@ -772,7 +778,12 @@ def persistent_cache( # type: ignore[misc]f"Invalid method {method}, expected one of "f"{PERSISTENT_LOADERS.keys()}")- loader = PERSISTENT_LOADERS[method].partial(save_path=save_path)++ partial_args: dict[str, Any] = {"save_path": save_path}+ if store is not None:+ partial_args["store"] = store++ loader = PERSISTENT_LOADERS[method].partial(**partial_args)# Injection hook for testingif "_loader" in kwargs:loader = kwargs.pop("_loader")diff --git a/marimo/_save/stores/__init__.py b/marimo/_save/stores/__init__.pynew file mode 100644index 0000000000..c395093ab2--- /dev/null+++ b/marimo/_save/stores/__init__.py@@ -0,0 +1,41 @@+# Copyright 2025 Marimo. All rights reserved.+from typing import Literal++from marimo._save.stores.file import FileStore+from marimo._save.stores.redis import RedisStore+from marimo._save.stores.store import Store, StoreType++StoreKey = Literal["file", "redis"]++CACHE_STORES: dict[StoreKey, StoreType] = {+ "file": FileStore,+ "redis": RedisStore,+}+DEFAULT_STORE_KEY: StoreKey = "file"+DEFAULT_STORE: StoreType = CACHE_STORES[DEFAULT_STORE_KEY]+++def get_store() -> Store:+ from marimo._config.manager import get_default_config_manager++ cache_config = (+ get_default_config_manager(current_path=None)+ .get_config()+ .get("experimental", {})+ .get("cache", {})+ )+ store_type = cache_config.get("store", DEFAULT_STORE_KEY)+ assert store_type in CACHE_STORES, f"Invalid store type: {store_type}"+ return CACHE_STORES[store_type](**cache_config.get("args", {}))+++__all__ = [+ "CACHE_STORES",+ "DEFAULT_STORE",+ "FileStore",+ "RedisStore",+ "Store",+ "StoreKey",+ "StoreType",+ "get_store",+]diff --git a/marimo/_save/stores/file.py b/marimo/_save/stores/file.pynew file mode 100644index 0000000000..be4c94c821--- /dev/null+++ b/marimo/_save/stores/file.py@@ -0,0 +1,41 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import os+from typing import TYPE_CHECKING, Optional++from marimo._save.cache import (+ Cache,+)+from marimo._save.stores.store import Store++if TYPE_CHECKING:+ from pathlib import Path++ from marimo._save.hash import HashKey+ from marimo._save.loaders import BasePersistenceLoader as Loader+++def _valid_path(path: Path) -> bool:+ return os.path.exists(path) and os.path.getsize(path) > 0+++class FileStore(Store):+ def get(self, key: HashKey, loader: Loader) -> Optional[bytes]:+ path = loader.build_path(key)+ if not _valid_path(path):+ return None+ with open(path, "rb") as f:+ return f.read()++ def put(self, cache: Cache, loader: Loader) -> None:+ path = loader.build_path(cache.key)+ blob = loader.to_blob(cache)+ if blob is None:+ return+ with open(path, "wb") as f:+ f.write(blob)++ def hit(self, key: HashKey, loader: Loader) -> bool:+ path = loader.build_path(key)+ return _valid_path(path)diff --git a/marimo/_save/stores/redis.py b/marimo/_save/stores/redis.pynew file mode 100644index 0000000000..ceb38b6aa6--- /dev/null+++ b/marimo/_save/stores/redis.py@@ -0,0 +1,34 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any, Optional++from marimo._save.cache import (+ Cache,+)+from marimo._save.stores.store import Store++if TYPE_CHECKING:+ from marimo._save.hash import HashKey+ from marimo._save.loaders import BasePersistenceLoader as Loader+++class RedisStore(Store):+ def __init__(self, **kwargs: Any) -> None:+ import redis++ # TODO: Construct from a full config dataclass, and pass in kwargs+ # opposed to experimental.store.redis.args+ # See list of options here:+ self.redis = redis.Redis(**kwargs)++ def get(self, key: HashKey, loader: Loader) -> Optional[bytes]:+ return self.redis.get(str(loader.build_path(key))) or None++ def put(self, cache: Cache, loader: Loader) -> None:+ self.redis.set(+ str(loader.build_path(cache.key)), loader.to_blob(cache) or b""+ )++ def hit(self, key: HashKey, loader: Loader) -> bool:+ return self.redis.exists(str(loader.build_path(key))) > 0diff --git a/marimo/_save/stores/store.py b/marimo/_save/stores/store.pynew file mode 100644index 0000000000..f0ee0e6a46--- /dev/null+++ b/marimo/_save/stores/store.py@@ -0,0 +1,39 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from abc import ABC, abstractmethod+from typing import TYPE_CHECKING, Optional++from marimo._save.cache import (+ Cache,+)++if TYPE_CHECKING:+ from marimo._save.hash import HashKey+ from marimo._save.loaders import BasePersistenceLoader as Loader+++class Store(ABC):+ _instance = None++ # Singleton+ def __new__(cls) -> Store:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ # Put any initialization here.+ return cls._instance++ @abstractmethod+ def get(self, key: HashKey, loader: Loader) -> Optional[bytes]:+ """Get the bytes of a cache from the store"""++ @abstractmethod+ def put(self, cache: Cache, loader: Loader) -> None:+ """Put a cache into the store"""++ @abstractmethod+ def hit(self, key: HashKey, loader: Loader) -> bool:+ """Check if the cache is in the store"""+++StoreType = type[Store]diff --git a/pyproject.toml b/pyproject.tomlindex a760822574..564008e0b2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -197,6 +197,7 @@ dependencies = ["types-Pillow~=10.2.0.20240520","types-Pygments~=2.18.0.20240506","types-psutil~=5.9.5.20240516",+ "types-redis~=4.6.0.20241004","types-Markdown~=3.6.0.20240316","types-PyYAML~=6.0.12.20240808",]@@ -437,6 +438,7 @@ banned-module-level-imports = ["ipython","anywidget","packaging",+ "redis","typing_extensions",]diff --git a/tests/_save/cache-dumps/json-dump-v1/E_77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY.json b/tests/_save/cache-dumps/json-dump-v1/E_77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY.jsonnew file mode 100644index 0000000000..15852a41ed--- /dev/null+++ b/tests/_save/cache-dumps/json-dump-v1/E_77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY.json@@ -0,0 +1,12 @@+{+ "defs": {+ "value": 3+ },+ "hash": "77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY",+ "cache_type": "ExecutionPath",+ "stateful_refs": [],+ "hit": false,+ "meta": {+ "version": 2+ }+}diff --git a/tests/_save/cache-dumps/json-dump-v2/E_JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE.json b/tests/_save/cache-dumps/json-dump-v2/E_JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE.jsonnew file mode 100644index 0000000000..471b17f452--- /dev/null+++ b/tests/_save/cache-dumps/json-dump-v2/E_JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE.json@@ -0,0 +1,12 @@+{+ "defs": {+ "value": 2+ },+ "hash": "JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE",+ "cache_type": "ExecutionPath",+ "stateful_refs": [],+ "hit": false,+ "meta": {+ "version": 1+ }+}diff --git a/tests/_save/cache-dumps/pickle-dump-v1/E_77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY.pickle b/tests/_save/cache-dumps/pickle-dump-v1/E_77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY.picklenew file mode 100644index 0000000000..348a1fb78dBinary files /dev/null and b/tests/_save/cache-dumps/pickle-dump-v1/E_77bl8j6jcyv_Lupfe4-wtT2LqVfhlYmtdEIjF3dY3pY.pickle differdiff --git a/tests/_save/cache-dumps/pickle-dump-v2/E_JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE.pickle b/tests/_save/cache-dumps/pickle-dump-v2/E_JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE.picklenew file mode 100644index 0000000000..dff683157bBinary files /dev/null and b/tests/_save/cache-dumps/pickle-dump-v2/E_JM3zJ46ZRk9AC7fTCdAB9LsFUCZMcfLp-cDvUsidAsE.pickle differdiff --git a/tests/_save/mocks.py b/tests/_save/loaders/mocks.pysimilarity index 61%rename from tests/_save/mocks.pyrename to tests/_save/loaders/mocks.pyindex d84e8dc380..e2f7d26a1e 100644--- a/tests/_save/mocks.py+++ b/tests/_save/loaders/mocks.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom typing import Any, Optional-from marimo._save.cache import Cache, CacheType+from marimo._save.cache import Cachefrom marimo._save.loaders import Loader@@ -13,6 +13,7 @@ class MockLoader(Loader):save_path: str = "",data: Optional[dict[str, Any]] = None,stateful_refs: Optional[set[str]] = None,+ config_value: Any = None,) -> None:self.save_path = save_pathself._data = data or {}@@ -20,21 +21,25 @@ class MockLoader(Loader):self._loaded = Falseself._saved = Falseself._stateful_refs = stateful_refs or set()+ self.config_value = config_valuesuper().__init__(name)- def cache_hit(self, _hashed_context: str, _cache_type: CacheType) -> bool:+ def cache_hit(self, _) -> bool:return self._cache_hit- def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:+ def load_cache(self, key) -> Optional[Cache]:+ if not self._cache_hit:+ return Noneself._loaded = Truereturn Cache(- self._data,- hashed_context,- self._stateful_refs,- cache_type,- True,- {},+ defs=self._data,+ hash=key.hash,+ cache_type=key.cache_type,+ stateful_refs=self._stateful_refs,+ hit=True,+ meta={},)def save_cache(self, _cache: Cache) -> None:self._saved = True+ self._cache_hit = Truediff --git a/tests/_save/loaders/test_json_loader.py b/tests/_save/loaders/test_json_loader.pydeleted file mode 100644index fef7e60ad8..0000000000--- a/tests/_save/loaders/test_json_loader.py+++ /dev/null@@ -1,205 +0,0 @@-# Copyright 2024 Marimo. All rights reserved.-import json-import os-import tempfile-from pathlib import Path--import pytest--from marimo._save.cache import Cache-from marimo._save.loaders.json import JsonLoader-from marimo._save.loaders.loader import LoaderError---class TestJsonLoader:- def setup_method(self) -> None:- """Set up a temporary directory for each test."""- self.temp_dir = tempfile.TemporaryDirectory()- self.save_path = self.temp_dir.name-- def teardown_method(self) -> None:- """Clean up the temporary directory."""- self.temp_dir.cleanup()-- def test_init(self) -> None:- """Test initialization."""- loader = JsonLoader("test", self.save_path)- assert loader.name == "test"- assert loader.suffix == "json"- assert Path(str(loader.save_path)).name == "test"-- # Check that the directory was created- assert os.path.exists(os.path.join(self.save_path, "test"))-- def test_build_path(self) -> None:- """Test building the path for a cache file."""- loader = JsonLoader("test", self.save_path)- path = loader.build_path("hash1", "Pure")- assert str(path).endswith("P_hash1.json")-- path = loader.build_path("hash2", "Deferred")- assert str(path).endswith("D_hash2.json")-- def test_cache_hit_miss(self) -> None:- """Test cache hit and miss."""- loader = JsonLoader("test", self.save_path)-- # No file exists yet- assert not loader.cache_hit("hash1", "Pure")-- # Create a cache file- cache_path = loader.build_path("hash1", "Pure")-- # Create a valid JSON cache- cache_dict = {- "defs": {"var1": "value1"},- "hash": "hash1",- "stateful_refs": [],- "cache_type": "Pure",- "hit": True,- "meta": {},- }-- with open(cache_path, "w") as f:- json.dump(cache_dict, f)-- # Now it should hit- assert loader.cache_hit("hash1", "Pure")-- # Different hash should miss- assert not loader.cache_hit("hash2", "Pure")-- # Different cache type should miss- assert not loader.cache_hit("hash1", "Deferred")-- # Empty file should miss- empty_path = loader.build_path("empty", "Pure")- with open(empty_path, "w") as f:- pass- assert not loader.cache_hit("empty", "Pure")-- def test_load_persistent_cache(self) -> None:- """Test loading a persistent cache."""- loader = JsonLoader("test", self.save_path)-- # Create a cache file- cache_path = loader.build_path("hash1", "Pure")-- # Create a valid JSON cache- cache_dict = {- "defs": {"var1": "value1"},- "hash": "hash1",- "stateful_refs": [],- "cache_type": "Pure",- "hit": True,- "meta": {},- }-- with open(cache_path, "w") as f:- json.dump(cache_dict, f)-- # Load the cache- loaded_cache = loader.load_persistent_cache("hash1", "Pure")- assert loaded_cache.hash == "hash1"- assert loaded_cache.cache_type == "Pure"- assert loaded_cache.hit is True- assert isinstance(loaded_cache.stateful_refs, set)-- # Should raise for non-existent cache- with pytest.raises(FileNotFoundError):- loader.load_persistent_cache("nonexistent", "Pure")-- # Test with invalid JSON- invalid_path = loader.build_path("invalid", "Pure")- with open(invalid_path, "w") as f:- f.write("not valid json")-- with pytest.raises(json.JSONDecodeError):- loader.load_persistent_cache("invalid", "Pure")-- # Test with missing required fields- missing_fields_path = loader.build_path("missing", "Pure")- with open(missing_fields_path, "w") as f:- json.dump({"hash": "missing", "stateful_refs": []}, f)-- with pytest.raises(LoaderError, match="Invalid json object"):- loader.load_persistent_cache("missing", "Pure")-- def test_load_cache(self) -> None:- """Test the load_cache method."""- loader = JsonLoader("test", self.save_path)-- # Create a cache file- cache_path = loader.build_path("hash1", "Pure")-- # Create a valid JSON cache- cache_dict = {- "defs": {"var1": "value1"},- "hash": "hash1",- "stateful_refs": [],- "cache_type": "Pure",- "hit": True,- "meta": {},- }-- with open(cache_path, "w") as f:- json.dump(cache_dict, f)-- # Load the cache- loaded_cache = loader.load_cache("hash1", "Pure")- assert loaded_cache.hash == "hash1"-- # Should raise for non-existent cache- with pytest.raises(LoaderError, match="Unexpected cache miss"):- loader.load_cache("nonexistent", "Pure")-- def test_save_cache(self) -> None:- """Test saving a cache."""- loader = JsonLoader("test", self.save_path)-- # Create a cache with a stateful reference- cache = Cache(- {"var1": "value1"},- "hash1",- {"stateful"},- "Pure",- True,- {"version": 1},- )-- # Save the cache- loader.save_cache(cache)-- # Verify the file was created- cache_path = loader.build_path("hash1", "Pure")- assert os.path.exists(cache_path)-- # Load the JSON and verify contents- with open(cache_path) as f:- loaded_json = json.load(f)-- assert loaded_json["hash"] == "hash1"- assert loaded_json["cache_type"] == "Pure"- assert loaded_json["hit"] is True- assert isinstance(- loaded_json["stateful_refs"], list- ) # Should be converted to list- assert loaded_json["meta"] == {"version": 1}-- # Save another cache with different type- cache2 = Cache(- {"var2": "value2"}, "hash2", set(), "Deferred", True, {}- )-- loader.save_cache(cache2)-- # Verify the second file was created- cache2_path = loader.build_path("hash2", "Deferred")- assert os.path.exists(cache2_path)-- # Load the second JSON and verify contents- with open(cache2_path) as f:- loaded_json2 = json.load(f)-- assert loaded_json2["hash"] == "hash2"- assert loaded_json2["cache_type"] == "Deferred"diff --git a/tests/_save/loaders/test_loader.py b/tests/_save/loaders/test_loader.pyindex 91313eb7c7..e8ce3df281 100644--- a/tests/_save/loaders/test_loader.py+++ b/tests/_save/loaders/test_loader.py@@ -1,56 +1,27 @@# Copyright 2024 Marimo. All rights reserved.++import json+import os+import pickle+import tempfile+from abc import ABC, abstractmethodfrom pathlib import Pathimport pytestfrom marimo._save.cache import Cache+from marimo._save.hash import HashKey+from marimo._save.loaders import JsonLoader, MemoryLoader, PickleLoaderfrom marimo._save.loaders.loader import (BasePersistenceLoader,Loader,- LoaderError,LoaderPartial,)+from tests._save.loaders.mocks import MockLoader-# Mock loader for testing-class MockLoader(Loader):- def __init__(self, name: str, config_value: str = "default") -> None:- super().__init__(name)- self.config_value = config_value- self.saved_caches: dict[str, Cache] = {}-- def cache_hit(self, hashed_context: str, cache_type: str) -> bool:- key = f"{cache_type}_{hashed_context}"- return key in self.saved_caches-- def load_cache(self, hashed_context: str, cache_type: str) -> Cache:- key = f"{cache_type}_{hashed_context}"- if key not in self.saved_caches:- raise LoaderError("Unexpected cache miss.")- return self.saved_caches[key]-- def save_cache(self, cache: Cache) -> None:- key = f"{cache.cache_type}_{cache.hash}"- self.saved_caches[key] = cache---# Mock persistence loader for testing-class MockPersistenceLoader(BasePersistenceLoader):- def __init__(self, name: str, save_path: str) -> None:- super().__init__(name, "mock", save_path)- self.saved_caches: dict[str, Cache] = {}-- def load_persistent_cache(- self, hashed_context: str, cache_type: str- ) -> Cache:- key = f"{cache_type}_{hashed_context}"- if key not in self.saved_caches:- raise FileNotFoundError(f"No cache found for {key}")- return self.saved_caches[key]-- def save_cache(self, cache: Cache) -> None:- key = f"{cache.cache_type}_{cache.hash}"- self.saved_caches[key] = cache+def key(a, b):+ return HashKey(a, b)class TestLoaderPartial:@@ -77,63 +48,13 @@ class TestLoaderPartial:partial("test_name")-class TestLoader:- def test_build_path(self) -> None:- """Test building a path from hash and cache type."""- loader = MockLoader("test")-- path = loader.build_path("hash1", "Pure")- assert str(path) == "P_hash1"-- path = loader.build_path("hash2", "Deferred")- assert str(path) == "D_hash2"-- def test_cache_attempt_miss(self) -> None:- """Test cache attempt with a miss."""- loader = MockLoader("test")- defs = {"var1"}- stateful_refs: set[str] = set()-- cache = loader.cache_attempt(defs, "hash1", stateful_refs, "Pure")-- assert cache.hash == "hash1"- assert cache.hit is False- assert cache.cache_type == "Pure"- assert set(cache.defs.keys()) == defs- assert all(value is None for value in cache.defs.values())-- def test_cache_attempt_hit(self) -> None:- """Test cache attempt with a hit."""- loader = MockLoader("test")- defs = {"var1"}- stateful_refs: set[str] = set()-- # Create and save a cache- original_cache = Cache(- {"var1": "value1"},- "hash1",- stateful_refs,- "Pure",- True,- {"version": 1},- )- loader.saved_caches["Pure_hash1"] = original_cache-- # Attempt to load the cache- cache = loader.cache_attempt(defs, "hash1", stateful_refs, "Pure")+class ABCTestLoader(ABC):+ save_path = None+ suffix = None+ value = None- assert cache.hash == "hash1"- assert cache.hit is True- assert cache.cache_type == "Pure"- assert cache.defs["var1"] == "value1"- assert cache.meta == {"version": 1}---class TestBasePersistenceLoader:def setup_method(self) -> None:"""Set up a temporary directory for each test."""- import tempfile-self.temp_dir = tempfile.TemporaryDirectory()self.save_path = self.temp_dir.name@@ -141,54 +62,129 @@ class TestBasePersistenceLoader:"""Clean up the temporary directory."""self.temp_dir.cleanup()+ def instance(self) -> Loader:+ if self.value is None:+ self.value = self._instance()+ return self.value+def test_init(self) -> None:"""Test initialization."""- loader = MockPersistenceLoader("test", self.save_path)+ loader = self.instance()assert loader.name == "test"- assert loader.suffix == "mock"- assert Path(str(loader.save_path)).name == "test"+ if self.suffix:+ assert loader.suffix == self.suffix+ if isinstance(loader, BasePersistenceLoader):+ assert Path(str(loader.save_path)).name == "test"+ # Check that the directory was created+ assert os.path.exists(loader.save_path)++ def test_build_path(self) -> None:+ """Test building the path for a cache file."""+ loader = self.instance()+ path = loader.build_path(key("hash1", "Pure"))+ suffix = f".{self.suffix}" if self.suffix else ""+ assert str(path).endswith(f"P_hash1{suffix}")- # Check that the directory was created- assert Path(self.save_path, "test").exists()+ path = loader.build_path(key("hash2", "Deferred"))+ assert str(path).endswith(f"D_hash2{suffix}")- def test_cache_hit(self) -> None:- """Test cache hit detection."""- loader = MockPersistenceLoader("test", self.save_path)+ def test_cache_hit_miss(self) -> None:+ """Test cache hit and miss."""+ loader = self.instance()- # No cache exists yet- assert not loader.cache_hit("hash1", "Pure")+ # No file exists yet+ assert not loader.cache_hit(key("hash1", "Pure"))- # Create a cache file (just a placeholder file)- cache_path = loader.build_path("hash1", "Pure")- with open(cache_path, "w") as f:- f.write("placeholder")+ # Create a cache file+ cache_path = loader.build_path(key("hash1", "Pure"))++ # Create a valid JSON cache+ self.seed_cache()# Now it should hit- assert loader.cache_hit("hash1", "Pure")+ assert (+ loader.cache_attempt({"var1"}, key("hash1", "Pure"), set())+ is not None+ )# Different hash should miss- assert not loader.cache_hit("hash2", "Pure")+ assert not loader.cache_hit(key("hash2", "Pure"))# Different cache type should miss- assert not loader.cache_hit("hash1", "Deferred")+ assert not loader.cache_hit(key("hash1", "Deferred"))++ # Empty file should miss+ empty_path = loader.build_path(key("empty", "Pure"))+ with open(empty_path, "w") as f:+ pass+ assert not loader.cache_hit(key("empty", "Pure"))++ assert loader.hits == 1++ @abstractmethod+ def _instance(self) -> Loader:+ pass++ @abstractmethod+ def seed_cache(self) -> None:+ pass+++class TestMemoryLoader(ABCTestLoader):+ def _instance(self) -> Loader:+ return MemoryLoader("test")++ def seed_cache(self) -> None:+ cache_path = self.instance().build_path(key("hash1", "Pure"))+ self.instance()._cache[cache_path] = Cache(+ defs={"var1": "value1"},+ hash="hash1",+ cache_type="Pure",+ stateful_refs=set(),+ hit=True,+ meta={},+ )- def test_load_cache(self) -> None:- """Test the load_cache method."""- loader = MockPersistenceLoader("test", self.save_path)- # Create and save a cache- cache = Cache({"var1": "value1"}, "hash1", set(), "Pure", True, {})- loader.saved_caches["Pure_hash1"] = cache+class TestJsonLoader(ABCTestLoader):+ suffix = "json"++ def _instance(self) -> Loader:+ return JsonLoader("test", self.save_path)++ def seed_cache(self):+ cache_path = self.instance().build_path(key("hash1", "Pure"))+ cache_dict = {+ "defs": {"var1": "value1"},+ "key": {+ "hash": "hash1",+ "cache_type": "Pure",+ },+ "stateful_refs": [],+ "hit": True,+ "meta": {},+ }- # Create a placeholder file to trigger cache_hit- cache_path = loader.build_path("hash1", "Pure")with open(cache_path, "w") as f:- f.write("placeholder")+ json.dump(cache_dict, f)+- # Load the cache- loaded_cache = loader.load_cache("hash1", "Pure")- assert loaded_cache.hash == "hash1"+class TestPickleLoader(ABCTestLoader):+ suffix = "pickle"++ def _instance(self) -> Loader:+ return PickleLoader("test", self.save_path)++ def seed_cache(self) -> None:+ cache_path = self.instance().build_path(key("hash1", "Pure"))+ cache = Cache(+ defs={"var1": "value1"},+ hash="hash1",+ cache_type="Pure",+ stateful_refs=set(),+ hit=True,+ meta={},+ )- # Should raise for non-existent cache- with pytest.raises(LoaderError, match="Unexpected cache miss"):- loader.load_cache("nonexistent", "Pure")+ with open(cache_path, "wb") as f:+ pickle.dump(cache, f)diff --git a/tests/_save/loaders/test_memory_loader.py b/tests/_save/loaders/test_memory_loader.pydeleted file mode 100644index 3cba772447..0000000000--- a/tests/_save/loaders/test_memory_loader.py+++ /dev/null@@ -1,199 +0,0 @@-# Copyright 2024 Marimo. All rights reserved.-from collections import OrderedDict--import pytest--from marimo._save.cache import Cache-from marimo._save.loaders.loader import LoaderError-from marimo._save.loaders.memory import MemoryLoader---class TestMemoryLoader:- def test_init_default(self) -> None:- """Test default initialization."""- loader = MemoryLoader("test")- assert loader.name == "test"- assert loader.max_size == 128- assert loader.is_lru is True- assert isinstance(loader._cache, OrderedDict)- assert loader._cache_lock is not None-- def test_init_with_max_size_zero(self) -> None:- """Test initialization with max_size=0."""- loader = MemoryLoader("test", max_size=0)- assert loader.max_size == 0- assert loader.is_lru is False- assert not isinstance(loader._cache, OrderedDict)- assert loader._cache_lock is None-- def test_init_with_custom_cache(self) -> None:- """Test initialization with a custom cache."""- custom_cache = OrderedDict()- loader = MemoryLoader("test", cache=custom_cache)- assert id(loader._cache) != id(- custom_cache- ) # Should be a copy, not the same instance- assert len(loader._cache) == 0-- def test_cache_hit_miss(self) -> None:- """Test cache hit and miss."""- loader = MemoryLoader("test")- assert not loader.cache_hit("hash1", "Pure")-- # Create and save a cache- # Use string directly instead of Name constructor- stateful_refs = set()- cache = Cache(- {"var1": "value1"}, "hash1", stateful_refs, "Pure", True, {}- )- loader.save_cache(cache)-- # Now it should hit- assert loader.cache_hit("hash1", "Pure")- # Different hash should miss- assert not loader.cache_hit("hash2", "Pure")- # Different cache type should miss- assert not loader.cache_hit("hash1", "Deferred")-- def test_load_cache(self) -> None:- """Test loading a cache."""- loader = MemoryLoader("test")-- # Create and save a cache- # Use string directly instead of Name constructor- stateful_refs = set()- cache = Cache(- {"var1": "value1"}, "hash1", stateful_refs, "Pure", True, {}- )- loader.save_cache(cache)-- # Load the cache- loaded_cache = loader.load_cache("hash1", "Pure")- assert loaded_cache.hash == "hash1"- assert loaded_cache.cache_type == "Pure"- assert loaded_cache.hit is True-- # Should raise for non-existent cache- with pytest.raises(LoaderError, match="Unexpected cache miss"):- loader.load_cache("nonexistent", "Pure")-- def test_save_cache(self) -> None:- """Test saving a cache."""- loader = MemoryLoader("test")-- # Create and save a cache- cache = Cache({"var1": "value1"}, "hash1", set(), "Pure", True, {})- loader.save_cache(cache)-- # Verify it was saved- assert loader.cache_hit("hash1", "Pure")-- # Save another cache with the same hash but different type- cache2 = Cache(- {"var2": "value2"}, "hash1", set(), "Deferred", True, {}- )- loader.save_cache(cache2)-- # Both should be accessible- assert loader.cache_hit("hash1", "Pure")- assert loader.cache_hit("hash1", "Deferred")-- def test_lru_eviction(self) -> None:- """Test LRU cache eviction."""- loader = MemoryLoader("test", max_size=2)-- # Create and save 3 caches- for i in range(3):- # Use string directly instead of Name constructor- cache = Cache(- {f"var{i}": f"value{i}"}, f"hash{i}", set(), "Pure", True, {}- )- loader.save_cache(cache)-- # The first one should be evicted- assert not loader.cache_hit("hash0", "Pure")- assert loader.cache_hit("hash1", "Pure")- assert loader.cache_hit("hash2", "Pure")-- # Access hash1 to move it to the end of the LRU- loader.load_cache("hash1", "Pure")-- # Add another cache- cache = Cache({"var3": "value3"}, "hash3", set(), "Pure", True, {})- loader.save_cache(cache)-- # hash2 should now be evicted- assert not loader.cache_hit("hash0", "Pure")- assert loader.cache_hit("hash1", "Pure")- assert not loader.cache_hit("hash2", "Pure")- assert loader.cache_hit("hash3", "Pure")-- def test_resize(self) -> None:- """Test resizing the cache."""- loader = MemoryLoader("test", max_size=3)-- # Create and save 3 caches- for i in range(3):- # Use string directly instead of Name constructor- cache = Cache(- {f"var{i}": f"value{i}"}, f"hash{i}", set(), "Pure", True, {}- )- loader.save_cache(cache)-- # All should be present- for i in range(3):- assert loader.cache_hit(f"hash{i}", "Pure")-- # Resize to 1- loader.resize(1)- assert loader.max_size == 1-- # Only the most recently used should remain- assert not loader.cache_hit("hash0", "Pure")- assert not loader.cache_hit("hash1", "Pure")- assert loader.cache_hit("hash2", "Pure")-- # Resize to 0 (disable LRU)- loader.resize(0)- assert loader.max_size == 0- assert not loader.is_lru- assert not isinstance(loader._cache, OrderedDict)- # The implementation might not set _cache_lock to None, so we don't test that-- # The cache should still be accessible- assert loader.cache_hit("hash2", "Pure")-- # Add a new cache- cache = Cache({"var4": "value4"}, "hash4", set(), "Pure", True, {})- loader.save_cache(cache)-- # Both should be accessible (no eviction)- assert loader.cache_hit("hash2", "Pure")- assert loader.cache_hit("hash4", "Pure")-- # Re-enable LRU with max_size=1- loader.resize(1)- assert loader.max_size == 1- assert loader.is_lru- assert isinstance(loader._cache, OrderedDict)- assert loader._cache_lock is not None-- # After re-enabling LRU, both caches might still be present- # The implementation doesn't automatically evict entries when resizing- assert loader.cache_hit("hash4", "Pure")- # We don't assert on the exact cache size as it depends on implementation details-- def test_max_size_property(self) -> None:- """Test the max_size property."""- loader = MemoryLoader("test", max_size=3)- assert loader.max_size == 3-- # Change max_size- loader.max_size = 1- assert loader.max_size == 1- assert loader.is_lru is True-- # Disable LRU- loader.max_size = 0- assert loader.max_size == 0- assert loader.is_lru is Falsediff --git a/tests/_save/loaders/test_pickle_loader.py b/tests/_save/loaders/test_pickle_loader.pydeleted file mode 100644index dc9824189b..0000000000--- a/tests/_save/loaders/test_pickle_loader.py+++ /dev/null@@ -1,156 +0,0 @@-# Copyright 2024 Marimo. All rights reserved.-import os-import pickle-import tempfile-from pathlib import Path--import pytest--from marimo._save.cache import Cache-from marimo._save.loaders.loader import LoaderError-from marimo._save.loaders.pickle import PickleLoader---class TestPickleLoader:- def setup_method(self) -> None:- """Set up a temporary directory for each test."""- self.temp_dir = tempfile.TemporaryDirectory()- self.save_path = self.temp_dir.name-- def teardown_method(self) -> None:- """Clean up the temporary directory."""- self.temp_dir.cleanup()-- def test_init(self) -> None:- """Test initialization."""- loader = PickleLoader("test", self.save_path)- assert loader.name == "test"- assert loader.suffix == "pickle"- assert Path(str(loader.save_path)).name == "test"-- # Check that the directory was created- assert os.path.exists(os.path.join(self.save_path, "test"))-- def test_build_path(self) -> None:- """Test building the path for a cache file."""- loader = PickleLoader("test", self.save_path)- path = loader.build_path("hash1", "Pure")- assert str(path).endswith("P_hash1.pickle")-- path = loader.build_path("hash2", "Deferred")- assert str(path).endswith("D_hash2.pickle")-- def test_cache_hit_miss(self) -> None:- """Test cache hit and miss."""- loader = PickleLoader("test", self.save_path)-- # No file exists yet- assert not loader.cache_hit("hash1", "Pure")-- # Create a cache file- cache_path = loader.build_path("hash1", "Pure")- cache = Cache({"var1": "value1"}, "hash1", set(), "Pure", True, {})-- with open(cache_path, "wb") as f:- pickle.dump(cache, f)-- # Now it should hit- assert loader.cache_hit("hash1", "Pure")-- # Different hash should miss- assert not loader.cache_hit("hash2", "Pure")-- # Different cache type should miss- assert not loader.cache_hit("hash1", "Deferred")-- # Empty file should miss- empty_path = loader.build_path("empty", "Pure")- with open(empty_path, "wb") as f:- pass- assert not loader.cache_hit("empty", "Pure")-- def test_load_persistent_cache(self) -> None:- """Test loading a persistent cache."""- loader = PickleLoader("test", self.save_path)-- # Create a cache file- cache_path = loader.build_path("hash1", "Pure")- # Use string directly instead of Name constructor- original_cache = Cache(- {"var1": "value1"}, "hash1", set(), "Pure", True, {}- )-- with open(cache_path, "wb") as f:- pickle.dump(original_cache, f)-- # Load the cache- loaded_cache = loader.load_persistent_cache("hash1", "Pure")- assert loaded_cache.hash == "hash1"- assert loaded_cache.cache_type == "Pure"- assert loaded_cache.hit is True-- # Should raise for non-existent cache- with pytest.raises(FileNotFoundError):- loader.load_persistent_cache("nonexistent", "Pure")-- # Test with invalid cache object- invalid_path = loader.build_path("invalid", "Pure")- with open(invalid_path, "wb") as f:- pickle.dump("not a cache", f)-- with pytest.raises(LoaderError, match="Excepted cache object"):- loader.load_persistent_cache("invalid", "Pure")-- def test_load_cache(self) -> None:- """Test the load_cache method."""- loader = PickleLoader("test", self.save_path)-- # Create a cache file- cache_path = loader.build_path("hash1", "Pure")- # Use string directly instead of Name constructor- original_cache = Cache(- {"var1": "value1"}, "hash1", set(), "Pure", True, {}- )-- with open(cache_path, "wb") as f:- pickle.dump(original_cache, f)-- # Load the cache- loaded_cache = loader.load_cache("hash1", "Pure")- assert loaded_cache.hash == "hash1"-- # Should raise for non-existent cache- with pytest.raises(LoaderError, match="Unexpected cache miss"):- loader.load_cache("nonexistent", "Pure")-- def test_save_cache(self) -> None:- """Test saving a cache."""- loader = PickleLoader("test", self.save_path)-- # Create a cache- cache = Cache({"var1": "value1"}, "hash1", set(), "Pure", True, {})-- # Save the cache- loader.save_cache(cache)-- # Verify the file was created- cache_path = loader.build_path("hash1", "Pure")- assert os.path.exists(cache_path)-- # Load the cache and verify contents- with open(cache_path, "rb") as f:- loaded_cache = pickle.load(f)-- assert loaded_cache.hash == "hash1"- assert loaded_cache.cache_type == "Pure"-- # Save another cache with different type- cache2 = Cache(- {"var2": "value2"}, "hash2", set(), "Deferred", True, {}- )-- loader.save_cache(cache2)-- # Verify the second file was created- cache2_path = loader.build_path("hash2", "Deferred")- assert os.path.exists(cache2_path)diff --git a/tests/_save/store/mocks.py b/tests/_save/store/mocks.pynew file mode 100644index 0000000000..1f90a0344a--- /dev/null+++ b/tests/_save/store/mocks.py@@ -0,0 +1,25 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any, Optional++from marimo._save.stores import Store++if TYPE_CHECKING:+ from marimo._save.cache import Cache+ from marimo._save.hash import HashKey+ from marimo._save.loaders import Loader+++class MockStore(Store):+ def __init__(self) -> None:+ super().__init__()+ self._cache: dict[str, Any] = {}++ def get(self, key: HashKey, _loader: Loader) -> Optional[bytes]:+ return self._cache.get(key.hash, None)++ def put(self, cache: Cache, _loader: Loader) -> None:+ self._cache[cache.key.hash] = cache++ def hit(self, key: HashKey, _loader: Loader) -> bool:+ return key in self._cachediff --git a/tests/_save/store/test_store.py b/tests/_save/store/test_store.pynew file mode 100644index 0000000000..2ed7974183--- /dev/null+++ b/tests/_save/store/test_store.py@@ -0,0 +1,25 @@+# Copyright 2024 Marimo. All rights reserved.++from __future__ import annotations++from marimo._ast.app import App+++class TestStore:+ def test_store(self, app: App) -> None:+ @app.cell+ def _():+ import marimo as mo+ from tests._save.store.mocks import MockStore++ store = MockStore()+ return store, mo++ @app.cell+ def _(mo, store):+ assert store._cache == {}+ with mo.persistent_cache("mock", store=store) as cache:+ a = 1+ b = 2++ assert store._cache[cache._cache.key.hash]diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 25896b1763..9d81e994fa 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -24,7 +24,7 @@ class TestScriptCache:def one() -> tuple[int]:# Check top level importfrom marimo import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader()) as cache:Y = 8@@ -52,7 +52,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader(data={"X": 7, "Y": 8})@@ -69,7 +69,7 @@ class TestScriptCache:def test_cache_loader_api(app) -> None:@app.celldef one() -> tuple[int]:- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith MockLoader.cache("one", data={"X": 7, "Y": 8}) as cache:Y = 9@@ -85,7 +85,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader# fmt: offwith persistent_cache(name="one",@@ -106,7 +106,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()# fmt: off@@ -124,7 +124,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()# fmt: off@@ -142,7 +142,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()b = 2@@ -156,7 +156,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()if False:@@ -171,7 +171,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()if False:@@ -193,7 +193,7 @@ class TestScriptCache:yield 1from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()with called(True):@@ -213,7 +213,7 @@ class TestScriptCache:yield 1from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()with persistent_cache("else", _loader=_loader):@@ -234,7 +234,7 @@ class TestScriptCache:assert vfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()# fmt: off@@ -254,7 +254,7 @@ class TestScriptCache:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader_loader = MockLoader()@@ -278,7 +278,7 @@ class TestAppCache:code=textwrap.dedent("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader()@@ -304,7 +304,7 @@ class TestAppCache:code=textwrap.dedent("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader(data={"X": 7, "Y": 8})@@ -330,7 +330,7 @@ class TestAppCache:code=textwrap.dedent("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader(data={"X": 1})):X = 1@@ -354,7 +354,7 @@ class TestAppCache:code=textwrap.dedent("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader()):# Comment@@ -395,7 +395,7 @@ class TestStateCache:exec_req.get("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="cache", _loader=MockLoader()@@ -425,7 +425,7 @@ class TestStateCache:exec_req.get("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="cache", _loader=MockLoader(),@@ -458,7 +458,7 @@ class TestStateCache:exec_req.get("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="cache", _loader=MockLoader()@@ -493,7 +493,7 @@ class TestStateCache:exec_req.get("""from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="cache",@@ -1478,7 +1478,7 @@ class TestPersistentCache:assert _b == 1assert not cache._cache.hitassert cache._cache.meta["version"] == mo._save.MARIMO_CACHE_VERSION- assert os.path.exists(tmp_path_fixture / "basic" / f"P_{cache._cache.hash}.pickle")+ #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:@@ -1486,7 +1486,7 @@ class TestPersistentCache:assert _b == 1assert cache_2._cache.hitassert cache._cache.hash == cache_2._cache.hash- assert os.path.exists(tmp_path_fixture / "basic" / f"P_{cache._cache.hash}.pickle")+ #assert os.path.exists(tmp_path_fixture / "basic" / f"P_{cache._cache.hash}.pickle")"""),])@@ -1513,7 +1513,7 @@ class TestPersistentCache:_b = 1assert _b == 1assert not json_cache._cache.hit- assert os.path.exists(tmp_path_fixture / "json" / f"P_{json_cache._cache.hash}.json")+ #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:@@ -1521,7 +1521,7 @@ class TestPersistentCache:assert _b == 1assert json_cache_2._cache.hitassert 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 os.path.exists(tmp_path_fixture / "json" / f"P_{json_cache._cache.hash}.json")"""),])diff --git a/tests/_save/test_cache_versions.py b/tests/_save/test_cache_versions.pynew file mode 100644index 0000000000..55862ba37a--- /dev/null+++ b/tests/_save/test_cache_versions.py@@ -0,0 +1,52 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import pytest+++class TestVersionCache:+ @staticmethod+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_load_v1_pickle(app) -> None:+ @app.cell+ def _():+ unhashable = [object()]++ @app.cell+ def v1(unhashable) -> tuple[int]:+ # Check top level import+ from marimo import persistent_cache++ ref = 1+ with persistent_cache(+ name="pickle-dump-v1", save_path="tests/_save/cache-dumps"+ ) as cache:+ value = 1 + len(unhashable) + ref+ assert cache.hit+ assert value == 3++ @staticmethod+ @pytest.mark.skipif(+ "sys.version_info < (3, 12) or sys.version_info >= (3, 13)"+ )+ def test_load_v1_json(app) -> None:+ @app.cell+ def _():+ unhashable = [object()]++ @app.cell+ def v1(unhashable) -> tuple[int]:+ # Check top level import+ from marimo import persistent_cache++ ref = 1+ with persistent_cache(+ name="json-dump-v1",+ save_path="tests/_save/cache-dumps",+ method="json",+ ) as cache:+ value = 1 + len(unhashable) + ref+ assert cache.hit+ assert value == 3diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 298e030d07..db5f590388 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -15,7 +15,7 @@ class TestHash:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderwith persistent_cache(name="one", _loader=MockLoader()) as cache:Y = [1, 2, 3]@@ -28,7 +28,7 @@ class TestHash:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoadera = 1with persistent_cache(name="one", _loader=MockLoader()) as cache:@@ -45,7 +45,7 @@ class TestHash:@app.celldef load() -> tuple[Any]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "haIqC9yzlTaNo-ClmY11Kvtiv08oQPz3-SlnOLfhJYM"@@ -85,7 +85,7 @@ class TestHash:@app.celldef one() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoadernon_primitive = [object()]@@ -103,12 +103,16 @@ class TestHash:app._pytest_rewrite = False@app.cell- def load() -> tuple[int]:+ def imports() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader++ return persistent_cache, MockLoader+ @app.cell+ def load() -> tuple[int]:shared = [None, object()]- return persistent_cache, MockLoader, shared+ return shared@app.celldef one(persistent_cache, MockLoader, shared) -> tuple[int]:@@ -121,7 +125,7 @@ class TestHash:# Cannot be reused/ shared, because it will change the hash.assert (_cache._cache.hash- == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"+ == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"return@@ -142,7 +146,7 @@ class TestHash:assert _X == 7assert (_cache._cache.hash- == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"+ == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"# and a post block difference@@ -169,7 +173,7 @@ class TestHash:# Cannot be reused/ shared, because it will change the hash.assert (_cache._cache.hash- == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"+ == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"return@@ -190,7 +194,7 @@ class TestHash:assert _X == 7assert (_cache._cache.hash- == "b7qDaJXGI0uohd9Q5llsyggPCtEW9dTM7Dt2ZtuuqCs"+ == "jjufTYhiG11S6Fe3odSETSvYbYObdSRZDYhWXFlCaXE"), _cache._cache.hashassert _cache._cache.cache_type == "ContextExecutionPath"# and a post block difference@@ -198,19 +202,23 @@ class TestHash:return (Z,)@app.cell- def load() -> tuple[int]:+ def imports() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoader++ return persistent_cache, MockLoader+ @app.cell+ def load() -> tuple[int]:shared = [None, object()]- return persistent_cache, MockLoader, shared+ return shared@staticmethoddef test_transitive_content_hash(app) -> None:@app.celldef load() -> tuple[int]:from marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoadershared = [None, object()]return persistent_cache, MockLoader, shared@@ -229,7 +237,7 @@ class TestHash:def load() -> tuple[Any]:import marimo as mofrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderslider = mo.ui.slider(1, 10)@@ -260,7 +268,7 @@ class TestHash:def load() -> tuple[Any]:import marimo as mofrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderstate, set_state = mo.state(0)@@ -315,7 +323,7 @@ class TestHash:def load() -> tuple[Any]:import marimo as mofrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderstate, set_state = mo.state(0)@@ -352,7 +360,7 @@ class TestHash:def load() -> tuple[Any]:import marimo as mofrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoadermo.__version__ = "0.0.0"@@ -397,7 +405,7 @@ class TestDataHash:import numpy as npfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "w_Bjhpz2xMVQC6Y61GgqB8O80u_UyoJ-1xQmJU3j0Gg"return MockLoader, persistent_cache, expected_hash, np@@ -450,7 +458,7 @@ class TestDataHash:from jax import numpy as npfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "aAL9QNoQIQ1zOJgm_xDbHG63Bc4Atnpn58pGW9x9A_A"return MockLoader, persistent_cache, expected_hash, np@@ -503,7 +511,7 @@ class TestDataHash:import torchfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "stIOtiKIn4yscvKd-uK6mbmZpWzzfGm8Ccz7mvnRrnI"return MockLoader, persistent_cache, expected_hash, torch@@ -563,7 +571,7 @@ class TestDataHash:import torchfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "iV5v_cNAxBPqe8tNJnI5volNORTH_gyhKuIvHcG_cds"return MockLoader, persistent_cache, expected_hash, torch@@ -603,7 +611,7 @@ class TestDataHash:from skbio import DNAfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "ggxwHLzWcyDQltN_Zq0_zYVP_w86a9AAQLQwleAMuH8"return MockLoader, persistent_cache, expected_hash, DNA, copy@@ -641,7 +649,7 @@ class TestDataHash:import pandas as pdfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "wtrS6NoH2AOH3DnWm7wooK4Bgw8TmMotgMbiY0bu5as"return MockLoader, persistent_cache, expected_hash, np, pd@@ -705,7 +713,7 @@ class TestDataHash:import pandas as pdfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "RbeMLx994_-kB9rF2ebi6mFMbCW_S6-Q41MsrgJgwUA"return MockLoader, persistent_cache, expected_hash, np, pd@@ -746,7 +754,7 @@ class TestDataHash:import polars as plfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "rC6YiNsuaZKQ1JqMgSRa0iyEDwi7ZTl6InABjuM0RDY"return MockLoader, persistent_cache, expected_hash, pl@@ -803,7 +811,7 @@ class TestDataHash:import polars as plfrom marimo._save.save import persistent_cache- from tests._save.mocks import MockLoader+ from tests._save.loaders.mocks import MockLoaderexpected_hash = "QzGgcNS-eEP58qkkFphgAOJNKEpoTNcXhJ-L2exXzr4"return MockLoader, persistent_cache, expected_hash, pl