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
improvement: refactor cache Store, add RESTStore (#4789)
Myles Scolnick018414c771c6
diff --git a/marimo/_save/loaders/json.py b/marimo/_save/loaders/json.pyindex 56513d5092..bd5693d76a 100644--- a/marimo/_save/loaders/json.py+++ b/marimo/_save/loaders/json.py@@ -13,8 +13,8 @@ from marimo._save.loaders.loader import BasePersistenceLoader, LoaderErrorclass JsonLoader(BasePersistenceLoader):"""Readable json loader for basic objects."""- def __init__(self, name: str, save_path: str, **kwargs: Any) -> None:- super().__init__(name, "json", save_path, **kwargs)+ def __init__(self, name: str, **kwargs: Any) -> None:+ super().__init__(name, "json", **kwargs)def restore_cache(self, key: HashKey, blob: bytes) -> Cache:del keydiff --git a/marimo/_save/loaders/loader.py b/marimo/_save/loaders/loader.pyindex 624b1b5658..df9502106a 100644--- a/marimo/_save/loaders/loader.py+++ b/marimo/_save/loaders/loader.py@@ -1,14 +1,12 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import osfrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Optionalfrom marimo._runtime.context import get_contextfrom marimo._runtime.context.types import ContextNotInitializedError-from marimo._runtime.runtime import notebook_dirfrom marimo._runtime.state import Statefrom marimo._save.cache import (CACHE_PREFIX,@@ -168,7 +166,7 @@ class Loader(ABC):"""Load Cache"""@abstractmethod- def save_cache(self, cache: Cache) -> None:+ def save_cache(self, cache: Cache) -> bool:"""Save Cache"""@@ -179,7 +177,6 @@ class BasePersistenceLoader(Loader):self,name: str,suffix: str,- save_path: str | Path | None,store: Optional[Store] = None,) -> None:super().__init__(name)@@ -193,37 +190,24 @@ class BasePersistenceLoader(Loader):self.store = DEFAULT_STORE()self.name = name- # Setter takes care of this, not sure why mypy is complaining.- self.save_path = save_path # type: ignoreself.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, key: HashKey) -> Path:prefix = CACHE_PREFIX.get(key.cache_type, "U_")- return self.save_path / f"{prefix}{key.hash}.{self.suffix}"+ return Path(self.name) / f"{prefix}{key.hash}.{self.suffix}"def cache_hit(self, key: HashKey) -> bool:- return self.store.hit(key, self)+ return self.store.hit(str(self.build_path(key)))- def save_cache(self, cache: Cache) -> None:- return self.store.put(cache, self)+ def save_cache(self, cache: Cache) -> bool:+ blob = self.to_blob(cache)+ if blob is None:+ return False+ return self.store.put(str(self.build_path(cache.key)), blob)def load_cache(self, key: HashKey) -> Optional[Cache]:try:- blob: Optional[bytes] = self.store.get(key, self)+ blob: Optional[bytes] = self.store.get(str(self.build_path(key)))if not blob:return Nonereturn self.restore_cache(key, blob)diff --git a/marimo/_save/loaders/memory.py b/marimo/_save/loaders/memory.pyindex 4f78e3e896..68ef7e95fa 100644--- a/marimo/_save/loaders/memory.py+++ b/marimo/_save/loaders/memory.py@@ -66,7 +66,7 @@ class MemoryLoader(Loader):self._cache.move_to_end(path)return self._cache[path]- def save_cache(self, cache: Cache) -> None:+ def save_cache(self, cache: Cache) -> bool:path = self.build_path(cache.key)# LRUif self.is_lru:@@ -78,6 +78,7 @@ class MemoryLoader(Loader):if len(self._cache) > self.max_size:self._cache.popitem(last=False)self._cache[path] = cache+ return Truedef 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 38a8e71dfe..c22c057b5e 100644--- a/marimo/_save/loaders/pickle.py+++ b/marimo/_save/loaders/pickle.py@@ -14,8 +14,8 @@ if TYPE_CHECKING:class PickleLoader(BasePersistenceLoader):"""General loader for serializable objects."""- def __init__(self, name: str, save_path: str, **kwargs: Any) -> None:- super().__init__(name, "pickle", save_path, **kwargs)+ def __init__(self, name: str, **kwargs: Any) -> None:+ super().__init__(name, "pickle", **kwargs)def restore_cache(self, key: HashKey, blob: bytes) -> Cache:del keydiff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 9845f326da..ebc6ae66ca 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -46,6 +46,7 @@ from marimo._save.loaders import (LoaderType,MemoryLoader,)+from marimo._save.stores.file import FileStorefrom marimo._types.ids import CellId_tfrom marimo._utils.with_skip import SkipContext@@ -780,8 +781,17 @@ def persistent_cache( # type: ignore[misc]f"Invalid method {method}, expected one of "f"{PERSISTENT_LOADERS.keys()}")+ if save_path is not None and store is not None:+ raise ValueError(+ "save_path and store cannot both be provided, "+ "provide one or the other."+ )++ # Providing a save_path forces the store to be a FileStore+ if save_path is not None:+ store = FileStore(save_path)- partial_args: dict[str, Any] = {"save_path": save_path}+ partial_args: dict[str, Any] = {}if store is not None:partial_args["store"] = storediff --git a/marimo/_save/stores/__init__.py b/marimo/_save/stores/__init__.pyindex c395093ab2..965d808787 100644--- a/marimo/_save/stores/__init__.py+++ b/marimo/_save/stores/__init__.py@@ -3,13 +3,15 @@ from typing import Literalfrom marimo._save.stores.file import FileStorefrom marimo._save.stores.redis import RedisStore+from marimo._save.stores.rest import RestStorefrom marimo._save.stores.store import Store, StoreType-StoreKey = Literal["file", "redis"]+StoreKey = Literal["file", "redis", "rest"]CACHE_STORES: dict[StoreKey, StoreType] = {"file": FileStore,"redis": RedisStore,+ "rest": RestStore,}DEFAULT_STORE_KEY: StoreKey = "file"DEFAULT_STORE: StoreType = CACHE_STORES[DEFAULT_STORE_KEY]diff --git a/marimo/_save/stores/file.py b/marimo/_save/stores/file.pyindex be4c94c821..6049cc785e 100644--- a/marimo/_save/stores/file.py+++ b/marimo/_save/stores/file.py@@ -1,41 +1,43 @@# Copyright 2025 Marimo. All rights reserved.from __future__ import annotations-import os-from typing import TYPE_CHECKING, Optional+from pathlib import Path+from typing import Optional-from marimo._save.cache import (- Cache,-)+from marimo._runtime.runtime import notebook_dirfrom 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+ return path.exists() and path.stat().st_size > 0class FileStore(Store):- def get(self, key: HashKey, loader: Loader) -> Optional[bytes]:- path = loader.build_path(key)+ def __init__(self, save_path: Optional[str] = None) -> None:+ self.save_path = Path(save_path or self._default_save_path())+ self._init_save_path()++ def _default_save_path(self) -> Path:+ if (root := notebook_dir()) is not None:+ return Path(root / "__marimo__" / "cache")+ # This can happen if the notebook file is unnamed.+ return Path("__marimo__", "cache")++ def _init_save_path(self) -> None:+ self.save_path.mkdir(parents=True, exist_ok=True)++ def get(self, key: str) -> Optional[bytes]:+ path = self.save_path / keyif 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 path.read_bytes()++ def put(self, key: str, value: bytes) -> bool:+ path = self.save_path / key+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(value)+ return True++ def hit(self, key: str) -> bool:+ path = self.save_path / keyreturn _valid_path(path)diff --git a/marimo/_save/stores/redis.py b/marimo/_save/stores/redis.pyindex ceb38b6aa6..3367d92ac9 100644--- a/marimo/_save/stores/redis.py+++ b/marimo/_save/stores/redis.py@@ -1,17 +1,10 @@# Copyright 2025 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Any, Optional+from typing import 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:@@ -22,13 +15,17 @@ class RedisStore(Store):# 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 get(self, key: str) -> Optional[bytes]:+ result = self.redis.get(key)+ if result is None:+ return None+ return result # type: ignore[no-any-return]- def put(self, cache: Cache, loader: Loader) -> None:- self.redis.set(- str(loader.build_path(cache.key)), loader.to_blob(cache) or b""- )+ def put(self, key: str, value: bytes) -> bool:+ result = self.redis.set(key, value)+ if result is None:+ return False+ return True- def hit(self, key: HashKey, loader: Loader) -> bool:- return self.redis.exists(str(loader.build_path(key))) > 0+ def hit(self, key: str) -> bool:+ return self.redis.exists(key) > 0diff --git a/marimo/_save/stores/rest.py b/marimo/_save/stores/rest.pynew file mode 100644index 0000000000..a2d14fe9e4--- /dev/null+++ b/marimo/_save/stores/rest.py@@ -0,0 +1,98 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import urllib.error+import urllib.request+from typing import Optional++from marimo import __version__, _loggers+from marimo._save.stores.store import Store++LOGGER = _loggers.marimo_logger()+++class RestStore(Store):+ def __init__(+ self, *, base_url: str, api_key: str, project_id: Optional[str] = None+ ) -> None:+ super().__init__()+ assert api_key, "api_key is required"+ assert base_url, "base_url is required"++ self.base_url = base_url+ self.api_key = api_key+ self.project_id = project_id+ self.headers = {+ "Authorization": f"Bearer {self.api_key}",+ "User-Agent": f"marimo/{__version__}",+ }+ import ssl++ self.context = ssl.create_default_context()++ def get(self, key: str) -> Optional[bytes]:+ url = self._get_url(key)+ req = urllib.request.Request(url, headers=self.headers)+ try:+ with urllib.request.urlopen(req, context=self.context) as response:+ if response.status == 200:+ LOGGER.debug(f"GET {url} - Status: {response.status}")+ return response.read() # type: ignore[no-any-return]+ if response.status >= 400 and response.status < 500:+ # 400s are fine, they just mean the key doesn't exist+ return None+ raise+ except urllib.error.HTTPError as e:+ if e.code >= 400 and e.code < 500:+ # 400s are fine, they just mean the key doesn't exist+ return None+ LOGGER.warning(f"GET {url} - Error: {e}")+ except Exception as e:+ LOGGER.warning(f"GET {url} - Error: {e}")+ return None++ def put(self, key: str, value: bytes) -> bool:+ url = self._get_url(key)+ req = urllib.request.Request(+ url,+ data=value,+ headers={+ **self.headers,+ "Content-Type": "application/octet-stream",+ },+ method="PUT",+ )+ try:+ with urllib.request.urlopen(req, context=self.context) as response:+ LOGGER.debug(f"PUT {url} - Status: {response.status}")+ return True+ except urllib.error.HTTPError as e:+ LOGGER.warning(+ f"PUT {url} - Status: {e.status} - Error: {e.reason}"+ )+ except Exception as e:+ LOGGER.warning(f"PUT {url} - Error: {e}")++ return False++ def hit(self, key: str) -> bool:+ url = self._get_url(key)+ req = urllib.request.Request(url, headers=self.headers, method="HEAD")+ try:+ with urllib.request.urlopen(req) as response:+ LOGGER.debug(f"HEAD {url} - Status: {response.status}")+ return response.status == 200 # type: ignore[no-any-return]+ except urllib.error.HTTPError as e:+ LOGGER.warning(+ f"HEAD {url} - Status: {e.status} - Error: {e.reason}"+ )+ return False+ except Exception as e:+ LOGGER.warning(f"HEAD {url} - Error: {e}")+ return False++ def _get_url(self, key: str) -> str:+ url = self.base_url+ if self.project_id:+ url = f"{url}/{self.project_id}"+ return f"{url}/{key}"diff --git a/marimo/_save/stores/store.py b/marimo/_save/stores/store.pyindex f0ee0e6a46..b95e3b2e2e 100644--- a/marimo/_save/stores/store.py+++ b/marimo/_save/stores/store.py@@ -2,37 +2,20 @@from __future__ import annotationsfrom 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+from typing import Optionalclass 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]:+ def get(self, key: str) -> Optional[bytes]:"""Get the bytes of a cache from the store"""@abstractmethod- def put(self, cache: Cache, loader: Loader) -> None:+ def put(self, key: str, value: bytes) -> bool:"""Put a cache into the store"""@abstractmethod- def hit(self, key: HashKey, loader: Loader) -> bool:+ def hit(self, key: str) -> bool:"""Check if the cache is in the store"""diff --git a/tests/_save/loaders/mocks.py b/tests/_save/loaders/mocks.pyindex e2f7d26a1e..2007919ebd 100644--- a/tests/_save/loaders/mocks.py+++ b/tests/_save/loaders/mocks.py@@ -40,6 +40,7 @@ class MockLoader(Loader):meta={},)- def save_cache(self, _cache: Cache) -> None:+ def save_cache(self, _cache: Cache) -> bool:self._saved = Trueself._cache_hit = True+ return Truediff --git a/tests/_save/loaders/test_loader.py b/tests/_save/loaders/test_loader.pyindex e8ce3df281..3420773733 100644--- a/tests/_save/loaders/test_loader.py+++ b/tests/_save/loaders/test_loader.py@@ -17,6 +17,7 @@ from marimo._save.loaders.loader import (Loader,LoaderPartial,)+from marimo._save.stores.file import FileStorefrom tests._save.loaders.mocks import MockLoader@@ -49,7 +50,6 @@ class TestLoaderPartial:class ABCTestLoader(ABC):- save_path = Nonesuffix = Nonevalue = None@@ -57,6 +57,7 @@ class ABCTestLoader(ABC):"""Set up a temporary directory for each test."""self.temp_dir = tempfile.TemporaryDirectory()self.save_path = self.temp_dir.name+ self.store = FileStore(save_path=self.save_path)def teardown_method(self) -> None:"""Clean up the temporary directory."""@@ -74,9 +75,9 @@ class ABCTestLoader(ABC):if self.suffix:assert loader.suffix == self.suffixif isinstance(loader, BasePersistenceLoader):- assert Path(str(loader.save_path)).name == "test"+ assert self.store.save_path.name == Path(self.temp_dir.name).name# Check that the directory was created- assert os.path.exists(loader.save_path)+ assert os.path.exists(self.store.save_path)def test_build_path(self) -> None:"""Test building the path for a cache file."""@@ -97,6 +98,7 @@ class ABCTestLoader(ABC):# Create a cache filecache_path = loader.build_path(key("hash1", "Pure"))+ assert cache_path# Create a valid JSON cacheself.seed_cache()@@ -115,8 +117,8 @@ class ABCTestLoader(ABC):# Empty file should missempty_path = loader.build_path(key("empty", "Pure"))- with open(empty_path, "w") as f:- pass+ empty_path.parent.mkdir(parents=True, exist_ok=True)+ empty_path.write_bytes(b"")assert not loader.cache_hit(key("empty", "Pure"))assert loader.hits == 1@@ -150,7 +152,7 @@ class TestJsonLoader(ABCTestLoader):suffix = "json"def _instance(self) -> Loader:- return JsonLoader("test", self.save_path)+ return JsonLoader("test", store=self.store)def seed_cache(self):cache_path = self.instance().build_path(key("hash1", "Pure"))@@ -165,15 +167,14 @@ class TestJsonLoader(ABCTestLoader):"meta": {},}- with open(cache_path, "w") as f:- json.dump(cache_dict, f)+ self.store.put(str(cache_path), json.dumps(cache_dict).encode("utf-8"))class TestPickleLoader(ABCTestLoader):suffix = "pickle"def _instance(self) -> Loader:- return PickleLoader("test", self.save_path)+ return PickleLoader("test", store=self.store)def seed_cache(self) -> None:cache_path = self.instance().build_path(key("hash1", "Pure"))@@ -186,5 +187,4 @@ class TestPickleLoader(ABCTestLoader):meta={},)- with open(cache_path, "wb") as f:- pickle.dump(cache, f)+ self.store.put(str(cache_path), pickle.dumps(cache))diff --git a/tests/_save/store/mocks.py b/tests/_save/store/mocks.pyindex 1f90a0344a..bf7358c0d8 100644--- a/tests/_save/store/mocks.py+++ b/tests/_save/store/mocks.py@@ -1,25 +1,21 @@from __future__ import annotations-from typing import TYPE_CHECKING, Any, Optional+from typing import Any, Optionalfrom 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 get(self, key: str) -> Optional[bytes]:+ return self._cache.get(key, None)- def put(self, cache: Cache, _loader: Loader) -> None:- self._cache[cache.key.hash] = cache+ def put(self, key: str, value: bytes) -> bool:+ self._cache[key] = value+ return True- def hit(self, key: HashKey, _loader: Loader) -> bool:+ def hit(self, key: str) -> bool:return key in self._cachediff --git a/tests/_save/store/test_store.py b/tests/_save/store/test_store.pyindex 2ed7974183..5f86fc47a3 100644--- a/tests/_save/store/test_store.py+++ b/tests/_save/store/test_store.py@@ -22,4 +22,6 @@ class TestStore:a = 1b = 2- assert store._cache[cache._cache.key.hash]+ key = f"mock/P_{cache._cache.key.hash}.pickle"+ assert key in store._cache.keys()+ assert store._cache[key]