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.

docs: Expound upon mo.cache expectations and limitations (#5917)

Dylan Madisettia204848eaa74
diff --git a/docs/api/caching.md b/docs/api/caching.md
index f8f0bcda49..a8d4387cea 100644
--- a/docs/api/caching.md
+++ b/docs/api/caching.md
@@ -1,37 +1,342 @@
# Caching
-marimo comes with utilities to cache intermediate computations. These utilities
-come in two types: caching the return values of expensive functions in memory,
-and caching the values of variables to disk.
+marimo comes with utilities to cache intermediate computations. These
+utilities can be applied as decorators to functions to cache their
+returned values; you can choose between saving caches in memory or to disk.
-## Caching expensive functions
+## Basic usage
-Use [`mo.cache`][marimo.cache] to cache the return values of functions in
-memory, based on the function arguments, closed-over values, and the notebook
-code defining the function.
+marimo provides two decorators for caching the return values of expensive
+functions:
-The resulting cache is similar to `functools.cache`, but with the benefit that
-[`mo.cache`][marimo.cache] won't return stale values (because it keys on
-closed-over values) and isn't invalidated when the cell defining the decorated
-function is simply re-run (because it keys on notebook code). This means that
-like marimo notebooks, [`mo.cache`][marimo.cache] has no hidden state
-associated with the cached function, which makes you more productive while developing iteratively.
+1. [`mo.cache`][marimo.cache], which saves cached values to memory;
+2. [`mo.persistent_cache`][marimo.persistent_cache], which saves cached values to disk.
-For a cache with bounded size, use [`mo.lru_cache`][marimo.lru_cache].
+/// tab | `mo.cache`
-::: marimo.cache
-::: marimo.lru_cache
+```python
+import marimo as mo
+
+def compute_embedding(data: str, embedding_dimension: int, model: str) -> np.ndarray:
+ ...
+```
+
+///
+
+/// tab | `mo.persistent_cache`
-## Caching variables to disk
+```python
+import marimo as mo
-Use [`mo.persistent_cache`][marimo.persistent_cache] to cache variables computed in an expensive block of
-code to disk. The next time this block of code is run, if marimo detects a
-cache hit, the code will be skipped and your variables will be loaded into
-memory, letting you pick up where you left off.
+def compute_embedding(data: str, embedding_dimension: int, model: str) -> np.ndarray
+ ...
+```
-!!! tip "Cache location"
- By default, caches are stored in `__marimo__/cache/`, in the directory of the
+///
+
+Roughly speaking, the first time a cached function is called with a particular
+sequence of arguments, the function will run and its return value will be
+cached. The next time it is called with the same sequence of arguments (on
+cache hit), the function body will be skipped and the return value will be
+retrieved from cache instead.
+
+The in-memory cache ([`mo.cache`][marimo.cache]) is faster and doesn't consume disk space, but
+it is lost on notebook restart. The disk cache ([`mo.persistent_cache`][marimo.persistent_cache]) is
+slower and consumes space on disk, but it persists across notebook runs,
+letting you pick up where you left off.
+
+(For an in-memory cache of bounded size, use [`mo.lru_cache`][marimo.lru_cache].)
+
+!!! tip "Where persistent caches are stored"
+ By default, persistent caches are stored in `__marimo__/cache/`, in the directory of the
current notebook. For projects versioned with `git`, consider adding
`**/__marimo__/cache/` to your `.gitignore`.
+!!! tip "Caches are preserved even when a cell is re-run"
+ If a cell defining a cached function is re-run, the cache will be preserved unless
+ its source code (or the source code of the cell's ancestors) has changed.
+
+### Persistent cache context manager
+
+You can also use marimo's [`mo.persistent_cache`][marimo.persistent_cache] as a context manager:
+
+```python
+with mo.persistent_cache("my_cache_name"):
+ X = my_expensive_computation(data, model)
+```
+
+The next time this block of code is run, if marimo detects a cache hit, the
+code will be skipped and your variables will be loaded into memory. The cache
+key for the context manager is computed in the same way as it is computed for
+decorated functions.
+
+
+## Cache key
+
+Both `mo.cache` and `mo.persistent_cache` use the same mechanism for creating a
+cache key, differing only in where the cache is stored. The cache key is based
+on function arguments and closed-over variables.
+
+### Function arguments
+**Arguments must either be primitive, marimo UI elements, array-like, or pickleable:**
+
+1. Primitive types (strings, bytes, numbers, None) are hashed.
+2. marimo UI elements are hashed based on their value.
+3. [Array-like objects](https://numpy.org/doc/stable/reference/arrays.interface.html#object.__array_interface__) are introspected, with their values being hashed.
+4. All other objects are pickled.
+
+
+### Closed-over variables
+Syntactically closing over variables provides another way to parametrize
+functions. In this example, the variable `x` is "closed over":
+
+```python
+x = 0
+```
+
+```python
+def my_function():
+ return x + 1
+```
+
+Closed-over variables are processed in the following way:
+
+* marimo first attempts to hash or pickle the closed-over variables, just as it
+does for arguments.
+* If a closed-over variables cannot be hashed or pickled, then marimo uses the
+source code that defines the value as part of the cache key; in particular, marimo
+hashes the cell that defines the variable as well as the source code of that
+cell's ancestors. This assumes that the variable's value is a deterministic
+function of the source code that defines it, although certain side-effects
+(specifically, if a cell raised an exception or loaded from another cache)
+are taken into account.
+
+Because marimo's cache key construction can fall back to source code for
+closed-over variables, closing over variables lets you cache functions even in
+the presence of non-hashable and non-pickleable arguments.
+
+## Limitations
+
+marimo's cache has some limitations:
+
+- Side effects are not cached. This means that on a cache hit, side effects like printing, file I/O, or network requests will not occur.
+- The source code of imported modules is not used when computing the cache key.
+ - By setting `pin_modules` to `True`, you can ensure that the cache is invalidated when module versions change (`e.g.`, update when the module's `__version__` attribute changes).
+ - This limitation does not apply if the external module is a marimo notebook.
+- The return values of persistently cached functions must be serializable with pickle.
+
+<!--!!! note "Persistent cache invalidation across marimo library versions"-->
+<!-- marimo promises not to invalidate caches across patch (e.g. `0.x.y` ->-->
+<!-- `0.x.z`) versions of the library. Between minor (`0.a.b` -> `0.c.0`) and major-->
+<!-- (`0.a.b` -> `1.0.0`) versions of marimo, old persistent cache hits may become-->
+<!-- invalid. A notice will be provided in the release notes when this occurs.-->
+<!-- Overall, the caching mechanism is expected to be stable.-->
+<!---->
+
+!!! warning "Don't mutate variables"
+ marimo works best when you don't mutate variables across cells. The same
+ is true for caching, since the cache key may not always be able to take
+ mutations into account.
+
+
+### Decorators defined in other Python modules
+
+Decorators defined in other Python modules that do not use `functools.wraps`
+cannot be correctly cached. This can lead to confusing bugs like the example
+below:
+
+
+```python
+# my_lib.py
+def my_decorator(func):
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+```
+
+```python
+# Cell 1
+from my_lib import my_decorator
+
+@my_decorator
+def expensive_function():
+ # ... some computation
+ return "result1"
+
+@my_decorator
+def another_expensive_function():
+ # ... different computation
+ return "result2"
+
+# This assertion may unexpectedly pass due to cache collision!
+assert expensive_function() == another_expensive_function(), "But why?"
+```
+
+The fix is to make sure the decorator uses `functools.wraps`:
+
+```python
+# my_lib.py (fixed)
+from functools import wraps
+
+def my_decorator(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+```
+
+In this instance, the cache will work as expected because the decorated function has the same signature and metadata as the original function.
+## Comparison with `functools.cache`
+
+Here is a table comparing marimo's cache with `functools.cache`:
+
+| Feature | marimo cache | `functools.cache` |
+|-------- | ------------------|-----------------|
+| Cache return values in memory? | ✅ | ✅ |
+| Cache return values to disk?| ✅ | ❌ |
+| Preserved on cell re-runs? | ✅ | ❌ |
+| Tracks closed-over variables | ✅ | ❌ |
+| Allows unhashable arguments? | ✅ | ❌ |
+| Allows Array-like arguments? | ✅ | ❌ |
+| Suitable for lightweight functions (microseconds)? | ❌ | ✅ |
+
+
+!!! tip "When to use `functools.cache`"
+ Prefer `functools.cache` for extremely lightweight functions
+ (that execute in less than a millisecond). Using memoization to calculate
+ the Fibonacci sequence is a classic example of using `functools.cache`
+ effectively. On a basic macbook in pure python, `fib(35)` takes 1 second to
+ compute; with `mo.cache` it takes 0.000229 seconds; with `functools.cache`, it
+ takes 0.000025 seconds (x9 faster!!). Although relatively small, the additional overhead of
+ `mo.cache` (and more so `mo.persistent_cache`) is larger than
+ `functools.cache`. If your function takes more than a few milliseconds to
+ compute, the difference is negligible.
+
+
+## Tips
+
+### Isolate cached code blocks to their own cells
+
+Isolating cached functions in separate cells improves cache reliability. When
+dependencies and cached functions are in the same cell, any change to the cell
+invalidates the cache, even if the cached function itself hasn't changed.
+Separating them ensures the cache is only invalidated when the function
+actually changes.
+
+**Don't do this:**
+```python
+# Cell 1
+llm_client = ...
+def prompt_llm(query, **kwargs):
+ message = {"role": "user", "content": query}
+ return llm_client.chat.completions.create(messages=[message], **kwargs)
+```
+
+**Do this instead:**
+
+```python
+# Cell 1
+llm_client = ...
+```
+
+```python
+# Cell 2
+def prompt_llm(query, **kwargs):
+ message = {"role": "user", "content": query}
+ return llm_client.chat.completions.create(messages=[message], **kwargs)
+```
+
+### Close over unhashable or un-pickleable arguments
+
+The [cache key](#cache-key) is constructed in part by hashing or pickle-ing function arguments. When you call a cached function with arguments that cannot be processed in this way, an exception will be raised. To parametrize cached functions with unhashable or un-pickleable arguments, syntactically close over them instead.
+
+**You can't do this:**
+```python
+# Cell 1
+def query_database(query, engine):
+ return engine.execute(query)
+```
+
+```python
+# This won't work because my_database_engine is not hashable
+query_database("SELECT * FROM my_table", my_database_engine)
+```
+
+Instead, you can close over `my_database_engine`:
+
+**Do this:**
+
+```python
+# Cell 1
+my_database_engine = ...
+```
+
+```python
+# Cell 2
+def query_database(query):
+ return my_database_engine.execute(query)
+```
+
+### Close-over low-memory-footprint variables
+
+Non-primitive closed-over variables are serialized for cache key generation.
+When possible, compute derived values (like length) outside the cache block and
+only use the small values inside.
+
+**Don't do this:**
+```python
+with mo.persistent_cache("bad example"):
+ length = len(my_very_large_dataset)
+ ... # uses length
+```
+
+**Do this instead:**
+```python
+length = len(my_very_large_dataset) # my_very_large_dataset is not needed for cache invalidation
+```
+
+```python
+with mo.persistent_cache("good example"):
+ ... # uses length
+```
+
+
+### Use `mo.watch.file` when working with files
+
+**Don't do this:**
+```python
+my_file = open("my_file.txt")
+with mo.persistent_cache("my_file"):
+ data = my_file.read()
+ # Do something with data
+my_file.close()
+```
+
+**Do this instead:**
+```python
+# Cell 1
+my_file = mo.watch.file("my_file.txt")
+```
+
+```python
+# Cell 2
+with mo.persistent_cache("my_file"):
+ data = my_file.read()
+ # Do something with data
+```
+
+## API
+
+::: marimo.cache
+::: marimo.lru_cache
::: marimo.persistent_cache
+
+
diff --git a/docs/guides/expensive_notebooks.md b/docs/guides/expensive_notebooks.md
index ce1d34a971..b54166a0d7 100644
--- a/docs/guides/expensive_notebooks.md
+++ b/docs/guides/expensive_notebooks.md
@@ -74,114 +74,40 @@ Learn more about exporting notebooks in our [exporting guide](../guides/exportin
## Caching
-marimo provides two caching utilities to help you manage expensive computations:
+marimo provides two decorators to cache the return values of expensive functions:
1. In-memory caching with [`mo.cache`][marimo.cache]
2. Disk caching with [`mo.persistent_cache`][marimo.persistent_cache]
Both utilities can be used as decorators or context managers.
-### In-memory caching
-
-Use [`mo.cache`][marimo.cache] to cache the return values of
-expensive functions, based on their arguments:
-
-/// tab | decorator
+/// tab | `mo.cache`
```python
import marimo as mo
@mo.cache
-def compute_predictions(problem_parameters):
- # do some expensive computations and return a value
- ...
-```
-
-///
-
-/// tab | context manager
-
-```python
-import marimo as mo
-
-with mo.cache("my_cache") as c:
- predictions = compute_predictions(problem_parameters):
-```
-
-///
-
-
-When `compute_predictions` is called with a value of
-`problem_parameters` it hasn't seen, it will compute the predictions and store
-them in an in-memory cache. The next time it is called with the same
-parameters, instead of recomputing the predictions, it will return the
-previously computed value from the cache.
-
-??? note "Comparison to `functools.cache`"
-
- [`mo.cache`][marimo.cache] is like `functools.cache` but smarter.
- `functools` will sometimes evict values from the cache when it doesn't need to.
-
- In particular, consider the case when a cell defining a `@mo.cache`-d function
- re-runs due to an ancestor of it running, or a UI element value changing.
- `mo.cache` will analyze the dataflow graph to determine whether or not the
- decorated function has changed, and if it hasn't, it's cache won't be
- invalidated. In contrast, on re-run a `functools` cache is always invalidated,
- because `functools` has no knowledge about the structure of marimo's dataflow
- graph.
-
- Conversely, [`mo.cache`][marimo.cache] knows to invalidate the cache if
- closed over variables change, whereas `functools.cache` doesn't, yielding
- incorrect cache hits.
-
- [`mo.cache`][marimo.cache] is slightly slower than `functools.cache`, but
- in most applications the overhead is negligible. For performance critical code,
- where the decorated function will be called in a tight loop, prefer
- `functools.cache`.
-
-### Disk caching
-
-Use [`mo.persistent_cache`][marimo.persistent_cache] to cache variables to
-disk. The next time your run your notebook, the cached variables will be loaded
-from disk instead of being recomputed, letting you pick up where you left off.
-
-Reserve this for expensive computations that you would like to persist across
-notebook restarts. Cached outputs are automatically saved to `__marimo__/cache`.
-
-**Example.**
-
-/// tab | decorator
-
-```python
-import marimo as mo
-
[email protected]_cache(name="my_cache")
-def compute_predictions(problem_parameters):
- # do some expensive computations and return a value
+def compute_embedding(data: str, embedding_dimension: int, model: str) -> np.ndarray:
...
```
-///
+///
-/// tab | context manager
+/// tab | `mo.persistent_cache`
```python
import marimo as mo
-with mo.persistent_cache(name="my_cache"):
- # This block of code and its computed variables will be cached to disk
- # the first time it's run. The next time it's run, `predictions``
- # will be loaded from disk.
- predictions = compute_predictions(problem_parameters)
+def compute_embedding(data: str, embedding_dimension: int, model: str) -> np.ndarray
...
```
///
-Roughly speaking, [`mo.persistent_cache`][marimo.persistent_cache] registers a
-cache hit when the cell is not stale, meaning its code hasn't changed and
-neither have its ancestors. On cache hit the code block won't execute and
-instead variables will be loaded into memory.
+
+See our [guide on caching](../api/caching.md) for details, including how the cache
+key is constructed, and limitations.
## Lazy-load expensive UIs
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index 9dc09475ad..6ca257dd6c 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -770,6 +770,12 @@ class BlockHasher:
NB. "Hashable" types are primitives, data primitives, and pure
functions. With modules being "hashed" by version number, or ignored.
+ The current "hashables" are:
+ - module (with pin by version)
+ - primitive (bytes, str, numbers.Number, type(None))
+ - data primitive (e.g. numpy array, torch tensor)
+ - external module definitions (imported anything)
+
Args:
refs: A set of reference names unaccounted for.
scope: A dictionary representing the current scope.
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index c845b887a5..9279ef69a0 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -947,18 +947,12 @@ def persistent_cache( # type: ignore[misc]
`__marimo__/cache` in the directory of the notebook file
method: the serialization method to use, current options are "json",
and "pickle" (default).
- pin_modules: if True, the cache will be invalidated if module versions
- differ between runs, defaults to False.
store: optional store.
- **kwargs: keyword arguments passed to `cache()`
- *args: positional arguments passed to `cache()`
fn: the wrapped function if no settings are passed.
- save_path: the folder in which to save the cache, defaults to
- `__marimo__/cache` in the directory of the notebook file
- method: the serialization method to use, current options are "json",
- and "pickle" (default).
+ *args: positional arguments passed to `cache()`
pin_modules: if True, the cache will be invalidated if module versions
differ between runs, defaults to False.
+ **kwargs: keyword arguments passed to `cache()`
"""
arg = name