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.

improvement: add tiered cache store (#4918)

Myles Scolnick1d9eefe8bb11
diff --git a/marimo/_save/stores/__init__.py b/marimo/_save/stores/__init__.py
index 3fa73eac10..ea5b0a4d16 100644
--- a/marimo/_save/stores/__init__.py
+++ b/marimo/_save/stores/__init__.py
@@ -1,20 +1,28 @@
# Copyright 2025 Marimo. All rights reserved.
-from typing import Literal, Optional
+from typing import Any, Literal, Optional, TypedDict, Union, cast
from marimo import _loggers
from marimo._save.stores.file import FileStore
from marimo._save.stores.redis import RedisStore
from marimo._save.stores.rest import RestStore
from marimo._save.stores.store import Store, StoreType
+from marimo._save.stores.tiered import TieredStore
LOGGER = _loggers.marimo_logger()
-StoreKey = Literal["file", "redis", "rest"]
+StoreKey = Literal["file", "redis", "rest", "tiered"]
+
+
+class StoreConfig(TypedDict, total=False):
+ type: StoreKey
+ args: dict[str, Any]
+
CACHE_STORES: dict[StoreKey, StoreType] = {
"file": FileStore,
"redis": RedisStore,
"rest": RestStore,
+ "tiered": TieredStore,
}
DEFAULT_STORE_KEY: StoreKey = "file"
DEFAULT_STORE: StoreType = CACHE_STORES[DEFAULT_STORE_KEY]
@@ -23,28 +31,52 @@ DEFAULT_STORE: StoreType = CACHE_STORES[DEFAULT_STORE_KEY]
def get_store(current_path: Optional[str] = None) -> Store:
from marimo._config.manager import get_default_config_manager
- cache_config = (
+ cache_config: Union[list[StoreConfig], StoreConfig] = (
get_default_config_manager(current_path=current_path)
.get_config()
.get("experimental", {})
.get("cache", {})
)
- store_type = cache_config.get("store", DEFAULT_STORE_KEY)
- if store_type not in CACHE_STORES:
- LOGGER.error(f"Invalid store type: {store_type}")
- store_type = DEFAULT_STORE_KEY
- try:
- return CACHE_STORES[store_type](**cache_config.get("args", {}))
- except Exception as e:
- LOGGER.error(f"Error creating store: {e}")
+
+ return _get_store_from_config(cache_config)
+
+
+def _get_store_from_config(
+ config: Union[list[StoreConfig], StoreConfig, None],
+) -> Store:
+ if config is None:
return DEFAULT_STORE()
+ if isinstance(config, list):
+ sub_stores = [
+ _get_store_from_config(item) for item in config if item is not None
+ ]
+ if len(sub_stores) == 0:
+ return DEFAULT_STORE()
+ if len(sub_stores) == 1:
+ return sub_stores[0]
+ return TieredStore(sub_stores)
+ else:
+ store_type = cast(StoreKey, config.get("store", DEFAULT_STORE_KEY))
+ if store_type not in CACHE_STORES:
+ LOGGER.error(f"Invalid store type: {store_type}")
+ store_type = DEFAULT_STORE_KEY
+
+ try:
+ store_args = config.get("args", {})
+ return CACHE_STORES[store_type](**store_args)
+ except Exception as e:
+ LOGGER.error(f"Error creating store: {e}")
+ return DEFAULT_STORE()
+
__all__ = [
"CACHE_STORES",
"DEFAULT_STORE",
"FileStore",
"RedisStore",
+ "RestStore",
+ "TieredStore",
"Store",
"StoreKey",
"StoreType",
diff --git a/marimo/_save/stores/tiered.py b/marimo/_save/stores/tiered.py
new file mode 100644
index 0000000000..e686752765
--- /dev/null
+++ b/marimo/_save/stores/tiered.py
@@ -0,0 +1,75 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Optional
+
+from marimo import _loggers
+from marimo._save.stores.store import Store
+
+LOGGER = _loggers.marimo_logger()
+
+
+class TieredStore(Store):
+ """A composite store that tries multiple stores in order.
+
+ Reads will check each store in order until the data is found.
+ Writes will update all stores.
+ """
+
+ def __init__(self, stores: list[Store]) -> None:
+ """Initialize the tiered store with a list of stores.
+
+ Args:
+ stores: List of stores to use, in order of priority
+ """
+ if not stores:
+ raise ValueError("At least one store is required")
+ self.stores = stores
+
+ def get(self, key: str) -> Optional[bytes]:
+ """Get a value from the first store that has it."""
+ for i, store in enumerate(self.stores):
+ try:
+ value = store.get(key)
+ if value is not None:
+ # Found in this store, update preceding stores
+ self._update_preceding_stores(key, value, i)
+ return value
+ except Exception as e:
+ LOGGER.error(f"Error getting from store {i}: {e}")
+
+ return None
+
+ def put(self, key: str, value: bytes) -> bool:
+ """Put a value in all stores."""
+ success = False
+
+ for i, store in enumerate(self.stores):
+ try:
+ if store.put(key, value):
+ success = True
+ except Exception as e:
+ LOGGER.error(f"Error putting to store {i}: {e}")
+
+ return success
+
+ def hit(self, key: str) -> bool:
+ """Check if any store has the key."""
+ for i, store in enumerate(self.stores):
+ try:
+ if store.hit(key):
+ return True
+ except Exception as e:
+ LOGGER.error(f"Error checking hit on store {i}: {e}")
+
+ return False
+
+ def _update_preceding_stores(
+ self, key: str, value: bytes, found_index: int
+ ) -> None:
+ """Update all stores before the one where the value was found."""
+ for i in range(found_index):
+ try:
+ self.stores[i].put(key, value)
+ except Exception as e:
+ LOGGER.error(f"Error updating preceding store {i}: {e}")
diff --git a/tests/_save/stores/test_store_config.py b/tests/_save/stores/test_store_config.py
new file mode 100644
index 0000000000..30e1f286e5
--- /dev/null
+++ b/tests/_save/stores/test_store_config.py
@@ -0,0 +1,72 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+from __future__ import annotations
+
+from marimo._save.stores import (
+ DEFAULT_STORE,
+ FileStore,
+ TieredStore,
+ _get_store_from_config,
+)
+
+
+class TestGetStoreFromConfig:
+ def test_none_config(self) -> None:
+ """Test that None config returns the default store."""
+ store = _get_store_from_config(None)
+ assert isinstance(store, DEFAULT_STORE)
+
+ def test_empty_list_config(self) -> None:
+ """Test that an empty list config returns the default store."""
+ store = _get_store_from_config([])
+ assert isinstance(store, DEFAULT_STORE)
+
+ def test_list_with_none_config(self) -> None:
+ """Test that a list with None items returns the default store."""
+ store = _get_store_from_config([None])
+ assert isinstance(store, DEFAULT_STORE)
+
+ def test_single_item_list(self) -> None:
+ """Test that a list with a single valid item returns that item's store."""
+ config = [{"type": "file", "args": {"save_path": "/tmp/test"}}]
+ store = _get_store_from_config(config)
+ assert isinstance(store, FileStore)
+ assert store.save_path.as_posix() == "/tmp/test"
+
+ def test_multi_item_list(self) -> None:
+ """Test that a list with multiple items returns a TieredStore."""
+ config = [
+ {"type": "file", "args": {"save_path": "/tmp/test1"}},
+ {"type": "file", "args": {"save_path": "/tmp/test2"}},
+ ]
+ store = _get_store_from_config(config)
+ assert isinstance(store, TieredStore)
+ assert len(store.stores) == 2
+ assert all(isinstance(s, FileStore) for s in store.stores)
+ assert store.stores[0].save_path.as_posix() == "/tmp/test1"
+ assert store.stores[1].save_path.as_posix() == "/tmp/test2"
+
+ def test_dict_config(self) -> None:
+ """Test that a dict config returns the appropriate store."""
+ config = {"type": "file", "args": {"save_path": "/tmp/test"}}
+ store = _get_store_from_config(config)
+ assert isinstance(store, FileStore)
+ assert store.save_path.as_posix() == "/tmp/test"
+
+ def test_invalid_store_type(self) -> None:
+ """Test that an invalid store type returns the default store."""
+ config = {"type": "invalid", "args": {}}
+ store = _get_store_from_config(config)
+ assert isinstance(store, DEFAULT_STORE)
+
+ def test_store_creation_error(self) -> None:
+ """Test that an error during store creation returns the default store."""
+ config = {"type": "file", "args": {"invalid_arg": "value"}}
+ store = _get_store_from_config(config)
+ assert isinstance(store, DEFAULT_STORE)
+
+ def test_missing_store_type_uses_default(self) -> None:
+ """Test that a missing store type uses the default store type."""
+ config = {"args": {}}
+ store = _get_store_from_config(config)
+ assert isinstance(store, DEFAULT_STORE)
diff --git a/tests/_save/stores/test_tiered.py b/tests/_save/stores/test_tiered.py
new file mode 100644
index 0000000000..2dd0923a50
--- /dev/null
+++ b/tests/_save/stores/test_tiered.py
@@ -0,0 +1,175 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from marimo._save.stores.tiered import TieredStore
+from tests._save.store.mocks import MockStore
+
+
+def throw_exception(*args: Any, **kwargs: Any) -> None:
+ del args, kwargs
+ raise ValueError("Test exception")
+
+
+class TestTieredStore:
+ def test_init_with_empty_stores_raises_error(self) -> None:
+ """Test that initializing with empty stores raises an error."""
+ with pytest.raises(ValueError, match="At least one store is required"):
+ TieredStore([])
+
+ def test_init_with_multiple_stores(self) -> None:
+ """Test that initializing with multiple stores works."""
+ stores = [MockStore(), MockStore()]
+ tiered_store = TieredStore(stores)
+ assert tiered_store.stores == stores
+
+ def test_get_from_first_store(self) -> None:
+ """Test getting a value that exists in the first store."""
+ store1 = MockStore()
+ store2 = MockStore()
+ key = "test_key"
+ value = b"test_value"
+ store1._cache[key] = value
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.get(key)
+
+ assert result == value
+ # Second store should remain empty
+ assert key not in store2._cache
+
+ def test_get_from_second_store_updates_first(self) -> None:
+ """Test getting a value from the second store updates the first store."""
+ store1 = MockStore()
+ store2 = MockStore()
+ key = "test_key"
+ value = b"test_value"
+ store2._cache[key] = value
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.get(key)
+
+ assert result == value
+ # First store should be updated
+ assert key in store1._cache
+ assert store1._cache[key] == value
+
+ def test_get_not_found(self) -> None:
+ """Test that get returns None when the key is not found in any store."""
+ store1 = MockStore()
+ store2 = MockStore()
+ key = "test_key"
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.get(key)
+
+ assert result is None
+
+ def test_put_updates_all_stores(self) -> None:
+ """Test that put updates all stores."""
+ store1 = MockStore()
+ store2 = MockStore()
+ key = "test_key"
+ value = b"test_value"
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.put(key, value)
+
+ assert result is True
+ assert key in store1._cache
+ assert store1._cache[key] == value
+ assert key in store2._cache
+ assert store2._cache[key] == value
+
+ def test_hit_returns_true_if_any_store_has_key(self) -> None:
+ """Test that hit returns True if any store has the key."""
+ store1 = MockStore()
+ store2 = MockStore()
+ key = "test_key"
+ value = b"test_value"
+ store2._cache[key] = value
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.hit(key)
+
+ assert result is True
+
+ def test_hit_returns_false_if_no_store_has_key(self) -> None:
+ """Test that hit returns False if no store has the key."""
+ store1 = MockStore()
+ store2 = MockStore()
+ key = "test_key"
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.hit(key)
+
+ assert result is False
+
+ @patch("marimo._save.stores.tiered.LOGGER")
+ def test_get_with_exception(self, mock_logger) -> None:
+ """Test handling exceptions during get operation."""
+ store1 = MockStore()
+ # Create a store that will raise an exception
+ store2 = MockStore()
+ store2.get = throw_exception
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.get("test_key")
+
+ assert result is None
+ mock_logger.error.assert_called_once()
+ assert "Test exception" in mock_logger.error.call_args[0][0]
+
+ @patch("marimo._save.stores.tiered.LOGGER")
+ def test_put_with_exception(self, mock_logger) -> None:
+ """Test handling exceptions during put operation."""
+ store1 = MockStore()
+ # Create a store that will raise an exception
+ store2 = MockStore()
+ store2.put = throw_exception
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.put("test_key", b"test_value")
+
+ # Should still return True because store1 succeeded
+ assert result is True
+ mock_logger.error.assert_called_once()
+ assert "Test exception" in mock_logger.error.call_args[0][0]
+
+ @patch("marimo._save.stores.tiered.LOGGER")
+ def test_hit_with_exception(self, mock_logger) -> None:
+ """Test handling exceptions during hit operation."""
+ store1 = MockStore()
+ # Create a store that will raise an exception
+ store2 = MockStore()
+ store2.hit = throw_exception
+
+ tiered_store = TieredStore([store1, store2])
+ result = tiered_store.hit("test_key")
+
+ assert result is False
+ mock_logger.error.assert_called_once()
+ assert "Test exception" in mock_logger.error.call_args[0][0]
+
+ @patch("marimo._save.stores.tiered.LOGGER")
+ def test_update_preceding_stores_with_exception(self, mock_logger) -> None:
+ """Test handling exceptions during update_preceding_stores operation."""
+ store1 = MockStore()
+ store1.put = throw_exception
+ store2 = MockStore()
+ key = "test_key"
+ value = b"test_value"
+ store2._cache[key] = value
+
+ tiered_store = TieredStore([store1, store2])
+ # This should trigger _update_preceding_stores
+ result = tiered_store.get(key)
+
+ assert result == value
+ mock_logger.error.assert_called_once()
+ assert "Test exception" in mock_logger.error.call_args[0][0]