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.

feat: @marimo.cache + tests and documentation (#2318)

Dylan Madisettic02131d9845b
diff --git a/.gitignore b/.gitignore
index 631f791898..e7e5741624 100644
--- a/.gitignore
+++ b/.gitignore
@@ -111,3 +111,4 @@ marimo/_lsp/
.marimo.toml
.mypy_cache/
+__marimo__
diff --git a/docs/api/caching.md b/docs/api/caching.md
new file mode 100644
index 0000000000..27bffb7e0f
--- /dev/null
+++ b/docs/api/caching.md
@@ -0,0 +1,40 @@
+# 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.
+
+## Caching expensive functions
+
+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.
+
+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.
+
+For a cache with bounded size, use [`mo.lru_cache`](#marimo.lru_cache).
+
+
+```{eval-rst}
+.. autofunction:: marimo.cache
+```
+
+```{eval-rst}
+.. autofunction:: marimo.lru_cache
+```
+
+## Caching variables to disk
+
+Use `mo.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.
+
+```{eval-rst}
+.. autofunction:: marimo.persistent_cache
+```
diff --git a/docs/api/index.md b/docs/api/index.md
index a70d26ebf5..68e0c65fd0 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -17,6 +17,7 @@
html
query_params
cli_args
+ caching
state
app
cell
@@ -45,6 +46,7 @@ Use the marimo library in marimo notebooks (`import marimo as mo`) to
| {doc}`html` | Manipulate HTML objects |
| {doc}`query_params` | Access and set query parameters with `mo.query_params` |
| {doc}`cli_args` | Access command-line arguments with `mo.cli_args` |
+| {doc}`caching` | Cache expensive computations in memory or on disk |
| {doc}`state` | Synchronize multiple UI elements with `mo.state` |
| {doc}`app` | Embed notebooks in other notebooks |
| {doc}`cell` | Run cells defined in another notebook |
diff --git a/docs/faq.md b/docs/faq.md
index f01a68e18d..a59344e8f3 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -192,13 +192,16 @@ kick off expensive cells before you're ready to run them.
_Here are some tips to avoid accidental execution of expensive cells:_
-- [Disable expensive cells](guides/reactivity.md#disabling-cells).
-When a cell is disabled, it and its descendants are blocked from running.
-- Use Python's `functools.cache` to cache expensive
-intermediate computations (see our [best practices guide](/guides/best_practices/index.md)).
-- Wrap UI elements in a [form](/api/inputs/form.md#marimo.ui.form).
-- Use [`mo.stop`](/api/control_flow.md#marimo.stop) to conditionally stop
+- [Disable expensive cells](guides/reactivity.md#disabling-cells). When a cell
+ is disabled, it and its descendants are blocked from running.
+- Wrap UI elements in a [form](api/inputs/form.md#marimo.ui.form).
+- Use [`mo.stop`](api/control_flow.md#marimo.stop) to conditionally stop
execution of a cell and its descendants.
+- Decorate functions with marimo's [`mo.cache`](#marimo.cache) to cache
+ expensive intermediate computations.
+- Use [`mo.persistent_cache`](#marimo.persistent_cache) to cache variables to
+ disk; on re-run, marimo will read values from disk instead of recalculating
+ them as long as the cell is not stale.
- Disable automatic execution in the [runtime configuration](/guides/runtime_configuration.md).
<a name="faq-lazy"></a>
@@ -208,6 +211,9 @@ intermediate computations (see our [best practices guide](/guides/best_practices
You can disable automatic execution through the notebook runtime settings;
see the [guide on runtime configuration](/guides/runtime_configuration.md).
+When automatic execution is disabled, marimo still gives you guarantees on
+your notebook state and automatically marks cells as stale when appropriate.
+
<a name="faq-interactivity"></a>
### How do I use sliders and other interactive elements?
diff --git a/docs/guides/best_practices/performance.md b/docs/guides/best_practices/performance.md
index 66c0b6b781..83a2e21aea 100644
--- a/docs/guides/best_practices/performance.md
+++ b/docs/guides/best_practices/performance.md
@@ -1,23 +1,76 @@
# Performance
-## Cache computations with `@functools.cache`
+## Disable autorun
-Use Python's builtin `functools` library to cache expensive computations.
+For expensive notebooks, you can [disable automatic execution](/guides/reactivity.md#runtime-configuration).
-For example,
+## Cache computations with `@mo.cache`
+
+Use [`mo.cache`](#marimo.cache) to cache the return values of
+expensive functions, based on their arguments:
```python
-import functools
+import mo
def compute_predictions(problem_parameters):
- ...
+ # do some expensive computations and return a value
+ ...
```
-Whenever `compute_predictions` is called with a value of `problem_parameters`
-it has not seen, it will compute the predictions and store them in a 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.
+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.
+
+:::{dropdown} Comparison to `functools.cache`
+
+`mo.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 use sophisticated analysis of 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` knows to invalidate the cache if closed over variables
+change, whereas `functools.cache` doesn't, yielding incorrect cache hits.
+
+`mo.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`.
+:::
+
+## Save/load from disk with `mo.persistent_cache`
+
+Use `mo.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.**
+
+```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, `my_variable`
+ # will be loaded from disk.
+ my_variable = some_expensive_function()
+ ...
+```
+
+Roughly speaking, `mo.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.
## Disable expensive cells
@@ -26,10 +79,6 @@ helpful when you want to edit one part of a notebook without triggering
execution of other parts. See the
[reactivity guide](/guides/reactivity.md#disabling-cells) for more info.
-## Disable notebook autorun
-
-For expensive notebooks, you can [disable autorun](/guides/reactivity.md#runtime-configuration).
-
## Lazy-load expensive elements or computations
You can lazily render UI elements that are expensive to compute using `marimo.lazy`.
diff --git a/docs/recipes.md b/docs/recipes.md
index f20f3f2c60..9bce07381e 100644
--- a/docs/recipes.md
+++ b/docs/recipes.md
@@ -563,7 +563,7 @@ mo.md("#" + "🍃" * button.value) if button.value > 0 else None
## Caching
-### Cache expensive computations
+### Cache function outputs in memory
**Use case.** Because marimo runs cells automatically as code and
UI elements change, it can be helpful to cache expensive intermediate
@@ -573,12 +573,12 @@ for different configurations of the elements would greatly speed up your noteboo
**Recipe.**
-1. Use `functools` to cache function outputs given inputs.
+1. Use [`mo.cache`](#marimo.cache) to cache function outputs given inputs.
```python
-import functools
+import marimo as mo
def compute_predictions(problem_parameters):
# replace with your own function/parameters
...
@@ -589,4 +589,26 @@ it has not seen, it will compute the predictions and store them in a 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.
-See our [best practices guide](guides/best_practices) to learn more.
+### Persistent caching for very expensive computations
+
+**Use case.** If you are using marimo to capture very compute intensive
+results, you may want to save the state of your computations to disk. Ideally,
+if you update your code, then this save should be invalidated. It may also be
+advantageous to add UI elements to explore your results, without having to
+recompute expensive computations. You can achieve this with
+[`mo.persistent_cache`](#marimo.persistent_cache).
+
+**Recipe.**
+
+1. Use `mo.persistent_cache` to cache blocks of code to disk.
+
+```python
+import marimo as mo
+
+with mo.persistent_cache("my_cache"):
+ # This block of code, and results will be cached to disk
+ ...
+```
+
+If the execution conditions are the same, then cache will load results from
+disk, and populate variable definitions.
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 09f779527f..f480ca95dd 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -31,6 +31,7 @@ __all__ = [
"app_meta",
"as_html",
"audio",
+ "cache",
"callout",
"capture_stderr",
"capture_stdout",
@@ -47,6 +48,7 @@ __all__ = [
"image",
"lazy",
"left",
+ "lru_cache",
"md",
"mermaid",
"mpl",
@@ -54,8 +56,9 @@ __all__ = [
"notebook_dir",
"output",
"pdf",
- "plain_text",
+ "persistent_cache",
"plain",
+ "plain_text",
"query_params",
"redirect_stderr",
"redirect_stdout",
@@ -127,5 +130,6 @@ from marimo._runtime.runtime import (
refs,
)
from marimo._runtime.state import state
+from marimo._save.save import cache, lru_cache, persistent_cache
from marimo._server.asgi import create_asgi_app
from marimo._sql.sql import sql
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index 5dbdcf1668..9bc5468dd3 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import sys
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Iterator, Optional
@@ -18,6 +19,10 @@ from marimo._runtime.context.types import (
from marimo._runtime.dataflow import DirectedGraph
from marimo._runtime.functions import FunctionRegistry
from marimo._runtime.params import CLIArgs, QueryParams
+from marimo._runtime.patches import (
+ create_main_module,
+ patch_main_module_context,
+)
from marimo._runtime.state import State, StateRegistry
if TYPE_CHECKING:
@@ -42,7 +47,12 @@ class ScriptRuntimeContext(RuntimeContext):
@property
def globals(self) -> dict[str, Any]:
- return {}
+ with patch_main_module_context(
+ create_main_module(file=None, input_override=None)
+ ) as module:
+ glbls = module.__dict__
+ glbls.update(sys.modules["__main__"].__dict__)
+ return glbls
@property
def execution_context(self) -> ExecutionContext | None:
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index f7b995f0c4..c30204af1f 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -178,7 +178,9 @@ def _store_state_reference(
# Associate state variables with variable names
ctx = get_context()
ctx.state_registry.register_scope(runner.glbls, defs=cell.defs)
- ctx.state_registry.retain_active_states(set(runner.glbls.keys()))
+ ctx.state_registry.retain_active_states(
+ set(runner.graph.definitions.keys())
+ )
@kernel_tracer.start_as_current_span("broadcast_outputs")
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
index 43801850f8..22912d56e2 100644
--- a/marimo/_runtime/state.py
+++ b/marimo/_runtime/state.py
@@ -20,19 +20,38 @@ class StateItem(Generic[T]):
ref: weakref.ref[State[T]]
-class StateRegistry:
- _states: dict[str, StateItem[Any]] = {}
- # id -> variable name for state
- # NB. python reuses IDs, but an active pruning of the registry should help
- # protect against this.
- _inv_states: dict[Id, set[str]] = {}
+def extract_name(key: str) -> str:
+ # Some variables may use a state internally, as such the lookup needs a
+ # context qualifier. We delimit the context and name with a colon, which is
+ # not a valid python variable name character.
+ return key.split(":")[-1]
+
- def register(self, state: State[T], name: Optional[str] = None) -> None:
+class StateRegistry:
+ def __init__(self) -> None:
+ # variable name -> state
+ # State registry is pruned based on the variable definitions in scope.
+ self._states: dict[str, StateItem[Any]] = {}
+ # id -> variable name for state
+ # NB. python reuses IDs, but an active pruning of the registry should
+ # help protect against this.
+ self._inv_states: dict[Id, set[str]] = {}
+
+ def register(
+ self,
+ state: State[T],
+ name: Optional[str] = None,
+ context: Optional[str] = None,
+ ) -> None:
if name is None:
name = str(uuid4())
+ if context is not None:
+ name = f"{context}:{name}"
+
if id(state) in self._inv_states:
ref = next(iter(self._inv_states[id(state)]))
- if self._states[ref].id != id(state):
+ # Check for duplicate state ids and clean up accordingly
+ if id(self._states[ref].ref()) != id(state):
for ref in self._inv_states[id(state)]:
del self._states[ref]
self._inv_states[id(state)].clear()
@@ -65,19 +84,29 @@ class StateRegistry:
"""Retains only the active states in the registry."""
# Remove all non-active states by name
active_state_ids = set()
- for state_name in list(self._states.keys()):
- if state_name not in active_variables:
- self._inv_states.pop(id(self._states[state_name]), None)
- del self._states[state_name]
+ for state_key in list(self._states.keys()):
+ if extract_name(state_key) not in active_variables:
+ id_key = id(self._states[state_key])
+ lookup = self._inv_states.get(id_key, None)
+ if lookup is not None:
+ if state_key in lookup:
+ lookup.remove(state_key)
+ if not lookup:
+ del self._inv_states[id_key]
+ del self._states[state_key]
else:
- active_state_ids.add(id(self._states[state_name]))
+ active_state_ids.add(id(self._states[state_key]))
# Remove all non-active states by id
for state_id in list(self._inv_states.keys()):
if state_id not in active_state_ids:
del self._inv_states[state_id]
- def lookup(self, name: str) -> Optional[State[T]]:
+ def lookup(
+ self, name: str, context: Optional[str] = None
+ ) -> Optional[State[T]]:
+ if context is not None:
+ name = f"{context}:{name}"
if name in self._states:
return self._states[name].ref()
return None
@@ -96,6 +125,8 @@ class State(Generic[T]):
value: T,
allow_self_loops: bool = False,
_registry: Optional[StateRegistry] = None,
+ _name: Optional[str] = None,
+ _context: Optional[str] = None,
) -> None:
self._value = value
self.allow_self_loops = allow_self_loops
@@ -104,7 +135,7 @@ class State(Generic[T]):
try:
if _registry is None:
_registry = get_context().state_registry
- _registry.register(self)
+ _registry.register(self, _name, _context)
except ContextNotInitializedError:
# Registration may be picked up later, but there is nothing to do
# at this point.
diff --git a/marimo/_save/__init__.py b/marimo/_save/__init__.py
index be52407b50..00fdd04c7d 100644
--- a/marimo/_save/__init__.py
+++ b/marimo/_save/__init__.py
@@ -1 +1,4 @@
# Copyright 2024 Marimo. All rights reserved.
+from marimo._save.save import cache, lru_cache, persistent_cache
+
+__all__ = ["cache", "lru_cache", "persistent_cache"]
diff --git a/marimo/_save/ast.py b/marimo/_save/ast.py
index 9c55eabae1..b602ab8636 100644
--- a/marimo/_save/ast.py
+++ b/marimo/_save/ast.py
@@ -2,7 +2,9 @@
from __future__ import annotations
import ast
-from typing import Any, Sequence, cast
+import inspect
+import textwrap
+from typing import Any, Callable, Sequence, cast
from marimo._utils.variables import unmangle_local
@@ -140,3 +142,27 @@ class DeprivateVisitor(ast.NodeTransformer):
if hasattr(node, "name") and node.name:
node.name = unmangle_local(node.name).name
return super().generic_visit(node)
+
+
+class RemoveReturns(ast.NodeTransformer):
+ # NB: Won't work for generators since not replacing Yield.
+ # Note that functools caches the generator, which is then dequeue'd,
+ # so in that sense, it doesn't work either.
+ def visit_Return(self, node: ast.Return) -> ast.Expr:
+ expr = ast.Expr(value=node.value)
+ expr.lineno = node.lineno
+ expr.col_offset = node.col_offset
+ return expr
+
+
+def strip_function(fn: Callable[..., Any]) -> ast.Module:
+ code, _ = inspect.getsourcelines(fn)
+ function_ast = ast.parse(textwrap.dedent("".join(code)))
+ body = function_ast.body.pop()
+ assert isinstance(
+ body, (ast.FunctionDef, ast.AsyncFunctionDef)
+ ), "Expected a function definition"
+ extracted = ast.Module(body.body, type_ignores=[])
+ module = RemoveReturns().visit(extracted)
+ assert isinstance(module, ast.Module), "Expected a module"
+ return module
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index 12519e7d8a..ffde3bef79 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import re
from collections import namedtuple
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Literal
+from typing import TYPE_CHECKING, Any, Literal, Optional, get_args
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context import ContextNotInitializedError, get_context
@@ -18,6 +18,7 @@ CacheType = Literal[
"ContentAddressed",
"ExecutionPath",
"Pure",
+ "Deferred",
"Unknown",
]
# Easy visual identification of cache type.
@@ -26,11 +27,12 @@ CACHE_PREFIX: dict[CacheType, str] = {
"ContentAddressed": "C_",
"ExecutionPath": "E_",
"Pure": "P_",
+ "Deferred": "D_",
"Unknown": "U_",
}
ValidCacheSha = namedtuple("ValidCacheSha", ("sha", "cache_type"))
-MetaKey = str # e.g. Literal["code", "output"]
+MetaKey = Literal["return"]
# BaseException because "raise _ as e" is utilized.
@@ -68,20 +70,31 @@ class Cache:
value = defs[ref]
if isinstance(value, SetFunctor):
value(self.defs[ref])
- elif isinstance(value, UIElement):
- value._update(self.defs[ref])
- else:
+ # UI Values cannot be easily programmatically set, so only update
+ # state values.
+ elif not isinstance(value, UIElement):
raise CacheException(
"Failure while restoring cached values. "
"Unexpected stateful reference type "
f"({type(ref)}:{ref})."
)
- def update(self, scope: dict[str, Any]) -> None:
+ def update(
+ self,
+ scope: dict[str, Any],
+ meta: Optional[dict[MetaKey, Any]] = None,
+ ) -> None:
"""Loads values from scope, updating the cache."""
for var, lookup in self.contextual_defs():
self.defs[var] = scope[lookup]
+ self.meta = {}
+ if meta is not None:
+ for key, value in meta.items():
+ if key not in get_args(MetaKey):
+ raise CacheException(f"Unexpected meta key: {key}")
+ self.meta[key] = value
+
defs = {**globals(), **scope}
for ref in self.stateful_refs:
if ref not in defs:
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index 1d652210b3..2801c7c12b 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -7,9 +7,9 @@ import hashlib
import struct
import sys
import types
-from typing import TYPE_CHECKING, Any, Iterable, Optional
+from typing import TYPE_CHECKING, Any, Iterable, NamedTuple, Optional
-from marimo._ast.visitor import ScopedVisitor
+from marimo._ast.visitor import Name, ScopedVisitor
from marimo._dependencies.dependencies import DependencyManager
from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._runtime.primitives import (
@@ -32,7 +32,6 @@ if TYPE_CHECKING:
from types import CodeType
from marimo._ast.cell import CellId_t, CellImpl
- from marimo._ast.visitor import Name
from marimo._runtime.context.types import RuntimeContext
from marimo._runtime.dataflow import DirectedGraph
from marimo._save.loaders import Loader
@@ -42,9 +41,20 @@ if TYPE_CHECKING:
Tensor = Any
+# Default hash type is generally inconsequential, there may be implications of
+# malicious hash collision or performance. Malicious hash collision can be
+# mitigated with a signed cache, and performance is neligible compared to the
+# rest of the hashing mechanism.
DEFAULT_HASH = "sha256"
+# NamedTuple over dataclass for unpacking.
+class SerialRefs(NamedTuple):
+ refs: set[Name]
+ content_serialization: dict[Name, bytes]
+ stateful_refs: set[Name]
+
+
def hash_module(
code: Optional[CodeType], hash_type: str = DEFAULT_HASH
) -> bytes:
@@ -198,6 +208,37 @@ def data_to_buffer(data: Tensor) -> bytes:
return type_sign(memoryview(data_c_contiguous.view("uint8")), "data")
+def attempt_signed_bytes(value: bytes, label: str) -> bytes:
+ # Prevents hash collisions like:
+ # >>> fib(1)
+ # >>> s, _ = state(1)
+ # >>> fib(s)
+ # ^ would be a cache hit as is even though fib(s) would fail by
+ # itself
+ try:
+ return type_sign(common_container_to_bytes(value), label)
+ # Fallback to raw state for eval in content hash.
+ except TypeError:
+ return value
+
+
+def get_and_update_context_from_scope(
+ scope: dict[str, Any],
+) -> Optional[RuntimeContext]:
+ """Get stateful registers"""
+ # This is typically done in post execution hook, but it will not be
+ # called in script mode.
+ # TODO: Strip this out to allow for hash based look up. Name based
+ # lookup fails for anonymous instances of state and UI Elements.
+ try:
+ ctx = get_context()
+ ctx.ui_element_registry.register_scope(scope)
+ ctx.state_registry.register_scope(scope)
+ return ctx
+ except ContextNotInitializedError:
+ return None
+
+
class BlockHasher:
def __init__(
self,
@@ -209,12 +250,13 @@ class BlockHasher:
context: Optional[ast.Module] = None,
pin_modules: bool = False,
hash_type: str = DEFAULT_HASH,
- content_hash: bool = True,
+ apply_content_hash: bool = True,
+ scoped_refs: Optional[set[Name]] = None,
) -> None:
"""Hash the context of the module, and return a cache object.
- Hashing occurs 3 combined methods, content addressed, and execution
- path:
+ Hashing uses 3 combined methods: pure hashing, content addressed, and
+ execution path:
1) "Pure" hashing is used when a block has no references. The hash is
computed from the code itself.
@@ -236,6 +278,11 @@ class BlockHasher:
be deterministic. NB. The ContextExecutionPath is an extended case of
ExecutionPath hashing, just utilizing additional context.
+ For optimization, the content hash is performed after the execution
+ cache- however the content references are collected first. This
+ deferred content hash is useful in cases like repeated calls to a
+ cached function.
+
Args:
- module: The code content to create a hash for (e.g.
for persistent_cache, the body of the `With` statement).
@@ -248,15 +295,24 @@ class BlockHasher:
invocation, but still in the same cell.
- pin_modules: If True, then the module will be pinned to the version
- hash_type: The type of hash to use.
- - content_hash: If True, then the content hash will be attempted,
- otheriwise only use execution path hash.
-
+ - apply_content_hash: If True, then the content hash will be
+ attempted, otherwise only use execution path hash.
+ - scoped_refs: A set of references that cannot be traced via
+ execution path, and must be accounted for via content hashing.
"""
# Hash should not be pinned to cell id
scope = {unmangle_local(k, cell_id).name: v for k, v in scope.items()}
self.module = DeprivateVisitor().visit(module)
+ if not scoped_refs:
+ scoped_refs = set()
+ else:
+ assert (
+ not apply_content_hash
+ ), "scoped_refs should only be used with deferred hashing."
+
+ self._hash: Optional[str] = None
self.graph = graph
self.cell_id = cell_id
self.pin_modules = pin_modules
@@ -269,76 +325,209 @@ class BlockHasher:
refs = set(self.visitor.refs)
self.defs = self.visitor.defs
- # Get stateful registers
- # This is typically done in post execution hook, but it will not be
- # called in script mode.
- # TODO: Strip this out to allow for hash based look up. Name based
- # lookup fails for anonymous instances of state and UI Elements.
- try:
- ctx = get_context()
- ctx.ui_element_registry.register_scope(scope)
- ctx.state_registry.register_scope(scope)
- except ContextNotInitializedError:
- ctx = None
-
- refs, stateful_refs = self.extract_ref_state_and_normalize_scope(
+ # Deferred hashing (i.e. instantiation without applying content hash),
+ # may yield missing references.
+ self.missing: set[Name] = set()
+ if not apply_content_hash:
+ refs, self.missing = self.extract_missing_ref(refs, scope)
+
+ ctx = get_and_update_context_from_scope(scope)
+ refs, _, stateful_refs = self.extract_ref_state_and_normalize_scope(
refs, scope, ctx
)
self.stateful_refs = stateful_refs
# usedforsecurity=False used to satisfy some static analysis tools.
self.hash_alg = hashlib.new(hash_type, usedforsecurity=False)
+
+ # Hold on to each ref type
+ self.content_refs = set(refs)
+ self.execution_refs = set(refs)
+ self.context_refs = set(refs)
+
# Default type, means that there are no references at all.
cache_type: CacheType = "Pure"
- # TODO: Consider memoizing the hash contents and hashed cells, such
- # that a parent cell's BlockHasher can be used to speed up the hashing
- # of child.
+ # TODO: Consider memoizing the serialized contents and hashed cells,
+ # such that a parent cell's BlockHasher can be used to speed up the
+ # hashing of child.
- # Attempt content hash on the cell references
- if refs and content_hash:
+ # Collect references that will be utilized for a content hash.
+ content_serialization: dict[Name, bytes] = {}
+ if refs:
cache_type = "ContentAddressed"
- refs = self.hash_and_dequeue_content_refs(refs, scope)
- # Given an active thread, extract state based variables that
- # influence the graph, and hash them accordingly.
- if ctx:
- (
- refs,
- stateful_refs,
- ) = self.hash_and_dequeue_stateful_content_refs(
- refs, scope, ctx
+ refs, content_serialization, stateful_refs = (
+ self.collect_for_content_hash(
+ refs, scope, ctx, scoped_refs, apply_hash=False
)
- self.stateful_refs |= stateful_refs
+ )
+ self.stateful_refs |= stateful_refs
+ self.content_refs -= refs
# If there are still unaccounted for references, then fallback on
- # execution
- # hashing.
+ # execution hashing.
if refs:
cache_type = "ExecutionPath"
- # Execution path hash
refs = self.hash_and_dequeue_execution_refs(refs)
+ self.execution_refs -= refs | self.content_refs
+
+ # Remove values that should be provided by external scope.
+ refs -= scoped_refs
# If there are remaining references, they should be part of the
# provided context.
if refs:
cache_type = "ContextExecutionPath"
self.hash_and_verify_context_refs(refs, context)
+ self.context_refs -= refs | self.content_refs | self.execution_refs
+
+ # Now run the content hash on the content refs.
+ if apply_content_hash:
+ self._apply_content_hash(content_serialization)
+ elif self.missing:
+ cache_type = "Deferred"
# Finally, utilize the unrun block itself, and clean up.
self.cache_type = cache_type
self.hash_alg.update(hash_raw_module(module, hash_type))
- self.hash = (
- base64.urlsafe_b64encode(self.hash_alg.digest())
- .decode("utf-8")
- .strip("=")
+
+ @staticmethod
+ def from_parent(
+ parent: BlockHasher,
+ ) -> BlockHasher:
+ # Use a previous block as the basis of a new block.
+ block = BlockHasher.__new__(BlockHasher)
+ block.module = parent.module
+ block.graph = parent.graph
+ block.cell_id = parent.cell_id
+ block.pin_modules = parent.pin_modules
+ block.fn_cache = {}
+ if parent.fn_cache is not None:
+ block.fn_cache = dict(parent.fn_cache)
+ block.visitor = parent.visitor
+ block.defs = set(parent.defs)
+ block.stateful_refs = set(parent.stateful_refs)
+ block.hash_alg = parent.hash_alg.copy()
+ block._hash = None
+ block.cache_type = parent.cache_type
+ block.content_refs = set(parent.content_refs)
+ block.execution_refs = set(parent.execution_refs)
+ block.context_refs = set(parent.context_refs)
+ return block
+
+ @property
+ def hash(self) -> str:
+ if self._hash is None:
+ assert self.hash_alg is not None, "Hash algorithm not initialized."
+ self._hash = (
+ base64.urlsafe_b64encode(self.hash_alg.digest())
+ .decode("utf-8")
+ .strip("=")
+ )
+ return self._hash
+
+ def __hash__(self) -> int:
+ return hash(self.hash)
+
+ def _apply_content_hash(
+ self, content_serialization: dict[Name, bytes]
+ ) -> None:
+ self._hash = None
+ for ref in sorted(content_serialization):
+ self.hash_alg.update(content_serialization[ref])
+
+ def collect_for_content_hash(
+ self,
+ refs: set[Name],
+ scope: dict[str, Any],
+ ctx: Optional[RuntimeContext],
+ scoped_refs: set[Name],
+ apply_hash: bool = True,
+ ) -> SerialRefs:
+ self._hash = None
+ refs, content_serialization, _ = (
+ self.serialize_and_dequeue_content_refs(refs, scope)
)
+ # If scoped refs are present, then they are unhashable
+ # and we should fallback to normal hash or fail.
+ if unhashable := (refs & scoped_refs) - self.execution_refs:
+ # pickle is a python default
+ import pickle
+
+ failed = []
+ exceptions = []
+ # By rights, could just fail here - but this final attempt should
+ # provide better user experience.
+ for ref in unhashable:
+ try:
+ _hashed = pickle.dumps(scope[ref])
+ content_serialization[ref] = type_sign(_hashed, "pickle")
+ refs.remove(ref)
+ except (pickle.PicklingError, TypeError) as e:
+ exceptions.append(e)
+ failed.append(ref)
+ if failed:
+ # Ruff didn't like a lambda here
+ def get_type(ref: Name) -> str:
+ return (
+ str(type(item)) if (item := scope[ref]) else "missing"
+ )
+
+ ref_list = ", ".join(
+ [
+ f"{ref}: {get_type(ref)} ({str(e)})"
+ for ref, e in zip(failed, exceptions)
+ ]
+ )
+ # Note ExceptionGroup nicest here, but only available in 3.11
+ # ExceptionGroup(msg, exceptions)
+ raise TypeError(
+ "Content addressed hash could not be utilized. "
+ "Try defining the dependent sections in a separate cell. "
+ "The unhashable arguments/ references are: " + ref_list
+ )
+
+ # Given an active thread, extract state based variables that
+ # influence the graph, and hash them accordingly.
+ if ctx:
+ (
+ refs,
+ content_serialization_tmp,
+ stateful_refs,
+ ) = self.serialize_and_dequeue_stateful_content_refs(
+ refs, scope, ctx
+ )
+ content_serialization.update(content_serialization_tmp)
+ else:
+ stateful_refs = set()
+
+ if apply_hash:
+ self._apply_content_hash(content_serialization)
+ return SerialRefs(refs, content_serialization, stateful_refs)
+
+ def extract_missing_ref(
+ self,
+ refs: set[Name],
+ scope: dict[str, Any],
+ ) -> tuple[set[Name], set[Name]]:
+ _refs = set(refs)
+ missing = set()
+ for ref in refs:
+ # The block will likely throw a NameError, so remove and defer to
+ # execution.
+ if ref in scope.get("__builtins__", ()):
+ continue
+ if ref not in scope:
+ _refs.remove(ref)
+ missing.add(ref)
+ return _refs, missing
def extract_ref_state_and_normalize_scope(
self,
refs: set[Name],
scope: dict[str, Any],
ctx: Optional[RuntimeContext] = None,
- ) -> tuple[set[Name], set[Name]]:
+ ) -> SerialRefs:
"""
Preprocess the scope and references, and extract state references.
@@ -354,8 +543,9 @@ class BlockHasher:
ctx: An optional runtime context for stateful lookup.
Returns:
- tuple of:
+ SerialRefs tuple containing the following elements:
- The filtered references.
+ - _
- The stateful references.
"""
refs = set(refs)
@@ -374,31 +564,28 @@ class BlockHasher:
refs.remove(ref)
continue
- # The block will likely throw a NameError, so remove and defer to
- # execution.
- if ref not in scope:
- refs.remove(ref)
- continue
+ # Clean up the scope, and extract missing references.
+ refs, _ = self.extract_missing_ref(refs, scope)
# State relevant to the context, should be dependent on it's value-
# not the object.
value: Optional[State[Any]]
if ctx and (value := ctx.state_registry.lookup(ref)):
for state_name in ctx.state_registry.bound_names(value):
- scope[state_name] = value()
+ scope[state_name] = attempt_signed_bytes(value(), "state")
# Likewise, UI objects should be dependent on their value.
if ctx and (ui := ctx.ui_element_registry.lookup(ref)) is not None:
for ui_name in ctx.ui_element_registry.bound_names(ui._id):
- scope[ui_name] = ui.value
+ scope[ui_name] = attempt_signed_bytes(ui.value, "ui")
# If the UI is directly consumed, then hold on to the reference
# for proper cache update.
stateful_refs.add(ref)
- return refs, stateful_refs
+ return SerialRefs(refs, {}, stateful_refs)
- def hash_and_dequeue_content_refs(
+ def serialize_and_dequeue_content_refs(
self, refs: set[Name], scope: dict[Name, Any]
- ) -> set[Name]:
+ ) -> SerialRefs:
"""Use hashable references to update the hash object and dequeue them.
NB. "Hashable" types are primitives, data primitives, and pure
@@ -409,8 +596,11 @@ class BlockHasher:
scope: A dictionary representing the current scope.
Returns a filtered list of remaining references that were not utilized
- in updating the hash.
+ in updating the hash, and a dictionary of the content serialization.
"""
+ self._hash = None
+
+ content_serialization = {}
refs = set(refs)
# Content addressed hash is valid if every reference is accounted for
# and can be shown to be a primitive value.
@@ -425,9 +615,10 @@ class BlockHasher:
if self.pin_modules:
module = sys.modules[imports[ref].namespace]
version = getattr(module, "__version__", "")
- self.hash_alg.update(
- f"module:{ref}:{version}".encode("utf8")
- )
+
+ content_serialization[ref] = type_sign(
+ bytes(f"module:{ref}:{version}", "utf-8"), "module"
+ )
# No need to watch the module otherwise. If the block depends
# on it then it should be caught when hashing the block.
refs.remove(local_ref)
@@ -438,29 +629,31 @@ class BlockHasher:
continue
value = scope[local_ref]
+ serial_value = None
if is_primitive(value):
- self.hash_alg.update(primitive_to_bytes(value))
+ serial_value = primitive_to_bytes(value)
elif is_data_primitive(value):
- self.hash_alg.update(data_to_buffer(value))
+ serial_value = data_to_buffer(value)
elif is_data_primitive_container(value):
- self.hash_alg.update(common_container_to_bytes(value))
+ serial_value = common_container_to_bytes(value)
elif is_pure_function(
local_ref, value, scope, self.fn_cache, self.graph
):
- self.hash_alg.update(
- hash_module(value.__code__, self.hash_alg.name)
- )
+ serial_value = hash_module(value.__code__, self.hash_alg.name)
# An external module variable is assumed to be pure, with module
# pinning being the mechanism for invalidation.
elif getattr(value, "__module__", "__main__") == "__main__":
continue
+
+ if serial_value is not None:
+ content_serialization[ref] = serial_value
# Fall through means that the references should be dequeued.
refs.remove(local_ref)
- return refs
+ return SerialRefs(refs, content_serialization, set())
- def hash_and_dequeue_stateful_content_refs(
+ def serialize_and_dequeue_stateful_content_refs(
self, refs: set[Name], scope: dict[str, Any], ctx: RuntimeContext
- ) -> tuple[set[Name], set[Name]]:
+ ) -> SerialRefs:
"""Determines and uses stateful references that impact the code block.
Args:
@@ -471,10 +664,9 @@ class BlockHasher:
Returns:
tuple of:
- The updated references.
+ - A dictionary of the content serialization.
- additional stateful references.
"""
- # TODO: Utilize registry to associate stateful instances with top level
- # variables.
refs = set(refs)
# Determine _all_ additional relevant references
transitive_state_refs = self.graph.get_transitive_references(
@@ -491,11 +683,14 @@ class BlockHasher:
)
)
# Need to run extract again for the expanded ref set.
- refs, stateful_refs = self.extract_ref_state_and_normalize_scope(
+ refs, _, stateful_refs = self.extract_ref_state_and_normalize_scope(
refs, scope, ctx
)
# Attempt content hash again on the extracted stateful refs.
- return self.hash_and_dequeue_content_refs(refs, scope), stateful_refs
+ refs, content_serialization, _ = (
+ self.serialize_and_dequeue_content_refs(refs, scope)
+ )
+ return SerialRefs(refs, content_serialization, stateful_refs)
def hash_and_dequeue_execution_refs(self, refs: set[Name]) -> set[Name]:
"""Determines and uses the hash of refs' cells to update the hash.
@@ -507,6 +702,8 @@ class BlockHasher:
hash. This should only be possible in the case where a cell context is
provided, as those references should be accounted for in that context.
"""
+ self._hash = None
+
refs = set(refs)
# Execution path works by just analyzing the input cells to hash.
ancestors = self.graph.ancestors(self.cell_id)
@@ -543,11 +740,14 @@ class BlockHasher:
persistent_cache case, this applies to the code prior to
invocation, but still in the same cell.
"""
+ self._hash = None
+
# Native save won't pass down context, so if we are here,
# then something is wrong with the remaining references.
assert context is not None, (
"Execution path could not be resolved. "
- "There may be cyclic definitions in the code."
+ "There may be cyclic definitions in the code. "
+ f"The unresolved references are: {refs}. "
"This is unexpected, please report this issue to "
"https://github.com/marimo-team/marimo/issues"
)
@@ -587,11 +787,17 @@ def cache_attempt_from_hash(
context: Optional[ast.Module] = None,
pin_modules: bool = False,
hash_type: str = DEFAULT_HASH,
+ scoped_refs: Optional[set[Name]] = None,
loader: Loader,
+ as_fn: bool = False,
) -> Cache:
"""Hash a code block with context from the same cell, and return a cache
object.
+ Extra args
+ - loader: The loader to use for cache operations.
+ - as_fn: If True, then the block is treated as a function
+
Returns:
- A cache object that may, or may not be fully populated.
"""
@@ -604,11 +810,102 @@ def cache_attempt_from_hash(
context=context,
pin_modules=pin_modules,
hash_type=hash_type,
+ scoped_refs=scoped_refs,
)
+ if as_fn:
+ hasher.defs.clear()
+
return loader.cache_attempt(
hasher.defs,
hasher.hash,
hasher.stateful_refs,
hasher.cache_type,
)
+
+
+def content_cache_attempt_from_base(
+ previous_block: BlockHasher,
+ scope: dict[str, Any],
+ loader: Loader,
+ scoped_refs: Optional[set[Name]] = None,
+ required_refs: Optional[set[Name]] = None,
+ *,
+ as_fn: bool = False,
+ sensitive: bool = False,
+) -> Cache:
+ """Hash a code block with context from the same cell, and attempt a cache
+ lookup.
+
+ Args:
+ - previous_block: The block to base the new block on.
+ - scope: The scope of the new block.
+ - loader: The loader to use for cache operations.
+ - scoped_refs: A set of references that cannot be traced via
+ execution path, and must be accounted for via content hashing.
+ - as_fn: If True, then the block is treated as a function, and will not
+ cache definitions in scope.
+ - sensitive: If True, then the cache hash will to rehash references
+ resolved with path execution. This will invalidate the cache more
+ frequently.
+ """
+ if scoped_refs is None:
+ scoped_refs = set()
+
+ if required_refs is None:
+ required_refs = set()
+
+ scope = {
+ unmangle_local(k, previous_block.cell_id).name: v
+ for k, v in scope.items()
+ }
+
+ # Manually add back missing refs, which should now be in scope.
+ scoped_refs |= previous_block.missing
+ scoped_refs |= required_refs
+
+ # refine to values present
+ refs = scoped_refs & previous_block.visitor.refs
+ # Required refs are made explicit incase the examined block does not
+ # specify them e.g.
+ # @cache
+ # def foo(x):
+ # return random.random()
+ # assert foo(0) != foo(1)
+ refs |= required_refs
+ # Assume all execution refs could be content refs
+ # but only if sensitive is set.
+ if sensitive:
+ refs |= previous_block.execution_refs
+ refs |= previous_block.content_refs
+ refs |= previous_block.context_refs
+
+ hasher = BlockHasher.from_parent(previous_block)
+ ctx = get_and_update_context_from_scope(scope)
+ refs, _, stateful_refs = hasher.extract_ref_state_and_normalize_scope(
+ refs, scope, ctx
+ )
+
+ refs, content, tmp_stateful_refs = hasher.collect_for_content_hash(
+ refs, scope, ctx, scoped_refs, apply_hash=True
+ )
+ # If the execution block covers this variable, then that's OK
+ refs -= previous_block.execution_refs
+
+ stateful_refs |= tmp_stateful_refs
+
+ assert not refs, (
+ "Content addressed hash could not be resolved. "
+ "Try defining the cached block in a separate cell. "
+ f"The unresolved references are: {refs}. "
+ )
+
+ if as_fn:
+ hasher.defs.clear()
+
+ return loader.cache_attempt(
+ hasher.defs,
+ hasher.hash,
+ stateful_refs,
+ hasher.cache_type,
+ )
diff --git a/marimo/_save/loaders/__init__.py b/marimo/_save/loaders/__init__.py
new file mode 100644
index 0000000000..da49d65cac
--- /dev/null
+++ b/marimo/_save/loaders/__init__.py
@@ -0,0 +1,6 @@
+# Copyright 2024 Marimo. All rights reserved.
+from marimo._save.loaders.loader import Loader
+from marimo._save.loaders.memory import MemoryLoader
+from marimo._save.loaders.pickle import PickleLoader
+
+__all__ = ["Loader", "MemoryLoader", "PickleLoader"]
diff --git a/marimo/_save/loaders.py b/marimo/_save/loaders/loader.py
similarity index 65%
rename from marimo/_save/loaders.py
rename to marimo/_save/loaders/loader.py
index b516561d57..0c3d36447e 100644
--- a/marimo/_save/loaders.py
+++ b/marimo/_save/loaders/loader.py
@@ -1,8 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
-import pickle
from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING
@@ -33,14 +31,12 @@ class Loader(ABC):
cloud).
"""
- def __init__(self, name: str, save_path: str) -> None:
+ def __init__(self, name: str) -> None:
self.name = name
- self.save_path = Path(save_path) / name
- self.save_path.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}"
+ return Path(f"{prefix}{hashed_context}")
def cache_attempt(
self,
@@ -92,30 +88,3 @@ class Loader(ABC):
@abstractmethod
def save_cache(self, cache: Cache) -> None:
"""Save Cache"""
-
-
-class PickleLoader(Loader):
- """General loader for serializable objects."""
-
- def build_path(self, hashed_context: str, cache_type: CacheType) -> Path:
- return Path(f"{super().build_path(hashed_context, cache_type)}.pickle")
-
- 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 load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
- assert self.cache_hit(
- hashed_context, cache_type
- ), INCONSISTENT_CACHE_BOILER_PLATE
- with open(self.build_path(hashed_context, cache_type), "rb") as handle:
- cache = pickle.load(handle)
- assert isinstance(cache, Cache), (
- "Excepted cache object, got" f"{type(cache)} ",
- INCONSISTENT_CACHE_BOILER_PLATE,
- )
- 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)
diff --git a/marimo/_save/loaders/memory.py b/marimo/_save/loaders/memory.py
new file mode 100644
index 0000000000..c4b19ee52b
--- /dev/null
+++ b/marimo/_save/loaders/memory.py
@@ -0,0 +1,101 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import threading
+from collections import OrderedDict
+from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union
+
+from marimo._save.cache import Cache, CacheType
+from marimo._save.loaders.loader import INCONSISTENT_CACHE_BOILER_PLATE, Loader
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+
+T = TypeVar("T")
+
+
+class MemoryLoader(Loader):
+ """In memory loader for saved objects."""
+
+ def __init__(
+ self,
+ *args: Any,
+ max_size: int = 128,
+ cache: Optional[OrderedDict[Path, Cache]] = None,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+
+ self._cache: Union[OrderedDict[Path, Cache], dict[Path, Cache]]
+ self.is_lru = max_size > 0
+
+ # Normal python dicts are atomic, ordered dictionaries are not.
+ # As such, default to normal dict if not LRU.
+ self._cache = {}
+ # ordered dict is protected by a lock
+ self._cache_lock: threading.Lock | None = None
+ if self.is_lru:
+ self._cache = OrderedDict()
+ self._cache_lock = threading.Lock()
+ self.max_size = max_size
+ self.hits = 0
+ if cache is not None:
+ self._maybe_lock(lambda: self._cache.update(cache))
+
+ def _maybe_lock(self, fn: Callable[..., T]) -> T:
+ if self._cache_lock is not None:
+ with self._cache_lock:
+ return fn()
+ 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 load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
+ assert self.cache_hit(
+ hashed_context, cache_type
+ ), INCONSISTENT_CACHE_BOILER_PLATE
+ self.hits += 1
+ key = self.build_path(hashed_context, cache_type)
+ if self.is_lru:
+ assert isinstance(self._cache, OrderedDict)
+ assert self._cache_lock is not None
+ with self._cache_lock:
+ self._cache.move_to_end(key)
+ return self._cache[key]
+
+ def save_cache(self, cache: Cache) -> None:
+ key = self.build_path(cache.hash, cache.cache_type)
+ # LRU
+ if self.is_lru:
+ assert isinstance(self._cache, OrderedDict)
+ assert self._cache_lock is not None
+ with self._cache_lock:
+ self._cache[key] = cache
+ self._cache.move_to_end(key)
+ if len(self._cache) > self.max_size:
+ self._cache.popitem(last=False)
+ self._cache[key] = cache
+
+ def resize(self, max_size: int) -> None:
+ if not self.is_lru:
+ self.is_lru = max_size > 0
+ if self.is_lru:
+ self._cache = OrderedDict(self._cache.items())
+ self._cache_lock = threading.Lock()
+ self.max_size = max_size
+ return
+ assert isinstance(self._cache, OrderedDict)
+ assert self._cache_lock is not None
+ with self._cache_lock:
+ self.is_lru = max_size > 0
+ if not self.is_lru:
+ self._cache = dict(self._cache.items())
+ self.max_size = max_size
+ return
+ while len(self._cache) > max_size:
+ self._cache.popitem(last=False)
+ self.max_size = max_size
diff --git a/marimo/_save/loaders/pickle.py b/marimo/_save/loaders/pickle.py
new file mode 100644
index 0000000000..acab1fe1fe
--- /dev/null
+++ b/marimo/_save/loaders/pickle.py
@@ -0,0 +1,43 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+import pickle
+from pathlib import Path
+
+from marimo._save.cache import CACHE_PREFIX, Cache, CacheType
+from marimo._save.loaders.loader import INCONSISTENT_CACHE_BOILER_PLATE, Loader
+
+
+class PickleLoader(Loader):
+ """General loader for serializable objects."""
+
+ def __init__(self, name: str, save_path: str) -> None:
+ super().__init__(name)
+ self.name = name
+ self.save_path = Path(save_path) / name
+ self.save_path.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}.pickle"
+
+ 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 load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
+ assert self.cache_hit(
+ hashed_context, cache_type
+ ), INCONSISTENT_CACHE_BOILER_PLATE
+ with open(self.build_path(hashed_context, cache_type), "rb") as handle:
+ cache = pickle.load(handle)
+ assert isinstance(cache, Cache), (
+ "Excepted cache object, got" f"{type(cache)} ",
+ INCONSISTENT_CACHE_BOILER_PLATE,
+ )
+ 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)
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 86d1c0502c..77fd0ef990 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import ast
+import inspect
import io
import sys
import traceback
@@ -9,6 +10,7 @@ from sys import maxsize as MAXINT
from typing import (
TYPE_CHECKING,
Any,
+ Callable,
Optional,
Type,
Union,
@@ -16,10 +18,17 @@ from typing import (
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime.context import get_context
-from marimo._save.ast import ExtractWithBlock
+from marimo._runtime.state import State
+from marimo._save.ast import ExtractWithBlock, strip_function
from marimo._save.cache import Cache, CacheException
-from marimo._save.hash import cache_attempt_from_hash
-from marimo._save.loaders import Loader, PickleLoader
+from marimo._save.hash import (
+ DEFAULT_HASH,
+ BlockHasher,
+ cache_attempt_from_hash,
+ content_cache_attempt_from_base,
+)
+from marimo._save.loaders import Loader, 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
# catch all to motive users to report if something does fail.
@@ -30,42 +39,320 @@ UNEXPECTED_FAILURE_BOILERPLATE = (
"https://github.com/marimo-team/marimo/issues"
)
-
if TYPE_CHECKING:
from types import FrameType, TracebackType
from _typeshed import TraceFunction
from typing_extensions import Self
+ from marimo._runtime.dataflow import DirectedGraph
+
class SkipWithBlock(Exception):
"""Special exception to get around executing the with block body."""
+class _cache_base(object):
+ """Like functools.cache but notebook-aware. See `cache` docstring`"""
+
+ graph: DirectedGraph
+ cell_id: str
+ module: ast.Module
+ _args: list[str]
+ _loader: Optional[State[MemoryLoader]] = None
+ name: str
+ fn: Optional[Callable[..., Any]]
+
+ def __init__(
+ self,
+ _fn: Optional[Callable[..., Any]] = None,
+ *,
+ # -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 _fn
+ frame_offset: int = 0,
+ ) -> None:
+ self.max_size = maxsize
+ self.pin_modules = pin_modules
+ self.hash_type = hash_type
+ self._frame_offset = frame_offset
+ if _fn is None:
+ self.fn = None
+ else:
+ self._set_context(_fn)
+
+ @property
+ def hits(self) -> int:
+ if self._loader is None:
+ return 0
+ return self._loader().hits
+
+ def _set_context(self, fn: Callable[..., Any]) -> None:
+ assert callable(fn), "the provided function must be callable"
+ ctx = get_context()
+ assert ctx.execution_context is not None, (
+ "Could not resolve context for cache. "
+ "Either @cache is not called from a top level cell or "
+ f"{UNEXPECTED_FAILURE_BOILERPLATE}"
+ )
+
+ self.fn = fn
+ self._args = list(self.fn.__code__.co_varnames)
+ # Retrieving frame from the stack: frame is
+ #
+ # 0 _set_context ->
+ # 1 __call__ (or init) -->
+ # ...
+ # 2 + self._frame_offset: fn
+ #
+ # Note, that deeply nested frames may cause issues, however
+ # checking a single frame- should be good enough.
+ f_locals = inspect.stack()[2 + self._frame_offset][0].f_locals
+ self.scope = {**ctx.globals, **f_locals}
+
+ # Scoped refs are references particular to this block, that may not be
+ # defined out of the context of the block, or the cell.
+ # For instance, the args of the invoked function are restricted to the
+ # block.
+ cell_id = ctx.cell_id or ctx.execution_context.cell_id or ""
+ self.scoped_refs = set(self._args)
+ # # As are the "locals" not in globals
+ self.scoped_refs |= set(f_locals.keys()) - set(ctx.globals.keys())
+ # Defined in the cell, and currently available in scope
+ self.scoped_refs |= ctx.graph.cells[cell_id].defs & set(
+ ctx.globals.keys()
+ )
+ # The defined private variables of this cell, normalized
+ self.scoped_refs |= set(
+ unmangle_local(x).name
+ for x in ctx.globals.keys()
+ if is_mangled_local(x, cell_id)
+ )
+
+ graph = ctx.graph
+ cell_id = ctx.cell_id or ctx.execution_context.cell_id
+ module = strip_function(self.fn)
+
+ self.base_block = BlockHasher(
+ module=module,
+ graph=graph,
+ cell_id=cell_id,
+ scope=self.scope,
+ pin_modules=self.pin_modules,
+ hash_type=self.hash_type,
+ scoped_refs=self.scoped_refs,
+ apply_content_hash=False,
+ )
+
+ # Load global cache from state
+ name = self.fn.__name__
+ # Note, that if the function name shadows a global variable, the
+ # 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 + "*"
+
+ 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)
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ # Capture the deferred call case
+ if self.fn is None:
+ if len(args) != 1:
+ raise TypeError(
+ "cache() takes at most 1 argument (expecting function)"
+ )
+ self._set_context(args[0])
+ return self
+
+ # Capture the call case
+ arg_dict = {k: v for (k, v) in zip(self._args, args)}
+ scope = {**self.scope, **get_context().globals, **arg_dict, **kwargs}
+ assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATE
+ attempt = content_cache_attempt_from_base(
+ self.base_block,
+ scope,
+ self._loader(),
+ scoped_refs=self.scoped_refs,
+ required_refs=set(self._args),
+ as_fn=True,
+ )
+
+ if attempt.hit:
+ attempt.restore(scope)
+ return attempt.meta["return"]
+ response = self.fn(*args, **kwargs)
+ # stateful variables may be global
+ scope = {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)
+ 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):
- """Context block for cache lookup of a block of code.
+ """Save variables to disk and restore them thereafter.
- Example usage:
+ 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.
- >>> with persistent_cache(name="my_cache"):
- >>> variable = expensive_function() # This will be cached.
+ 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.
- For an implementation sibling regarding the block skipping, see `withhacks`
- in pypi.
+ **Usage.**
- NB: Since context abuses sys frame trace, this may conflict with debugging
- tools that also use sys.settrace.
+ ```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"
+ - `pin_modules`: if True, the cache will be invalidated if module versions
+ differ between runs, defaults to False.
"""
def __init__(
self,
- *,
- save_path: str = "outputs",
name: str,
+ *,
+ save_path: str = "__marimo__/cache",
pin_modules: bool = False,
_loader: Optional[Loader] = None,
) -> None:
+ # For an implementation sibling regarding the block skipping, see
+ # `withhacks` in pypi.
self.name = name
+ save_path = save_path
if _loader:
self._loader = _loader
else:
@@ -92,7 +379,7 @@ class persistent_cache(object):
def _trace(
self, with_frame: FrameType, _event: str, _arg: Any
- ) -> Union[TraceFunction | None]:
+ ) -> Union[TraceFunction, None]:
# General flow is as follows:
# 1) Follow the stack trace backwards to the first instance of a
# "<module>" function call, which corresponds to a cell level block.
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
index 0d7a9cc620..e5729693ae 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import textwrap
+import pytest
+
from marimo._ast.app import App
from marimo._runtime.requests import ExecutionRequest
from marimo._runtime.runtime import Kernel
@@ -18,7 +20,8 @@ class TestScriptCache:
@app.cell
def one() -> tuple[int]:
- from marimo._save.save import persistent_cache
+ # Check top level import
+ from marimo import persistent_cache
from tests._save.mocks import MockLoader
with persistent_cache(name="one", _loader=MockLoader()) as cache:
@@ -86,7 +89,8 @@ class TestAppCache:
[
ExecutionRequest(
cell_id="0",
- code=textwrap.dedent("""
+ code=textwrap.dedent(
+ """
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
@@ -96,7 +100,8 @@ class TestAppCache:
Y = 9
X = 10
Z = 3
- """),
+ """
+ ),
),
]
)
@@ -110,7 +115,8 @@ class TestAppCache:
[
ExecutionRequest(
cell_id="0",
- code=textwrap.dedent("""
+ code=textwrap.dedent(
+ """
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
@@ -120,7 +126,8 @@ class TestAppCache:
Y = 9
X = 10
Z = 3
- """),
+ """
+ ),
),
]
)
@@ -134,14 +141,16 @@ class TestAppCache:
[
ExecutionRequest(
cell_id="0",
- code=textwrap.dedent("""
+ code=textwrap.dedent(
+ """
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
with persistent_cache(name="one", _loader=MockLoader(data={"X": 1})):
X = 1
Y = 2
- """),
+ """
+ ),
),
]
)
@@ -156,7 +165,8 @@ class TestAppCache:
[
ExecutionRequest(
cell_id="0",
- code=textwrap.dedent("""
+ code=textwrap.dedent(
+ """
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
@@ -166,7 +176,8 @@ class TestAppCache:
# whitespace
X = 1 # Comment
Y = 2
- """),
+ """
+ ),
),
]
)
@@ -242,7 +253,8 @@ class TestStateCache:
]
)
- # Should be hit because of rerun
+ # Should be hit on rerun, because set_state does not have a state
+ # itself.
assert len(k.globals["impure"]) == 2
assert k.globals["impure"][0] == k.globals["impure"][1]
assert k.globals["state"]() == 9
@@ -318,36 +330,607 @@ class TestStateCache:
assert k.globals["state"]() == 7
-class TestUICache:
- async def test_ui_loads(
+class TestCacheDecorator:
+ async def test_basic_cache(
self, k: Kernel, exec_req: ExecReqProvider
) -> None:
await k.run(
[
- exec_req.get("import marimo as mo"),
- exec_req.get("slider = mo.ui.slider(1, 10)"),
exec_req.get(
"""
- from marimo._save.save import persistent_cache
- from tests._save.mocks import MockLoader
+ from marimo._save.save import cache
- a = 0
- with persistent_cache(
- name="cache",
- _loader=MockLoader(
- data={"slider": 7, "a": 9},
- stateful_refs={"slider"})
- ) as cache:
- raise Exception()
- a = slider.value + 1
- slider._update(3)
+ @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["slider"].value == 7
- assert k.globals["a"] == 9
+ assert k.globals["a"] == 5
+ assert k.globals["b"] == 55
+
+ async def test_lru_cache(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo._save.save import lru_cache
+
+ @lru_cache(maxsize=2)
+ def fib(n):
+ if n <= 1:
+ return n
+ return fib(n - 1) + fib(n - 2)
+
+ a = fib(5)
+ b = fib(10)
+ """
+ ),
+ ]
+ )
+
+ assert not len(k.stderr.messages)
+ # More hits with a smaller cache, because it needs to check the cache
+ # more.
+ assert k.globals["fib"].hits == 14
+
+ assert k.globals["a"] == 5
+ assert k.globals["b"] == 55
+
+ async def test_cross_cell_cache(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("""from marimo._save.save import cache"""),
+ exec_req.get(
+ """
+ @cache
+ def fib(n):
+ if n <= 1:
+ return n
+ return fib(n - 1) + fib(n - 2)
+ """
+ ),
+ exec_req.get("""a=fib(5)"""),
+ exec_req.get("""b=fib(10); a"""),
+ ]
+ )
+
+ 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_with_external(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("""from marimo._save.save import cache"""),
+ exec_req.get("""external = 0"""),
+ exec_req.get(
+ """
+ @cache
+ def fib(n):
+ if n <= 1:
+ return n + external
+ return fib(n - 1) + fib(n - 2)
+ """
+ ),
+ exec_req.get("""a = fib(5)"""),
+ exec_req.get("""b = fib(10); a"""),
+ ]
+ )
+
+ assert not k.stderr.messages
+
+ assert k.globals["a"] == 5
+ assert k.globals["b"] == 55
+ assert k.globals["fib"].hits == 9
+
+ async def test_cross_cell_cache_with_external_state(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo._save.save import cache
+ from marimo._runtime.state import state
+ """
+ ),
+ exec_req.get("""external, setter = state(0)"""),
+ exec_req.get(
+ """
+ @cache
+ def fib(n):
+ if n <= 1:
+ return n + external()
+ return fib(n - 1) + fib(n - 2)
+ """
+ ),
+ exec_req.get("""impure = []"""),
+ exec_req.get("""a = fib(5)"""),
+ exec_req.get("""b = fib(10); a"""),
+ exec_req.get(
+ """
+ c = a + b
+ if len(impure) == 0:
+ setter(1)
+ elif len(impure) == 1:
+ setter(0)
+ impure.append(c)
+ """
+ ),
+ ]
+ )
+
+ assert not k.stdout.messages
+ assert not k.stderr.messages
+
+ assert k.globals["a"] == 5
+ assert k.globals["b"] == 55
+ assert k.globals["impure"] == [60, 157, 60]
+ # Cache hit value may be flaky depending on when state is evicted from
+ # the registry. The actual cache hit is less important than caching
+ # occurring in the first place.
+ # 2 * 9 + 2
+ assert k.globals["fib"].hits in (9, 18, 20)
+
+ async def test_cross_cell_cache_with_external_ui(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ 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")"""),
+ exec_req.get(
+ """
+ external # To force rerun
+
+ @cache
+ def fib(n):
+ if n <= 1:
+ return n + slider.value
+ return fib(n - 1) + fib(n - 2)
+ """
+ ),
+ exec_req.get("""impure = []"""),
+ exec_req.get("""a = fib(5)"""),
+ exec_req.get("""b = fib(10); a"""),
+ exec_req.get(
+ """
+ c = a + b
+ if len(impure) == 0:
+ setter("b")
+ slider._update(1)
+ elif len(impure) == 1:
+ setter("c")
+ slider._update(0)
+ impure.append(c)
+ """
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages
+
+ assert k.globals["a"] == 5
+ assert k.globals["b"] == 55
+ assert k.globals["impure"] == [60, 157, 60]
+ # 2 * 9 + 2
+ assert k.globals["fib"].hits in (9, 18, 20)
+
+ async def test_full_scope_utilized(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo._save.save import cache
+ d = 0 # Check shadowing
+ """
+ ),
+ exec_req.get("""impure = []"""),
+ exec_req.get(
+ """
+ _a = 0
+ def _b():
+ _c = 2
+ @cache
+ def d():
+ return _a + _c
+ return d
+ _e = _b()
+ impure.append([_e, _e()])
+ """
+ ),
+ exec_req.get(
+ repeated := """
+ _a = 0
+ def _b():
+ _c = 1
+ @cache
+ def d():
+ return _a + _c
+ return d
+ _e = _b()
+ impure.append([_e, _e()])
+ """
+ ),
+ exec_req.get(repeated),
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert not k.stdout.messages, k.stdout
+
+ assert len(k.globals["impure"]) == 3
+ assert {
+ k.globals["impure"][0][1],
+ k.globals["impure"][1][1],
+ k.globals["impure"][2][1],
+ } == {2, 1}
+
+ # Same name, but should be under different entries
+ assert (
+ 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(),
+ }
+ )
+ == 2
+ )
+
+ # No cache hits
+ assert {
+ k.globals["impure"][0][0].hits,
+ k.globals["impure"][1][0].hits,
+ k.globals["impure"][2][0].hits,
+ } == {0}
+
+ async def test_full_scope_utilized_lru_cache(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo._save.save import lru_cache
+ d = 0 # Check shadowing
+ """
+ ),
+ exec_req.get("""impure = []"""),
+ exec_req.get(
+ """
+ _a = 0
+ def _b():
+ _c = 2
+ @lru_cache
+ def d():
+ return _a + _c
+ return d
+ _e = _b()
+ impure.append([_e, _e()])
+ """
+ ),
+ exec_req.get(
+ repeated := """
+ _a = 0
+ def _b():
+ _c = 1
+ @lru_cache
+ def d():
+ return _a + _c
+ return d
+ _e = _b()
+ impure.append([_e, _e()])
+ """
+ ),
+ exec_req.get(repeated),
+ ]
+ )
+
+ assert not k.stderr.messages, k.stderr
+ assert not k.stdout.messages, k.stdout
+
+ assert len(k.globals["impure"]) == 3
+ assert {
+ k.globals["impure"][0][1],
+ k.globals["impure"][1][1],
+ k.globals["impure"][2][1],
+ } == {2, 1}
+
+ # Same name, but should be under different entries
+ assert (
+ 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(),
+ }
+ )
+ == 2
+ )
+
+ # No cache hits
+ assert {
+ k.globals["impure"][0][0].hits,
+ k.globals["impure"][1][0].hits,
+ k.globals["impure"][2][0].hits,
+ } == {0}
+
+ @staticmethod
+ def test_object_content_hash() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def __():
+ import marimo as mo
+
+ return (mo,)
+
+ @app.cell
+ def __():
+ class Namespace: ...
+
+ ns = Namespace()
+ ns.x = 0
+ return Namespace, ns
+
+ @app.cell
+ def __(mo, ns):
+ @mo.cache
+ def f():
+ return ns
+
+ return (f,)
+
+ @app.cell
+ def __(f):
+ f()
+ assert f.hits == 0
+ assert f.base_block.execution_refs == {"ns"}
+ return
+
+ app.run()
+
+ @staticmethod
+ def test_execution_hash_same_block() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def __():
+ import marimo as mo
+
+ return (mo,)
+
+ @app.cell
+ def __(mo):
+ class Namespace: ...
+
+ ns = Namespace()
+ ns.x = 0
+
+ @mo.cache
+ def f():
+ return ns.x
+
+ return (
+ ns,
+ f,
+ )
+
+ @app.cell
+ def __(f, ns):
+ assert f() == 0
+ ns.x = 1
+ assert f() == 1
+ assert f.hits == 0
+ assert f() == 1
+ assert f.hits == 1
+ assert f.base_block.context_refs == {"ns"}, (
+ f.base_block.context_refs,
+ f.base_block.execution_refs,
+ f.base_block.content_refs,
+ )
+ assert f.base_block.context_refs == {
+ "ns"
+ }, f.base_block.context_refs
+ return
+
+ app.run()
+
+ @staticmethod
+ def test_execution_hash_diff_block() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def __():
+ import marimo as mo
+
+ return (mo,)
+
+ @app.cell
+ def __():
+ import weakref
+
+ class Namespace: ...
+
+ ns = Namespace()
+ ns.x = weakref.ref(ns)
+ z = ns.x
+
+ return (weakref, ns, z)
+
+ @app.cell
+ def __(mo, ns, z):
+ @mo.cache
+ def f():
+ return ns.x, z
+
+ return (f,)
+
+ @app.cell
+ def __(f):
+ f()
+ assert f.base_block.execution_refs == {"ns", "z"}
+ return
+
+ app.run()
+
+ @staticmethod
+ def test_content_hash_define_after() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def __():
+ import marimo as mo
+
+ return (mo,)
+
+ @app.cell
+ def __(mo):
+ @mo.cache
+ def f():
+ return ns.x
+
+ class Namespace: ...
+
+ ns = Namespace()
+ ns.x = 0
+
+ return (
+ ns,
+ f,
+ )
+
+ @app.cell
+ def __(f, ns):
+ assert f() == 0
+ ns.x = 1
+ assert f() == 1
+ assert f.hits == 0
+ assert f() == 1
+ assert f.hits == 1
+ assert (
+ f.base_block.execution_refs == set()
+ ), f.base_block.execution_refs
+ assert f.base_block.missing == {"ns"}, f.base_block.missing
+ return
+
+ app.run()
+
+ @staticmethod
+ def test_execution_hash_same_block_fails() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def __():
+ import marimo as mo
+
+ return (mo,)
+
+ @app.cell
+ def __():
+ import weakref
+
+ return (weakref,)
+
+ @app.cell
+ def __(mo, weakref):
+ class Namespace: ...
+
+ ns = Namespace()
+ ns.x = weakref.ref(ns)
+ z = ns.x
+
+ @mo.cache
+ def f():
+ return ns.x, z
+
+ return (
+ ns,
+ f,
+ )
+
+ @app.cell
+ def __(f):
+ f()
+ return
+
+ # Cannot hash the cell of the unhashable content, so it should fail
+ with pytest.raises(TypeError):
+ app.run()
+
+ @staticmethod
+ def test_unused_args() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def __():
+ import random
+
+ import marimo as mo
+
+ return (mo, random)
+
+ @app.cell
+ def __(mo, random):
+ @mo.cache
+ def g(_x):
+ return random.randint(0, 1000)
+
+ return (g,)
+
+ @app.cell
+ def __(g, random):
+ random.seed(0)
+ a = g("hello")
+ assert g("hello") == g("hello")
+ random.seed(1)
+ assert a == g("hello")
+ assert a != g("world")
+ return
+
+ app.run()
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index 2cb6cdea13..102ccdae7e 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -271,6 +271,31 @@ class TestHash:
app.run()
+ @staticmethod
+ def test_function_state_content_hash_distinct() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import marimo as mo
+ from marimo._save.save import cache
+
+ state, _set_state = mo.state(0)
+
+ @cache
+ def check_type(v) -> str:
+ return str(type(v))
+
+ a = check_type(0)
+ b = check_type(state)
+ assert a != b, (a, "!=", b)
+ assert a == "<class 'int'>", a
+ assert "State" in b, b
+ return a, b
+
+ app.run()
+
@staticmethod
def test_transitive_execution_path_when_state_dependent() -> None:
app = App()
@@ -368,7 +393,7 @@ class TestDataHash:
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
- expected_hash = "MsiRwkuTRK94PyMbWFPVGgYtpz-TNWoQhE7X87FXK2o"
+ expected_hash = "aInOwuFXPXqX3XHlU4KGi3w7rzr30OwBIPYTUBrpSKM"
return MockLoader, persistent_cache, expected_hash, np
@app.cell
diff --git a/tests/conftest.py b/tests/conftest.py
index acc07b4918..6ae1eb00a5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import dataclasses
import inspect
import os
+import re
import sys
import textwrap
from tempfile import TemporaryDirectory
@@ -58,6 +59,9 @@ class MockStdout(ThreadSafeStdout):
self.messages.append(data)
return len(data)
+ def __repr__(self) -> str:
+ return "".join(self.messages)
+
class MockStderr(ThreadSafeStderr):
"""Captures the output sent through the stream"""
@@ -73,6 +77,10 @@ class MockStderr(ThreadSafeStderr):
self.messages.append(data)
return len(data)
+ def __repr__(self) -> str:
+ # Error messages are commonly formatted for output in HTML
+ return re.sub(r"<.*?>", "", "".join(self.messages))
+
class MockStdin(ThreadSafeStdin):
"""Echoes the prompt."""