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.

Persistent cache (#1758)

Dylan Madisetti1e42aba6ddf6
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 908a93c8e8..896b508460 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -84,7 +84,9 @@ class RefData:
class ScopedVisitor(ast.NodeVisitor):
- def __init__(self, mangle_prefix: Optional[str] = None) -> None:
+ def __init__(
+ self, mangle_prefix: Optional[str] = None, ignore_local: bool = False
+ ) -> None:
self.block_stack: list[Block] = [Block()]
# Names to be loaded into a variable required_refs
self.ref_stack: list[set[Name]] = [set()]
@@ -97,6 +99,7 @@ class ScopedVisitor(ast.NodeVisitor):
if mangle_prefix is None
else mangle_prefix
)
+ self.is_local = (lambda _: False) if ignore_local else is_local
@property
def defs(self) -> set[Name]:
@@ -122,7 +125,9 @@ class ScopedVisitor(ast.NodeVisitor):
self, name: str, ignore_scope: bool = False
) -> str:
"""Mangle local variable name declared at top-level scope."""
- if is_local(name) and (len(self.block_stack) == 1 or ignore_scope):
+ if self.is_local(name) and (
+ len(self.block_stack) == 1 or ignore_scope
+ ):
return f"_{self.id}{name}"
else:
return name
@@ -499,16 +504,16 @@ class ScopedVisitor(ast.NodeVisitor):
elif (
isinstance(node.ctx, ast.Load)
and not self._is_defined(node.id)
- and not is_local(node.id)
+ and not self.is_local(node.id)
):
self._add_ref(node.id, deleted=False)
elif (
isinstance(node.ctx, ast.Del)
and not self._is_defined(node.id)
- and not is_local(node.id)
+ and not self.is_local(node.id)
):
self._add_ref(node.id, deleted=True)
- elif is_local(node.id):
+ elif self.is_local(node.id):
mangled_name = self._if_local_then_mangle(
node.id, ignore_scope=True
)
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index 6275138bca..da7430b9fe 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -96,7 +96,8 @@ class KernelRuntimeContext(RuntimeContext):
else:
setting_element_value = False
self._kernel.execution_context = ExecutionContext(
- cell_id=cell_id, setting_element_value=setting_element_value
+ cell_id=cell_id,
+ setting_element_value=setting_element_value,
)
yield
finally:
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index c5c632a9c7..2885fb40ce 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -53,6 +53,9 @@ def get_global_context() -> GlobalContext:
class ExecutionContext:
cell_id: CellId_t
setting_element_value: bool
+ # Cell ID corresponding to local graph object, and not prefixed in script
+ # context.
+ local_cell_id: Optional[CellId_t] = None
# output object set imperatively
output: Optional[list[Html]] = None
diff --git a/marimo/_save/__init__.py b/marimo/_save/__init__.py
new file mode 100644
index 0000000000..be52407b50
--- /dev/null
+++ b/marimo/_save/__init__.py
@@ -0,0 +1 @@
+# Copyright 2024 Marimo. All rights reserved.
diff --git a/marimo/_save/ast.py b/marimo/_save/ast.py
new file mode 100644
index 0000000000..6787b76b81
--- /dev/null
+++ b/marimo/_save/ast.py
@@ -0,0 +1,127 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+from typing import Any, Sequence, Union, cast
+
+
+class BlockException(Exception):
+ pass
+
+
+def compiled_ast(block: Sequence[Union[ast.AST | ast.stmt]]) -> ast.Module:
+ return cast(
+ ast.Module,
+ compile(
+ ast.Module(block, type_ignores=[]),
+ # <ast> is non-standard as a filename, but easier to debug than
+ # <module> everywhere.
+ "<ast>",
+ mode="exec",
+ flags=ast.PyCF_ONLY_AST | ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,
+ optimize=0,
+ dont_inherit=True,
+ ),
+ )
+
+
+def clean_to_modules(
+ pre_block: list[ast.AST], block: ast.With
+) -> tuple[ast.Module, ast.Module]:
+ """Standardizes a `with` block to modules.
+
+ Consider
+
+ >>> <pre_block>
+ >>> ...
+ >>> </pre_block>
+ >>> with fn(val:=other) as x:
+ >>> <block>
+ >>> ...
+ >>> </block>
+
+ We want to compile <pre_block>, and <block> into two separate modules,
+ however, line 4 removes the context of "x" and "val", so this is adjusted
+ to:
+
+ >>> <pre_block>
+ >>> ...
+ >>> x = fn(val := other)
+ >>> </pre_block>
+ >>> <block>
+ >>> ...
+ >>> </block>
+ """
+ assert len(block.items) == 1, "Unexpected with block structure."
+ (with_block,) = block.items
+ initializer: ast.AST = with_block.context_expr
+ if with_block.optional_vars:
+ initializer = ast.Assign(
+ targets=[with_block.optional_vars],
+ value=initializer,
+ )
+ else:
+ # Edgecase with no "as" clause.
+ initializer = ast.Expr(value=initializer)
+ initializer.lineno = len(pre_block) + 1
+ initializer.col_offset = 0
+ pre_block.append(initializer)
+ return (compiled_ast(pre_block), compiled_ast(block.body))
+
+
+class ExtractWithBlock(ast.NodeTransformer):
+ def __init__(self, line: int, *arg: Any, **kwargs: Any) -> None:
+ super().__init__(*arg, **kwargs)
+ self.target_line = line
+
+ def generic_visit(self, node: ast.AST) -> tuple[ast.Module, ast.Module]: # type: ignore[override]
+ pre_block = []
+
+ # There are a few strange edges cases like:
+ # >>> with open("file.txt"): pass
+ #
+ # It's difficult to properly delineate the block, so if multiple
+ # things map to the same line number, it's best to throw an error.
+ on_line = []
+ previous = None
+
+ assert isinstance(node, list), "Unexpected block structure."
+ for n in node:
+ if n.lineno < self.target_line:
+ pre_block.append(n)
+ previous = n
+ elif n.lineno == self.target_line:
+ on_line.append(n)
+ # The target line can easily be skipped if there are comments or
+ # white space or if the block is contained within another block.
+ else:
+ break
+
+ # Capture the edge case when the block is contained within another.
+ # These cases are explicitly restricted to If and other With blocks,
+ # excluding by omission try, for, classes and functions.
+ if len(on_line) == 0:
+ if isinstance(previous, (ast.With, ast.If)):
+ try:
+ # Recursion by referring the the containing block also
+ # captures the case where the target line number was not
+ # exactly hit.
+ return ExtractWithBlock(self.target_line).generic_visit(
+ previous.body # type: ignore[arg-type]
+ )
+ except BlockException:
+ on_line.append(previous)
+ else:
+ raise BlockException(
+ "persistent_cache cannot be invoked within a block "
+ "(try moving the block within the persistent_cache scope)."
+ )
+ # Intentionally not elif (on_line can be added in previous block)
+ if len(on_line) == 1:
+ assert isinstance(on_line[0], ast.With), "Unexpected block."
+ return clean_to_modules(pre_block, on_line[0])
+ # It should be possible to relate the lines with the AST,
+ # but reduce potential bugs by just throwing an error.
+ raise BlockException(
+ "Saving on a shared line may lead to unexpected behavior."
+ )
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
new file mode 100644
index 0000000000..f7fbd2588e
--- /dev/null
+++ b/marimo/_save/cache.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import re
+from collections import namedtuple
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Literal
+
+from marimo._runtime.context import get_context
+
+if TYPE_CHECKING:
+ from marimo._ast.visitor import Name
+
+CacheType = Literal["ContentAddressed", "ExecutionPath", "Unknown"]
+# Easy visual identification of cache type.
+CACHE_PREFIX: dict[CacheType, str] = {
+ "ContentAddressed": "C_",
+ "ExecutionPath": "E_",
+ "Unknown": "U_",
+}
+
+ValidCacheSha = namedtuple("ValidCacheSha", ("sha", "cache_type"))
+
+
+@dataclass
+class Cache:
+ defs: dict[Name, Any]
+ hash: str
+ cache_type: CacheType
+ hit: bool
+
+
+def contextual_defs(cache: Cache) -> dict[tuple[Name, Name], Any]:
+ """Uses context to resolve private variable names."""
+ context = get_context().execution_context
+ assert context is not None, "Context could not be resolved"
+ private_prefix = f"_cell_{context.cell_id}_"
+ return {
+ (var, re.sub(r"^_", private_prefix, var)): value
+ for var, value in cache.defs.items()
+ }
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
new file mode 100644
index 0000000000..4445189101
--- /dev/null
+++ b/marimo/_save/hash.py
@@ -0,0 +1,173 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+import base64
+import hashlib
+import numbers
+import types
+from typing import TYPE_CHECKING, Any, Optional
+
+from marimo._ast.visitor import ScopedVisitor
+from marimo._save.cache import Cache, ValidCacheSha
+from marimo._utils.variables import is_local_then_mangle
+
+if TYPE_CHECKING:
+ from types import CodeType
+
+ from marimo._ast.cell import CellId_t, CellImpl
+ from marimo._runtime.dataflow import DirectedGraph
+ from marimo._save.loaders import Loader
+
+BASE_PRIMITIVES = (str, numbers.Number, type(None))
+
+
+def hash_module(code: Optional[CodeType]) -> bytes:
+ if not code:
+ # SHA256 hash of 32 zero bytes, in the case of no code object
+ # Artifact of typing for mypy, but reasonable fallback.
+ return b"0" * 32
+
+ sha = hashlib.sha256()
+
+ def process(code_obj: CodeType) -> None:
+ # Recursively hash the constants that are also code objects
+ for const in code_obj.co_consts:
+ if isinstance(const, types.CodeType):
+ process(const)
+ else:
+ sha.update(str(const).encode("utf8"))
+ # Concatenate the names and bytecode of the current code object
+ # Will cause invalidation of variable naming at the top level
+ sha.update(bytes("|".join(code_obj.co_names), "utf8"))
+ sha.update(code_obj.co_code)
+
+ process(code)
+ return sha.digest()
+
+
+def hash_raw_module(module: ast.Module) -> bytes:
+ # AST has to be compiled to code object prior to process.
+ return hash_module(
+ compile(
+ module,
+ "<hash>",
+ mode="exec",
+ flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,
+ )
+ )
+
+
+def hash_cell_impl(cell: CellImpl) -> bytes:
+ return hash_module(cell.body) + hash_module(cell.last_expr)
+
+
+def build_execution_hash(
+ graph: DirectedGraph, cell_id: CellId_t
+) -> Optional[ValidCacheSha]:
+ # Execution path works by just analyzing the input cells to hash.
+ sha = hashlib.sha256()
+ ancestors = graph.ancestors(cell_id)
+ references = sorted(
+ [hash_cell_impl(graph.cells[cell_id]) for cell_id in ancestors]
+ )
+ for code in references:
+ sha.update(code)
+ return ValidCacheSha(sha, "ExecutionPath")
+
+
+def build_content_hash(
+ graph: DirectedGraph,
+ cell_id: CellId_t,
+ visitor: ScopedVisitor,
+ defs: dict[str, Any],
+) -> Optional[ValidCacheSha]:
+ # Content addressed hash is valid if every reference is accounted for and
+ # can be shown to be a primitive value.
+ sha = hashlib.sha256()
+ for ref in sorted(
+ graph.get_transitive_references(visitor.defs, inclusive=False)
+ | visitor.refs
+ ):
+ ref = is_local_then_mangle(ref, cell_id)
+ if ref not in defs:
+ if ref in defs["__builtins__"]:
+ continue
+ # ref is somehow not defined, because of unexpected execution path,
+ # do not utilize content hash in this case.
+ return None
+ else:
+ value = defs[ref]
+ # TODO: Hash module, and maybe recursively explore containers.
+ if isinstance(value, BASE_PRIMITIVES):
+ sha.update(str(value).encode("utf8"))
+ continue
+ return None
+ return ValidCacheSha(sha, "ContentAddressed")
+
+
+def cache_attempt_from_hash(
+ module: ast.Module,
+ graph: DirectedGraph,
+ cell_id: CellId_t,
+ defs: dict[str, Any],
+ *,
+ context: Optional[ast.Module] = None,
+ loader: Loader,
+) -> Cache:
+ """Hash the context of the module, and return a cache object.
+
+ Hashing occurs 2 exclusive methods, content addressed, and execution path:
+
+ 1) "Content Addressed" hashing is used when all references are known and
+ are shown to be primitive types (like a "pure" function).
+
+ 2) "Execution Path" hashing is when objects may contain state or other
+ hidden values that are difficult to hash deterministically. For this, the
+ code used to produce the object is used as the basis of the hash. It
+ follows that code which does not change, will produce the same output. This
+ draws inspiration from hashing methods in Nix. One notable difference
+ between these methods is that Nix sandboxes all execution, preventing
+ external file access, and internet. Sources of non-determinism are not
+ accounted for in this implementation, and are left to the user.
+
+ In both cases, as long as the module is deterministic, the output will be
+ deterministic.
+
+ TODO: Account for UI and state.
+
+ Args:
+ - module: The code content to create a hash for (e.g. persistent_cache,
+ the body of the `With` statement).
+ - graph: The dataflow graph of the notebook.
+ - cell_id: The cell id attached to the module.
+ - defs: The definitions of (globals) available in execution context.
+ - context: The "context" of the module, is a module corresponding
+ additional execution context for the cell. For instance, in
+ persistent_cache case, this applies to the code prior to invocation,
+ but still in the same cell.
+ - loader: The loader object to create/ save a cache object.
+
+ Returns:
+ - A cache object that may, or may not be fully populated.
+ """
+ # Empty name, so we can match and fill in cell context on load.
+ visitor = ScopedVisitor("", ignore_local=True)
+ visitor.visit(module)
+
+ # Attempt content hash
+ valid_cache_sha = build_content_hash(graph, cell_id, visitor, defs)
+ if not valid_cache_sha:
+ # Execution path hash
+ valid_cache_sha = build_execution_hash(graph, cell_id)
+ assert valid_cache_sha
+ if context:
+ valid_cache_sha.sha.update(hash_raw_module(context))
+
+ sha, cache_type = valid_cache_sha
+ sha.update(hash_raw_module(module))
+ hashed_context = (
+ base64.urlsafe_b64encode(sha.digest()).decode("utf-8").strip("=")
+ )
+
+ return loader.cache_attempt(visitor.defs, hashed_context, cache_type)
diff --git a/marimo/_save/loaders.py b/marimo/_save/loaders.py
new file mode 100644
index 0000000000..31ca7e23d3
--- /dev/null
+++ b/marimo/_save/loaders.py
@@ -0,0 +1,102 @@
+# 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
+
+from marimo._save.cache import CACHE_PREFIX, Cache, CacheType
+
+if TYPE_CHECKING:
+ from marimo._ast.visitor import Name
+
+INCONSISTENT_CACHE_BOILER_PLATE = (
+ "The cache state does not match "
+ "expectations, this can be due to file "
+ "corruption or an incompatible marimo "
+ "version. Alternatively, this may be a bug"
+ " in marimo. Please file an issue at "
+ "github.com/marimo-team/marimo/issues"
+)
+
+
+class Loader(ABC):
+ """Loaders are responsible for saving and loading persistent caches.
+
+ Loaders are provided a name, a save path and a cache key or "hash", which
+ should be deterministically determined given the notebook context.
+
+ In the future, they may be specialized for different types of data (such as
+ numpy or pandas dataframes), or remote storage (such as S3 or marimo
+ cloud).
+ """
+
+ def __init__(self, name: str, save_path: 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}"
+
+ def cache_attempt(
+ self, defs: set[Name], hashed_context: str, cache_type: CacheType
+ ) -> Cache:
+ if not self.cache_hit(hashed_context, cache_type):
+ return Cache(
+ {d: None for d in defs}, hashed_context, cache_type, False
+ )
+ loaded = self.load_cache(hashed_context, cache_type)
+ # TODO: Consider more robust verification
+ assert loaded.hash == hashed_context, INCONSISTENT_CACHE_BOILER_PLATE
+ assert set(defs) == set(loaded.defs), INCONSISTENT_CACHE_BOILER_PLATE
+ return Cache(loaded.defs, hashed_context, cache_type, True)
+
+ @abstractmethod
+ def cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:
+ """Check if cache has been hit given a result hash.
+
+ Args:
+ hashed_context: The hash of the result context
+ cache_type: The type of cache to check for
+
+ Returns:
+ bool: Whether the cache has been hit
+ """
+
+ @abstractmethod
+ def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
+ """Load Cache"""
+
+ @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:
+ return os.path.exists(self.build_path(hashed_context, cache_type))
+
+ 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
new file mode 100644
index 0000000000..a6a5443f58
--- /dev/null
+++ b/marimo/_save/save.py
@@ -0,0 +1,224 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+import io
+import sys
+import traceback
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Optional,
+ Type,
+ Union,
+)
+
+from marimo._messaging.tracebacks import write_traceback
+from marimo._runtime.context import get_context
+from marimo._save.ast import ExtractWithBlock
+from marimo._save.cache import Cache, contextual_defs
+from marimo._save.hash import cache_attempt_from_hash
+from marimo._save.loaders import Loader, PickleLoader
+
+# Many assertions are for typing and should always pass. This message is a
+# catch all to motive users to report if something does fail.
+UNEXPECTED_FAILURE_BOILERPLATE = (
+ "— this is"
+ " unexpected and is likely a bug in marimo. "
+ "Please file an issue at "
+ "https://github.com/marimo-team/marimo/issues"
+)
+
+
+if TYPE_CHECKING:
+ from types import FrameType, TracebackType
+
+ from _typeshed import TraceFunction
+ from typing_extensions import Self
+
+
+class SkipWithBlock(Exception):
+ """Special exception to get around executing the with block body."""
+
+
+# BaseException because "raise _ as e" is utilized.
+class CacheException(BaseException):
+ pass
+
+
+class persistent_cache(object):
+ """Context block for cache lookup of a block of code.
+
+ Example usage:
+
+ >>> with persistent_cache(name="my_cache"):
+ >>> variable = expensive_function() # This will be cached.
+
+ For an implementation sibling regarding the block skipping, see `withhacks`
+ in pypi.
+
+ NB: Since context abuses sys frame trace, this may conflict with debugging
+ tools that also use sys.settrace.
+ """
+
+ def __init__(
+ self,
+ *,
+ save_path: str = "outputs",
+ name: str,
+ _loader: Optional[Loader] = None,
+ ) -> None:
+ self.name = name
+ if _loader:
+ self._loader = _loader
+ else:
+ self._loader = PickleLoader(name, save_path)
+
+ self._skipped = True
+ self._cache: Optional[Cache] = None
+ self._entered_trace = False
+ self._old_trace: Optional[TraceFunction] = None
+ self._frame: Optional[FrameType] = None
+
+ def __enter__(self) -> Self:
+ sys.settrace(lambda *_args, **_keys: None)
+ frame = sys._getframe(1)
+ # Hold on to the previous trace.
+ self._old_trace = frame.f_trace
+ # Setting the frametrace, will cause the function to be run on _every_
+ # single context call until the trace is cleared.
+ frame.f_trace = self.trace
+ return self
+
+ def trace(
+ self, with_frame: FrameType, _event: str, _arg: Any
+ ) -> 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.
+ # 2) Run static analysis to determine whether the call meets our
+ # criteria. The procedure is a little brittle as such, certain contexts
+ # are not allow (e.g. called within a function or a loop).
+ # 3) Hash the execution and lookup the cache, and return!
+ # otherwise) Set _skipped such that the block continues to execute.
+
+ self._entered_trace = True
+ stack = traceback.extract_stack()
+
+ if not self._skipped:
+ return self._old_trace
+
+ # This is possible if `With` spans multiple lines.
+ # This behavior may be a python bug.
+ # Could not replicate in 3.10, 3.11 or 3.12 with direct testing; but it
+ # may be due to the block being compiled prior to traversal.
+ # See failure in:
+ # github:marimo/actions/runs/9947523119/job/27480334273?pr=1758
+ # TODO: Dig in and report bug to CPython.
+ if self._cache and self._cache.hit:
+ raise SkipWithBlock()
+
+ # This only executes on the first line of code in the block. If the
+ # cache is hit, the block terminates early with a SkipWithBlock
+ # exception, if the block is not hit, self._skipped is set to False,
+ # causing this function to terminate before reaching this block.
+ self._frame = with_frame
+ for i, frame in enumerate(stack[::-1]):
+ _filename, lineno, function_name, _code = frame
+ if function_name == "<module>":
+ ctx = get_context()
+ assert ctx.execution_context is not None, (
+ "Could not resolve context for cache.",
+ f"{UNEXPECTED_FAILURE_BOILERPLATE}",
+ )
+ graph = ctx.graph
+ cell_id = (
+ ctx.execution_context.cell_id
+ or ctx.execution_context.cell_id
+ )
+ pre_module, save_module = ExtractWithBlock(lineno - 1).visit(
+ ast.parse(graph.cells[cell_id].code).body # type: ignore[arg-type]
+ )
+
+ self._cache = cache_attempt_from_hash(
+ save_module,
+ graph,
+ cell_id,
+ {**globals(), **with_frame.f_locals},
+ loader=self._loader,
+ context=pre_module,
+ )
+
+ self.cache_type = self._cache
+ # Raising on the first valid line, prevents a bug where
+ # whitespace in `With`, changes behavior. This might be
+ # an issue with Python's parser? Noticed because lint/ format
+ # breaks things.
+ if self._cache and self._cache.hit:
+ if lineno >= save_module.body[0].lineno:
+ raise SkipWithBlock()
+ return self._old_trace
+ self._skipped = False
+ return self._old_trace
+ elif i > 1:
+ raise CacheException(
+ "`persistent_cache` must be invoked from cell level "
+ "(cannot be in a function or class)"
+ )
+ raise CacheException(
+ (
+ "`persistent_cache` could not resolve block"
+ f"{UNEXPECTED_FAILURE_BOILERPLATE}"
+ )
+ )
+
+ def __exit__(
+ self,
+ exception: Optional[Type[BaseException]],
+ instance: Optional[BaseException],
+ _tracebacktype: Optional[TracebackType],
+ ) -> bool:
+ sys.settrace(self._old_trace) # Clear to previous set trace.
+ if not self._entered_trace:
+ raise CacheException(
+ ("Unexpected block format" f"{UNEXPECTED_FAILURE_BOILERPLATE}")
+ )
+
+ # Backfill the loaded values into global scope.
+ if self._cache and self._cache.hit:
+ assert self._frame is not None, UNEXPECTED_FAILURE_BOILERPLATE
+ for lookup, var in contextual_defs(self._cache):
+ self._frame.f_locals[var] = self._cache.defs[lookup]
+ # Return true to suppress the SkipWithBlock exception.
+ return True
+
+ # NB: exception is a type.
+ if exception:
+ assert not isinstance(instance, SkipWithBlock), (
+ "Cache was not correctly set"
+ f"{UNEXPECTED_FAILURE_BOILERPLATE}"
+ )
+ if isinstance(instance, BaseException):
+ raise instance from CacheException("Failure during save.")
+ raise exception
+
+ # Fill the cache object and save.
+ assert self._cache is not None, UNEXPECTED_FAILURE_BOILERPLATE
+ assert self._frame is not None, UNEXPECTED_FAILURE_BOILERPLATE
+ for lookup, var in contextual_defs(self._cache):
+ self._cache.defs[lookup] = self._frame.f_locals[var]
+
+ try:
+ self._loader.save_cache(self._cache)
+ except Exception as e:
+ sys.stderr.write(
+ "An exception was raised when attempting to cache this code "
+ "block with the following message:\n"
+ f"{str(e)}\n"
+ "NOTE: The cell has run, but cache has not been saved.\n"
+ )
+ tmpio = io.StringIO()
+ traceback.print_exc(file=tmpio)
+ tmpio.seek(0)
+ write_traceback(tmpio.read())
+ return False
diff --git a/marimo/_utils/variables.py b/marimo/_utils/variables.py
index cae340b3cb..89004ec46c 100644
--- a/marimo/_utils/variables.py
+++ b/marimo/_utils/variables.py
@@ -1,12 +1,25 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import re
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from marimo._ast.cell import CellId_t
+def is_local_then_mangle(ref: str, cell_id: CellId_t) -> str:
+ if is_local(ref):
+ if ref.startswith("_cell"):
+ return ref
+ return f"_cell_{cell_id}{ref}"
+ return ref
+
+
+def unmangle_local(name: str) -> tuple[str, str]:
+ return re.sub(r"^_cell_\w+", "_", name), name[6:10]
+
+
def is_mangled_local(name: str, cell_id: CellId_t) -> bool:
return name.startswith(f"_cell_{cell_id}")
diff --git a/tests/_save/mocks.py b/tests/_save/mocks.py
new file mode 100644
index 0000000000..7ab83dd491
--- /dev/null
+++ b/tests/_save/mocks.py
@@ -0,0 +1,31 @@
+from __future__ import annotations
+
+from typing import Any, Dict, Optional
+
+from marimo._save.cache import Cache, CacheType
+from marimo._save.loaders import Loader
+
+
+class MockLoader(Loader):
+ def __init__(
+ self,
+ name: str = "mock",
+ save_path: str = "",
+ data: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ self.name = name
+ self.save_path = save_path
+ self._data = data or {}
+ self._cache_hit = data is not None
+ self._loaded = False
+ self._saved = False
+
+ def cache_hit(self, _hashed_context: str, _cache_type: CacheType) -> bool:
+ return self._cache_hit
+
+ def load_cache(self, hashed_context: str, cache_type: CacheType) -> Cache:
+ self._loaded = True
+ return Cache(self._data, hashed_context, cache_type, True)
+
+ def save_cache(self, _cache: Cache) -> None:
+ self._saved = True
diff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.py
new file mode 100644
index 0000000000..9aa6a966ab
--- /dev/null
+++ b/tests/_save/test_cache.py
@@ -0,0 +1,170 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+from __future__ import annotations
+
+import textwrap
+
+from marimo._ast.app import App
+from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.runtime import Kernel
+
+
+class TestScriptCache:
+ @staticmethod
+ def test_cache_miss() -> None:
+ app = App()
+
+ @app.cell
+ def one() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ Y = 8
+ X = 7
+ assert X == 7
+ assert cache._cache.defs == {"X": 7, "Y": 8}
+ assert cache._loader._saved
+ assert not cache._loader._loaded
+ return X, Y, persistent_cache
+
+ app.run()
+
+ @staticmethod
+ def test_cache_hit() -> None:
+ app = App()
+
+ @app.cell
+ def one() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(
+ name="one", _loader=MockLoader(data={"X": 7, "Y": 8})
+ ) as cache:
+ Y = 9
+ X = 10
+ assert X == 7
+ assert cache._cache.defs == {"X": 7, "Y": 8}
+ assert not cache._loader._saved
+ assert cache._loader._loaded
+ return X, Y, persistent_cache
+
+ app.run()
+
+ @staticmethod
+ def test_cache_hit_whitespace() -> None:
+ app = App()
+
+ @app.cell
+ def one() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ # fmt: off
+ with persistent_cache(name="one", _loader=MockLoader(data={"X": 7, "Y": 8})) as cache: # noqa: E501
+ Y = 9
+ X = 10
+ # fmt: on
+ assert X == 7
+ assert cache._cache.defs == {"X": 7, "Y": 8}
+ assert not cache._loader._saved
+ assert cache._loader._loaded
+ return X, Y, persistent_cache
+
+ app.run()
+
+
+class TestAppCache:
+ async def test_cache_miss(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent("""
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(name="one") as cache:
+ Y = 9
+ X = 10
+ Z = 3
+ """),
+ ),
+ ]
+ )
+ assert k.globals["Y"] == 9
+ assert k.globals["X"] == 10
+ assert k.globals["Z"] == 3
+
+ async def test_cache_hit(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ 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": 7, "Y": 8})
+ ) as cache:
+ Y = 9
+ X = 10
+ Z = 3
+ """),
+ ),
+ ]
+ )
+ assert k.globals["X"] == 7
+ assert k.globals["Y"] == 8
+ assert k.globals["Z"] == 3
+
+ async def test_cache_one_line(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ 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
+ """),
+ ),
+ ]
+ )
+ assert k.errors == {}
+ assert k.errors == {}
+ assert k.globals["X"] == 1
+ assert k.globals["Y"] == 2
+
+ async def test_cache_comment_line(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent("""
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(name="one"):
+ # Comment
+
+ # whitespace
+ X = 1 # Comment
+ Y = 2
+ """),
+ ),
+ ]
+ )
+ assert k.errors == {}
+ assert k.errors == {}
+ assert k.globals["X"] == 1
+ assert k.globals["Y"] == 2
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
new file mode 100644
index 0000000000..5ec0ec1890
--- /dev/null
+++ b/tests/_save/test_hash.py
@@ -0,0 +1,155 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+from __future__ import annotations
+
+import pytest
+
+from marimo._ast.app import App
+
+
+class TestHash:
+ @staticmethod
+ def test_content_hash() -> None:
+ app = App()
+
+ @app.cell
+ def one() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ Y = 8
+ assert cache._cache.cache_type == "ContentAddressed"
+ return Y
+
+ app.run()
+
+ # Note: Hash may change based on byte code, so pin to particular version
+ @staticmethod
+ @pytest.mark.skipif(
+ "sys.version_info < (3, 11) or sys.version_info >= (3, 12)"
+ )
+ def test_content_reproducibility() -> None:
+ app = App()
+
+ @app.cell
+ def load() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ expected_hash = "vi8ruEJL5Wja4sNnDwJZV8b0FGEOHOn_LOJY8RG51W4"
+
+ return expected_hash, persistent_cache, MockLoader
+
+ @app.cell
+ def one(expected_hash, persistent_cache, MockLoader) -> tuple[int]:
+ _a = 1
+ with persistent_cache(
+ name="one", _loader=MockLoader(data={"_X": 7})
+ ) as _cache:
+ _X = 10 + _a
+ assert _X == 7
+ print(_cache._cache.hash)
+ assert _cache._cache.cache_type == "ContentAddressed"
+ assert _cache._cache.hash == expected_hash
+ return
+
+ @app.cell
+ def two(expected_hash, persistent_cache, MockLoader) -> tuple[int]:
+ # The same as cell one, but with this comment
+ _a = 2 - 1
+
+ # Some white space
+ with persistent_cache(
+ name="one", _loader=MockLoader(data={"_X": 7})
+ ) as _cache:
+ # More Comments
+ _X = 10 + _a
+ assert _X == 7
+ print(_cache._cache.hash)
+ assert _cache._cache.cache_type == "ContentAddressed"
+ assert _cache._cache.hash == expected_hash
+ # and a post block difference
+ Z = 11
+ return Z
+
+ app.run()
+
+ @staticmethod
+ def test_execution_hash() -> None:
+ app = App()
+
+ @app.cell
+ def one() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ non_primitive = [object()]
+
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ Y = 8 + len(non_primitive)
+ assert cache._cache.cache_type == "ExecutionPath"
+ return Y
+
+ app.run()
+
+ @staticmethod
+ @pytest.mark.skipif(
+ "sys.version_info < (3, 11) or sys.version_info >= (3, 12)"
+ )
+ def test_execution_reproducibility() -> None:
+ app = App()
+
+ @app.cell
+ def load() -> tuple[int]:
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ shared = [None, object()]
+ return persistent_cache, MockLoader, shared
+
+ @app.cell
+ def one(persistent_cache, MockLoader, shared) -> tuple[int]:
+ _a = [1]
+ with persistent_cache(
+ name="one", _loader=MockLoader(data={"_X": 7})
+ ) as _cache:
+ _X = (
+ 10
+ + _a[0] # Comment
+ - len(shared)
+ )
+ assert _X == 7
+ print(_cache._cache.hash)
+ assert (
+ _cache._cache.hash
+ == "84XqUk17Yiuz_jlAVbtdCOvWHrUFj-YApa7-0rB8Kl8"
+ )
+ assert _cache._cache.cache_type == "ExecutionPath"
+ return
+
+ @app.cell
+ def two(persistent_cache, MockLoader, shared) -> tuple[int]:
+ # The same as cell one, but with this comment
+ _a = [
+ 1, # Comment
+ ]
+
+ # Some white space
+ with persistent_cache(
+ name="one", _loader=MockLoader(data={"_X": 7})
+ ) as _cache:
+ # More Comments
+ _X = 10 + _a[0] - len(shared)
+ assert _X == 7
+ print(_cache._cache.hash)
+ assert (
+ _cache._cache.hash
+ == "84XqUk17Yiuz_jlAVbtdCOvWHrUFj-YApa7-0rB8Kl8"
+ )
+ assert _cache._cache.cache_type == "ExecutionPath"
+ # and a post block difference
+ Z = 11
+ return Z
+
+ app.run()