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
feature: allow persistent_cache to be used as a decorator (#3550)
Dylan Madisettif25319284d43
diff --git a/marimo/_save/loaders/__init__.py b/marimo/_save/loaders/__init__.pyindex da49d65cac..801fe15741 100644--- a/marimo/_save/loaders/__init__.py+++ b/marimo/_save/loaders/__init__.py@@ -1,6 +1,12 @@# Copyright 2024 Marimo. All rights reserved.-from marimo._save.loaders.loader import Loader+from marimo._save.loaders.loader import Loader, LoaderPartial, LoaderTypefrom marimo._save.loaders.memory import MemoryLoaderfrom marimo._save.loaders.pickle import PickleLoader-__all__ = ["Loader", "MemoryLoader", "PickleLoader"]+__all__ = [+ "Loader",+ "LoaderPartial",+ "LoaderType",+ "MemoryLoader",+ "PickleLoader",+]diff --git a/marimo/_save/loaders/loader.py b/marimo/_save/loaders/loader.pyindex 03e92ce147..f5094d4872 100644--- a/marimo/_save/loaders/loader.py+++ b/marimo/_save/loaders/loader.py@@ -3,8 +3,10 @@ from __future__ import annotationsfrom abc import ABC, abstractmethodfrom pathlib import Path-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Any, TypeVar+from marimo._runtime.context import get_context+from marimo._runtime.state import Statefrom marimo._save.cache import CACHE_PREFIX, Cache, CacheTypeif TYPE_CHECKING:@@ -20,6 +22,60 @@ INCONSISTENT_CACHE_BOILER_PLATE = ()+LoaderType = TypeVar("LoaderType", bound="Loader")+++class LoaderPartial:+ """Cache implementation sometimes requires a deferred construction.+ Moreover, for a cache persistence, we utilize the state registry to store+ the loader such that the loader object is not actually reconstructed if it+ does not need to be.+ """++ def __init__(self, loader_type: type[Loader], **kwargs: Any) -> None:+ self.loader_type = loader_type+ self.kwargs = kwargs++ def __call__(self, name: str) -> Loader:+ try:+ return self.loader_type(name, **self.kwargs)+ except TypeError as e:+ raise TypeError(+ f"Could not create {self.loader_type} from the construction "+ f"arguments: [{', '.join(self.kwargs.keys())}]. Consider "+ "setting these arguments explicitly with "+ f"{self.loader_type}.partial(needed_arg=value)."+ ) from e++ def create_or_reconfigure(+ self, name: str, context: str = "cache_partial"+ ) -> State[Loader]:+ ctx = get_context()+ if ctx.state_registry is None:+ return State(self(name), _name=name, _context=context)++ loader_state: State[Loader] | None = ctx.state_registry.lookup(+ name, context=context+ )+ if loader_state is None:+ loader = self(name)+ # State creation automatically registers itself.+ return State(loader, _name=name, _context=context)+ else:+ loader = loader_state()+ if isinstance(loader, self.loader_type):+ # Manually set the attributes of the old loader.+ # Overriding attr.setter is useful for+ # managed behavior.+ for key, value in self.kwargs.items():+ setattr(loader, key, value)+ else:+ loader = self(name)+ # Replace the previous loader with the new construction.+ loader_state._set_value(loader)+ return loader_state++class Loader(ABC):"""Loaders are responsible for saving and loading persistent caches.@@ -33,6 +89,7 @@ class Loader(ABC):def __init__(self, name: str) -> None:self.name = name+ self._hits = 0def build_path(self, hashed_context: str, cache_type: CacheType) -> Path:prefix = CACHE_PREFIX.get(cache_type, "U_")@@ -60,6 +117,7 @@ class Loader(ABC):assert set(defs | stateful_refs) == set(loaded.defs), (INCONSISTENT_CACHE_BOILER_PLATE)+ self._hits += 1return Cache(loaded.defs,hashed_context,@@ -69,6 +127,21 @@ class Loader(ABC):loaded.meta,)+ @property+ def hits(self) -> int:+ return self._hits++ @classmethod+ def partial(cls, **kwargs: Any) -> LoaderPartial:+ return LoaderPartial(cls, **kwargs)++ @classmethod+ def cache(cls, *args: Any, **kwargs: Any) -> Any:+ """General `mo.cache` api for this loader"""+ from marimo._save.save import cache++ return cache(*args, loader=cls, **kwargs) # type: ignore+@abstractmethoddef cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:"""Check if cache has been hit given a result hash.diff --git a/marimo/_save/loaders/memory.py b/marimo/_save/loaders/memory.pyindex 2e576d1829..de98b4251f 100644--- a/marimo/_save/loaders/memory.py+++ b/marimo/_save/loaders/memory.py@@ -38,8 +38,7 @@ class MemoryLoader(Loader):if self.is_lru:self._cache = OrderedDict()self._cache_lock = threading.Lock()- self.max_size = max_size- self.hits = 0+ self._max_size = max_sizeif cache is not None:self._maybe_lock(lambda: self._cache.update(cache))@@ -58,7 +57,6 @@ class MemoryLoader(Loader):assert self.cache_hit(hashed_context, cache_type), (INCONSISTENT_CACHE_BOILER_PLATE)- self.hits += 1key = self.build_path(hashed_context, cache_type)if self.is_lru:assert isinstance(self._cache, OrderedDict)@@ -86,7 +84,7 @@ class MemoryLoader(Loader):if self.is_lru:self._cache = OrderedDict(self._cache.items())self._cache_lock = threading.Lock()- self.max_size = max_size+ self._max_size = max_sizereturnassert isinstance(self._cache, OrderedDict)assert self._cache_lock is not None@@ -94,8 +92,16 @@ class MemoryLoader(Loader):self.is_lru = max_size > 0if not self.is_lru:self._cache = dict(self._cache.items())- self.max_size = max_size+ self._max_size = max_sizereturnwhile len(self._cache) > max_size:self._cache.popitem(last=False)- self.max_size = max_size+ self._max_size = max_size++ @property+ def max_size(self) -> int:+ return self._max_size++ @max_size.setter+ def max_size(self, value: int) -> None:+ self.resize(value)diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex 3159a4ea31..40aab29222 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -2,11 +2,17 @@from __future__ import annotationsimport ast+import functoolsimport inspectimport ioimport osimport sysimport traceback+from collections import abc+from pathlib import Path++# NB: maxsize follows functools.cache, but renamed max_size outside of drop-in+# api.from sys import maxsize as MAXINTfrom typing import (TYPE_CHECKING,@@ -15,6 +21,8 @@ from typing import (Optional,Type,Union,+ cast,+ overload,)from marimo._messaging.tracebacks import write_traceback@@ -29,7 +37,13 @@ from marimo._save.hash import (cache_attempt_from_hash,content_cache_attempt_from_base,)-from marimo._save.loaders import Loader, MemoryLoader, PickleLoader+from marimo._save.loaders import (+ Loader,+ LoaderPartial,+ LoaderType,+ MemoryLoader,+ PickleLoader,+)from marimo._utils.variables import is_mangled_local, unmangle_local# Many assertions are for typing and should always pass. This message is a@@ -54,33 +68,33 @@ class SkipWithBlock(Exception):"""Special exception to get around executing the with block body."""-class _cache_base(object):+class _cache_call(object):"""Like functools.cache but notebook-aware. See `cache` docstring`"""graph: DirectedGraphcell_id: strmodule: ast.Module_args: list[str]- _loader: Optional[State[MemoryLoader]] = None+ _loader: Optional[State[Loader]] = None+ _loader_partial: LoaderPartialname: strfn: Optional[Callable[..., Any]]def __init__(self,- _fn: Optional[Callable[..., Any]] = None,+ _fn: Optional[Callable[..., Any]],+ loader_partial: LoaderPartial,*,- # -1 means unbounded cache- maxsize: int = -1,pin_modules: bool = False,hash_type: str = DEFAULT_HASH,# frame_offset is the number of frames the __init__ call is nested# with respect to definition of _fnframe_offset: int = 0,) -> None:- self.max_size = maxsizeself.pin_modules = pin_modulesself.hash_type = hash_typeself._frame_offset = frame_offset+ self._loader_partial = loader_partialif _fn is None:self.fn = Noneelse:@@ -90,7 +104,7 @@ class _cache_base(object):def hits(self) -> int:if self._loader is None:return 0- return self._loader().hits+ return self.loader.hitsdef _set_context(self, fn: Callable[..., Any]) -> None:assert callable(fn), "the provided function must be callable"@@ -121,7 +135,7 @@ class _cache_base(object):# block.cell_id = ctx.cell_id or ctx.execution_context.cell_id or ""self.scoped_refs = set([f"{ARG_PREFIX}{k}" for k in self._args])- # # As are the "locals" not in globals+ # As are the "locals" not in globalsself.scoped_refs |= set(f_locals.keys()) - set(ctx.globals.keys())# Defined in the cell, and currently available in scopeself.scoped_refs |= ctx.graph.cells[cell_id].defs & set(@@ -155,15 +169,14 @@ class _cache_base(object):# lifetime of the cache will be tied to the global variable.# We can invalidate that by making an invalid namespace.if ctx.globals != f_locals:- name = name + "*"+ name = f"{name}*"- context = "cache"- self._loader = ctx.state_registry.lookup(name, context=context)- if self._loader is None:- loader = MemoryLoader(name, max_size=self.max_size)- self._loader = State(loader, _name=name, _context=context)- else:- self._loader().resize(self.max_size)+ self._loader = self._loader_partial.create_or_reconfigure(name)++ @property+ def loader(self) -> Loader:+ assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATE+ return self._loader()def __call__(self, *args: Any, **kwargs: Any) -> Any:# Capture the deferred call case@@ -172,6 +185,9 @@ class _cache_base(object):raise TypeError("cache() takes at most 1 argument (expecting function)")+ # Remove the additional frames from singledispatch, because invoking+ # the function directly.+ self._frame_offset -= 4self._set_context(args[0])return self@@ -184,7 +200,7 @@ class _cache_base(object):attempt = content_cache_attempt_from_base(self.base_block,scope,- self._loader(),+ self.loader,scoped_refs=self.scoped_refs,required_refs=set([f"{ARG_PREFIX}{k}" for k in self._args]),as_fn=True,@@ -197,175 +213,22 @@ class _cache_base(object):# stateful variables may be globalscope = {k: v for k, v in scope.items() if k in attempt.stateful_refs}attempt.update(scope, meta={"return": response})- self._loader().save_cache(attempt)+ self.loader.save_cache(attempt)return response-def cache(- _fn: Optional[Callable[..., Any]] = None,- *,- pin_modules: bool = False,-) -> _cache_base:- """Cache the value of a function based on args and closed-over variables.-- Decorating a function with `@mo.cache` will cache its value based on- the function's arguments, closed-over values, and the notebook code.-- **Usage.**-- ```python- import marimo as mo--- @mo.cache- def fib(n):- if n <= 1:- return n- return fib(n - 1) + fib(n - 2)- ```-- `mo.cache` is similar to `functools.cache`, but with three key benefits:-- 1. `mo.cache` persists its cache even if the cell defining the- cached function is re-run, as long as the code defining the function- (excluding comments and formatting) has not changed.- 2. `mo.cache` keys on closed-over values in addition to function arguments,- preventing accumulation of hidden state associated with- `functools.cache`.- 3. `mo.cache` does not require its arguments to be- hashable (only pickleable), meaning it can work with lists, sets, NumPy- arrays, PyTorch tensors, and more.-- `mo.cache` obtains these benefits at the cost of slightly higher overhead- than `functools.cache`, so it is best used for expensive functions.-- Like `functools.cache`, `mo.cache` is thread-safe.-- The cache has an unlimited maximum size. To limit the cache size, use- `@mo.lru_cache`. `mo.cache` is slightly faster than `mo.lru_cache`, but in- most applications the difference is negligible.-- **Args**:-- - `pin_modules`: if True, the cache will be invalidated if module versions- differ.- """- return _cache_base(- _fn,- maxsize=-1,- pin_modules=pin_modules,- frame_offset=1,- )---def lru_cache(- _fn: Optional[Callable[..., Any]] = None,- *,- maxsize: int = 128,- pin_modules: bool = False,-) -> _cache_base:- """Decorator for LRU caching the return value of a function.-- `mo.lru_cache` is a version of `mo.cache` with a bounded cache size. As an- LRU (Least Recently Used) cache, only the last used `maxsize` values are- retained, with the oldest values being discarded. For more information,- see the documentation of `mo.cache`.-- **Usage.**-- ```python- import marimo as mo--- @mo.lru_cache- def factorial(n):- return n * factorial(n - 1) if n else 1- ```-- **Args**:-- - `maxsize`: the maximum number of entries in the cache; defaults to 128.- Setting to -1 disables cache limits.- - `pin_modules`: if True, the cache will be invalidated if module versions- differ.- """-- return _cache_base(- _fn,- maxsize=maxsize,- pin_modules=pin_modules,- frame_offset=1,- )---class persistent_cache(object):- """Save variables to disk and restore them thereafter.-- The `mo.persistent_cache` context manager lets you delimit a block of code- in which variables will be cached to disk when they are first computed. On- subsequent runs of the cell, if marimo determines that this block of code- hasn't changed and neither has its ancestors, it will restore the variables- from disk instead of re-computing them, skipping execution of the block- entirely.-- Restoration happens even across notebook runs, meaning you can use- `mo.persistent_cache` to make notebooks start *instantly*, with variables- that would otherwise be expensive to compute already materialized in- memory.-- **Usage.**-- ```python- with persistent_cache(name="my_cache"):- variable = expensive_function() # This will be cached to disk.- print("hello, cache") # this will be skipped on cache hits- ```-- In this example, `variable` will be cached the first time the block- is executed, and restored on subsequent runs of the block. If cache- conditions are hit, the contents of `with` block will be skipped on- execution. This means that side-effects such as writing to stdout and- stderr will be skipped on cache hits.-- For function-level memoization, use `@mo.cache` or `@mo.lru_cache`.-- Note that `mo.state` and `UIElement` changes will also trigger cache- invalidation, and be accordingly updated.-- **Warning.** Since context abuses sys frame trace, this may conflict with- debugging tools or libraries that also use `sys.settrace`.-- **Args**:-- - `name`: the name of the cache, used to set saving path- to manually- invalidate the cache, change the name.- - `save_path`: the folder in which to save the cache, defaults to- `__marimo__/cache` in the directory of the notebook file- - `pin_modules`: if True, the cache will be invalidated if module versions- differ between runs, defaults to False.- """-+class _cache_context(object):def __init__(self,name: str,+ loader: Loader,*,- save_path: str | None = None,pin_modules: bool = False,- _loader: Optional[Loader] = None,+ hash_type: str = DEFAULT_HASH,) -> None:# For an implementation sibling regarding the block skipping, see# `withhacks` in pypi.self.name = name- 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")-- if _loader:- self._loader = _loader- else:- self._loader = PickleLoader(name, save_path)self._skipped = Trueself._cache: Optional[Cache] = None@@ -375,6 +238,8 @@ class persistent_cache(object):self._body_start: int = MAXINT# TODO: Consider having a user level setting.self.pin_modules = pin_modules+ self.hash_type = hash_type+ self._loader = loaderdef __enter__(self) -> Self:sys.settrace(lambda *_args, **_keys: None)@@ -440,9 +305,10 @@ class persistent_cache(object):loader=self._loader,context=pre_module,pin_modules=self.pin_modules,+ hash_type=self.hash_type,)- self.cache_type = self._cache+ self.cache_type = self._cache.cache_type# Raising on the first valid line, prevents a discrepancy where# whitespace in `With`, changes behavior.self._body_start = save_module.body[0].lineno@@ -511,3 +377,427 @@ class persistent_cache(object):tmpio.seek(0)write_traceback(tmpio.read())return False+++# A note on overloading:+# Single dispatch cues off only the first argument, and expects a similar+# signature for every overload: https://peps.python.org/pep-0443/+# However.+# The context and call APIs are slightly different, so `*` expansions are used+# to propagate that information down to the actually implementation.+# As such, we also leverage the `@overload` decorator to provide the correct+# signature and documentation for the singledispatch entry points.++# mypy also seems to do pretty poorly with this overloading, so there is liberal+# removal type rules.+++def _cache_invocation(+ arg: Any,+ loader: Union[LoaderPartial, Loader, LoaderType],+ *args: Any,+ frame_offset: int = 1,+ **kwargs: Any,+) -> Union[_cache_call, _cache_context]:+ del loader, args, kwargs, frame_offset+ raise TypeError(f"Invalid type for cache: {type(arg)}")+++def _invoke_call(+ _fn: Callable[..., Any] | None,+ loader: Union[LoaderPartial, Loader, LoaderType],+ *args: Any,+ frame_offset: int = 1,+ **kwargs: Any,+) -> _cache_call:+ if isinstance(loader, Loader):+ raise TypeError(+ "A loader instance cannot be passed to cache directly. "+ f"Specify a loader type (e.g. `{loader.__class__}`) or a loader "+ f"partial (e.g. `{loader.__class__}.partial(arg=value)`)."+ )+ elif isinstance(loader, type) and issubclass(loader, Loader):+ cache_args = {+ "pin_modules": kwargs.pop("pin_modules", False),+ "hash_type": kwargs.pop("hash_type", DEFAULT_HASH),+ }+ loader = cast(Loader, loader).partial(**kwargs)+ kwargs = cache_args++ if not isinstance(loader, LoaderPartial):+ raise TypeError(+ "Invalid loader type. "+ f"Expected a loader partial, got {type(loader)}."+ )+ return _cache_call(+ _fn, loader, *args, frame_offset=frame_offset + 1, **kwargs+ )+++@_cache_invocation.register+def _invoke_call_none(+ _fn: None,+ loader: Union[LoaderPartial, Loader, LoaderType],+ *args: Any,+ frame_offset: int = 1,+ **kwargs: Any,+) -> _cache_call:+ return _invoke_call(+ _fn, loader, *args, frame_offset=frame_offset + 1, **kwargs+ )+++@_cache_invocation.register+def _invoke_call_fn(+ # mypy would like some generics, but this breaks the singledispatch+ _fn: abc.Callable, # type: ignore[type-arg]+ loader: Union[LoaderPartial, Loader, LoaderType],+ *args: Any,+ frame_offset: int = 1,+ **kwargs: Any,+) -> _cache_call:+ return _invoke_call(+ _fn, loader, *args, frame_offset=frame_offset + 1, **kwargs+ )+++@_cache_invocation.register+def _invoke_context(+ name: str,+ loader: Union[LoaderPartial, Loader, LoaderType],+ *args: Any,+ frame_offset: int = 1,+ **kwargs: Any,+) -> _cache_context:+ del frame_offset++ if isinstance(loader, LoaderPartial):+ loader = loader.create_or_reconfigure(name)()+ elif isinstance(loader, type) and issubclass(loader, Loader):+ cache_args = {+ "pin_modules": kwargs.pop("pin_modules", False),+ "hash_type": kwargs.pop("hash_type", DEFAULT_HASH),+ }+ # Create through partial for meaningful error message.+ loader = (+ cast(Loader, loader)+ .partial(**kwargs)+ .create_or_reconfigure(name)()+ )+ kwargs = cache_args+ return _cache_context(name, loader, *args, **kwargs)+++@overload+def cache(+ fn: Optional[Callable[..., Any]] = None,+ pin_modules: bool = False,+ loader: LoaderPartial | LoaderType = MemoryLoader, # type: ignore[assignment]+) -> _cache_call: ...+++@overload+def cache(+ name: str,+ pin_modules: bool = False,+ loader: LoaderPartial | Loader | LoaderType = MemoryLoader, # type: ignore[assignment]+) -> _cache_context: ...+++def cache( # type: ignore[misc]+ name: Union[str, Optional[Callable[..., Any]]] = None,+ *args: Any,+ loader: Optional[Union[LoaderPartial, Loader]] = None,+ _frame_offset: int = 1,+ _internal_interface_not_for_external_use: None = None,+ **kwargs: Any,+) -> Union[_cache_call, _cache_context]:+ """## Cache the value of a function based on args and closed-over variables.++ Decorating a function with `@mo.cache` will cache its value based on+ the function's arguments, closed-over values, and the notebook code.++ **Usage.**++ ```python+ import marimo as mo+++ @mo.cache+ def fib(n):+ if n <= 1:+ return n+ return fib(n - 1) + fib(n - 2)+ ```++ `mo.cache` is similar to `functools.cache`, but with three key benefits:++ 1. `mo.cache` persists its cache even if the cell defining the+ cached function is re-run, as long as the code defining the function+ (excluding comments and formatting) has not changed.+ 2. `mo.cache` keys on closed-over values in addition to function arguments,+ preventing accumulation of hidden state associated with+ `functools.cache`.+ 3. `mo.cache` does not require its arguments to be+ hashable (only pickleable), meaning it can work with lists, sets, NumPy+ arrays, PyTorch tensors, and more.++ `mo.cache` obtains these benefits at the cost of slightly higher overhead+ than `functools.cache`, so it is best used for expensive functions.++ Like `functools.cache`, `mo.cache` is thread-safe.++ The cache has an unlimited maximum size. To limit the cache size, use+ `@mo.lru_cache`. `mo.cache` is slightly faster than `mo.lru_cache`, but in+ most applications the difference is negligible.++ Note, `mo.cache` can also be used as a drop in replacement for context block+ caching like `mo.persistent_cache`.++ **Args**:++ - `pin_modules`: if True, the cache will be invalidated if module versions+ differ.++ ## Context manager to cache the return value of a block of code.++ The `mo.cache` context manager lets you delimit a block of code in which+ variables will be cached to memory when they are first computed.++ By default, the cache is stored in memory and is not persisted across kernel+ runs, for that functionality, refer to `mo.persistent_cache`.++ **Usage.**++ ```python+ with mo.cache("my_cache") as cache:+ variable = expensive_function()+ ```++ **Args**:++ - `name`: the name of the cache, used to set saving path- to manually+ invalidate the cache, change the name.+ - `pin_modules`: if True, the cache will be invalidated if module versions+ differ.+ - `loader`: the loader to use for the cache, defaults to `MemoryLoader`.+ """+ arg = name+ del name++ if loader is None:+ loader = MemoryLoader.partial(max_size=-1)++ return _cache_invocation(+ arg,+ loader,+ *args,+ frame_offset=_frame_offset + 1,+ **kwargs,+ )+++@overload+def lru_cache(+ fn: Optional[Callable[..., Any]] = None,+ maxsize: int = 128,+ pin_modules: bool = False,+) -> _cache_call: ...+++@overload+def lru_cache(+ name: str,+ maxsize: int = 128,+ pin_modules: bool = False,+) -> _cache_call: ...+++def lru_cache( # type: ignore[misc]+ name: Union[str, Optional[Callable[..., Any]]] = None,+ maxsize: int = 128,+ *args: Any,+ _internal_interface_not_for_external_use: None = None,+ **kwargs: Any,+) -> Union[_cache_call, _cache_context]:+ """Decorator for LRU caching the return value of a function.++ `mo.lru_cache` is a version of `mo.cache` with a bounded cache size. As an+ LRU (Least Recently Used) cache, only the last used `maxsize` values are+ retained, with the oldest values being discarded. For more information,+ see the documentation of `mo.cache`.++ **Usage.**++ ```python+ import marimo as mo+++ @mo.lru_cache+ def factorial(n):+ return n * factorial(n - 1) if n else 1+ ```++ **Args**:++ - `maxsize`: the maximum number of entries in the cache; defaults to 128.+ Setting to -1 disables cache limits.+ - `pin_modules`: if True, the cache will be invalidated if module versions+ differ.++ ## Context manager for LRU caching the return value of a block of code.++ **Args**:++ - `name`: Namespace key for the cache.+ - `maxsize`: the maximum number of entries in the cache; defaults to 128.+ Setting to -1 disables cache limits.+ - `pin_modules`: if True, the cache will be invalidated if module versions+ differ.+ """+ arg = name+ del name++ if {"loader"} & set(kwargs.keys()):+ raise ValueError(+ "loader is not a valid argument "+ "for lru_cache, use mo.cache instead."+ )++ return cache( # type: ignore[no-any-return, call-overload]+ arg,+ *args,+ loader=MemoryLoader.partial(max_size=maxsize),+ _frame_offset=2,+ **kwargs,+ )+++@overload+def persistent_cache(+ name: str,+ save_path: str | None = None,+ pin_modules: bool = False,+) -> _cache_context: ...+++@overload+def persistent_cache(+ fn: Optional[Callable[..., Any]] = None,+ save_path: str | None = None,+ pin_modules: bool = False,+) -> _cache_call: ...+++def persistent_cache( # type: ignore[misc]+ name: Union[str, Optional[Callable[..., Any]]] = None,+ save_path: str | None = None,+ *args: Any,+ _internal_interface_not_for_external_use: None = None,+ **kwargs: Any,+) -> Union[_cache_call, _cache_context]:+ """## Context manager to save variables to disk and restore them thereafter.++ The `mo.persistent_cache` context manager lets you delimit a block of code+ in which variables will be cached to disk when they are first computed. On+ subsequent runs of the cell, if marimo determines that this block of code+ hasn't changed and neither has its ancestors, it will restore the variables+ from disk instead of re-computing them, skipping execution of the block+ entirely.++ Restoration happens even across notebook runs, meaning you can use+ `mo.persistent_cache` to make notebooks start *instantly*, with variables+ that would otherwise be expensive to compute already materialized in+ memory.++ **Usage.**++ ```python+ with persistent_cache(name="my_cache"):+ variable = expensive_function() # This will be cached to disk.+ print("hello, cache") # this will be skipped on cache hits+ ```++ In this example, `variable` will be cached the first time the block+ is executed, and restored on subsequent runs of the block. If cache+ conditions are hit, the contents of `with` block will be skipped on+ execution. This means that side-effects such as writing to stdout and+ stderr will be skipped on cache hits.++ Note that `mo.state` and `UIElement` changes will also trigger cache+ invalidation, and be accordingly updated.++ **Warning.** Since context abuses sys frame trace, this may conflict with+ debugging tools or libraries that also use `sys.settrace`.++ **Args**:++ - `name`: the name of the cache, used to set saving path- to manually+ invalidate the cache, change the name.+ - `save_path`: the folder in which to save the cache, defaults to+ `__marimo__/cache` in the directory of the notebook file+ - `pin_modules`: if True, the cache will be invalidated if module versions+ differ between runs, defaults to False.+++ ## Decorator for persistently caching the return value of a function.++ `persistent_cache` can also be used as a drop in function-level memoization+ for `@mo.cache` or `@mo.lru_cache`. This is much slower than cache, but+ can be useful for saving function values between kernel restarts. For more+ details, refer to `mo.cache`.++ **Usage.**++ ```python+ import marimo as mo+++ @mo.persistent_cache+ def my_expensive_function():+ # Do expensive things++ # or++ @mo.persistent_cache(save_path="my/path/to/cache")+ def my_expensive_function_cached_in_a_certain_location():+ # Do expensive things+ ```++ **Args**:++ - `fn`: the wrapped function if no settings are passed.+ - `save_path`: the folder in which to save the cache, defaults to+ `__marimo__/cache` in the directory of the notebook file+ - `pin_modules`: if True, the cache will be invalidated if module versions+ differ between runs, defaults to False.+ """++ arg = name+ del name++ if {"loader"} & set(kwargs.keys()):+ raise ValueError(+ "loader is not a valid argument "+ "for persistent_cache, use mo.cache instead."+ )++ if save_path is None and (root := notebook_dir()) is not None:+ save_path = str(root / "__marimo__" / "cache")+ elif save_path is None:+ # This can happen if the notebook file is unnamed.+ save_path = os.path.join("__marimo__", "cache")++ loader = PickleLoader.partial(save_path=Path(save_path))+ # Injection hook for testing+ if "_loader" in kwargs:+ loader = kwargs.pop("_loader")++ return cache( # type: ignore[no-any-return, call-overload]+ arg,+ *args,+ loader=loader,+ _frame_offset=2,+ **kwargs,+ )diff --git a/tests/_save/mocks.py b/tests/_save/mocks.pyindex 0b99f3374b..0ec2c73dec 100644--- a/tests/_save/mocks.py+++ b/tests/_save/mocks.py@@ -14,13 +14,13 @@ class MockLoader(Loader):data: Optional[Dict[str, Any]] = None,stateful_refs: Optional[set[str]] = None,) -> None:- self.name = nameself.save_path = save_pathself._data = data or {}self._cache_hit = data is not Noneself._loaded = Falseself._saved = Falseself._stateful_refs = stateful_refs or set()+ super().__init__(name)def cache_hit(self, _hashed_context: str, _cache_type: CacheType) -> bool:return self._cache_hitdiff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 7d1d5d9474..beb28806b0 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -58,6 +58,26 @@ class TestScriptCache:app.run()+ @staticmethod+ def test_cache_loader_api() -> None:+ app = App()+ app._anonymous_file = True++ @app.cell+ def one() -> tuple[int]:+ from tests._save.mocks import MockLoader++ with MockLoader.cache("one", data={"X": 7, "Y": 8}) as cache:+ Y = 9+ X = 10+ assert X == 7+ assert cache._cache.defs == {"X": 7, "Y": 8}+ assert not cache._loader._saved+ assert cache._loader._loaded+ return X, Y++ app.run()+@staticmethoddef test_cache_hit_whitespace() -> None:app = App()@@ -381,6 +401,7 @@ class TestAppCache:),])+ assert not k.stderr.messages, k.stderrassert k.errors == {}assert k.errors == {}assert k.globals["X"] == 1@@ -531,6 +552,62 @@ class TestStateCache:class TestCacheDecorator:+ async def test_basic_cache_api(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.loaders import MemoryLoader++ @MemoryLoader.cache+ def fib(n):+ if n <= 1:+ return n+ return fib(n - 1) + fib(n - 2)++ a = fib(5)+ b = fib(10)+ """+ ),+ ]+ )++ assert not k.stderr.messages+ assert k.globals["fib"].hits == 9++ assert k.globals["a"] == 5+ assert k.globals["b"] == 55++ async def test_basic_cache_api_with_arg(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.loaders import MemoryLoader++ @MemoryLoader.cache(max_size=2)+ def fib(n):+ if n <= 1:+ return n+ return fib(n - 1) + fib(n - 2)++ a = fib(5)+ b = fib(10)+ """+ ),+ ]+ )++ assert not k.stderr.messages+ assert k.globals["fib"].hits == 14++ assert k.globals["a"] == 5+ assert k.globals["b"] == 55+async def test_basic_cache(self, k: Kernel, exec_req: ExecReqProvider) -> None:@@ -581,7 +658,7 @@ class TestCacheDecorator:])- assert not len(k.stderr.messages)+ assert not k.stderr.messages, k.stderr# More hits with a smaller cache, because it needs to check the cache# more.assert k.globals["fib"].hits == 14@@ -589,6 +666,69 @@ class TestCacheDecorator:assert k.globals["a"] == 5assert k.globals["b"] == 55+ async def test_lru_cache_default(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.save import lru_cache++ @lru_cache+ def fib(n):+ if n <= 1:+ return n+ return fib(n - 1) + fib(n - 2)++ a = fib(260)+ b = fib(10)+ """+ ),+ ]+ )++ assert not k.stderr.messages+ # More hits with a smaller cache, because it needs to check the cache+ # more. Has 256 entries by default, normal cache hits just 259 times.+ assert k.globals["fib"].hits == 266++ # A little ridiculous, but still low compute.+ assert (+ k.globals["a"]+ == 971183874599339129547649988289594072811608739584170445+ )+ assert k.globals["b"] == 55++ async def test_persistent_cache(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.save import persistent_cache+ from marimo._save.loaders import MemoryLoader++ @persistent_cache(_loader=MemoryLoader)+ def fib(n):+ if n <= 1:+ return n+ return fib(n - 1) + fib(n - 2)++ a = fib(5)+ b = fib(10)+ """+ ),+ ]+ )++ assert not k.stderr.messages+ assert k.globals["fib"].hits == 9++ assert k.globals["a"] == 5+ assert k.globals["b"] == 55+async def test_cross_cell_cache(self, k: Kernel, exec_req: ExecReqProvider) -> None:@@ -649,9 +789,9 @@ class TestCacheDecorator:[exec_req.get("""- from marimo._save.save import cache- from marimo._runtime.state import state- """+ from marimo._save.save import cache+ from marimo._runtime.state import state+ """),exec_req.get("""external, setter = state(0)"""),exec_req.get(@@ -679,7 +819,6 @@ class TestCacheDecorator:])- assert not k.stdout.messagesassert not k.stderr.messagesassert k.globals["a"] == 5@@ -698,10 +837,10 @@ class TestCacheDecorator:[exec_req.get("""- from marimo._save.save import cache- from marimo._runtime.state import state- import marimo as mo- """+ from marimo._save.save import cache+ from marimo._runtime.state import state+ import marimo as mo+ """),exec_req.get("slider = mo.ui.slider(0, 1)"),exec_req.get("""external, setter = state("a")"""),@@ -742,6 +881,49 @@ class TestCacheDecorator:# 2 * 9 + 2assert k.globals["fib"].hits in (9, 18, 20)+ async def test_rerun_update(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get("""from marimo._save.save import cache"""),+ exec_req.get(+ """+ from marimo._runtime.state import state+ """+ ),+ exec_req.get("""max_size, setter = state(-1)"""),+ exec_req.get(+ """from marimo._save.loaders import MemoryLoader"""+ ),+ exec_req.get("""impure = []"""),+ exec_req.get("""external = 0;c={}"""),+ exec_req.get_with_id(+ cell_id="0",+ code="""+ @cache(loader=MemoryLoader.partial(max_size=max_size()))+ def fib(n):+ if n <= 1:+ return n + external+ return fib(n - 1) + fib(n - 2)+ fib(5)+ """,+ ),+ exec_req.get("""a = fib(5)"""),+ exec_req.get("""b = fib(10); a; impure.append(b)"""),+ exec_req.get(+ """+ if len(impure) == 1:+ setter(256)+ b+ """+ ),+ ]+ )+ assert not k.stderr.messages, k.stderr+ assert not k.stdout.messages, k.stdout+ assert k.globals["fib"].hits == 10 + 3+async def test_full_scope_utilized(self, k: Kernel, exec_req: ExecReqProvider) -> None:@@ -785,7 +967,6 @@ class TestCacheDecorator:)assert not k.stderr.messages, k.stderr- assert not k.stdout.messages, k.stdoutassert len(k.globals["impure"]) == 3assert {@@ -796,16 +977,16 @@ class TestCacheDecorator:# Same name, but should be under different entriesassert (- k.globals["impure"][0][0]._loader()- is not k.globals["impure"][1][0]._loader()+ k.globals["impure"][0][0].loader+ is not k.globals["impure"][1][0].loader)assert (len({- *k.globals["impure"][0][0]._loader()._cache.keys(),- *k.globals["impure"][1][0]._loader()._cache.keys(),- *k.globals["impure"][2][0]._loader()._cache.keys(),+ *k.globals["impure"][0][0].loader._cache.keys(),+ *k.globals["impure"][1][0].loader._cache.keys(),+ *k.globals["impure"][2][0].loader._cache.keys(),})== 2@@ -861,7 +1042,6 @@ class TestCacheDecorator:)assert not k.stderr.messages, k.stderr- assert not k.stdout.messages, k.stdoutassert len(k.globals["impure"]) == 3assert {@@ -872,16 +1052,16 @@ class TestCacheDecorator:# Same name, but should be under different entriesassert (- k.globals["impure"][0][0]._loader()- is not k.globals["impure"][1][0]._loader()+ k.globals["impure"][0][0].loader+ is not k.globals["impure"][1][0].loader)assert (len({- *k.globals["impure"][0][0]._loader()._cache.keys(),- *k.globals["impure"][1][0]._loader()._cache.keys(),- *k.globals["impure"][2][0]._loader()._cache.keys(),+ *k.globals["impure"][0][0].loader._cache.keys(),+ *k.globals["impure"][1][0].loader._cache.keys(),+ *k.globals["impure"][2][0].loader._cache.keys(),})== 2