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: Account for state and variable type in save (#1993)

Dylan Madisetti5b50371924bf
diff --git a/frontend/2043.py b/frontend/2043.py
deleted file mode 100644
index af3a7509d2..0000000000
--- a/frontend/2043.py
+++ /dev/null
@@ -1,133 +0,0 @@
-import marimo
-
-__generated_with = "0.8.0"
-app = marimo.App(width="medium")
-
-
-def __():
- import marimo as mo
- import anywidget
- import traitlets
- import random
- return anywidget, mo, random, traitlets
-
-
[email protected](hide_code=True)
-def __(anywidget, traitlets):
- class CounterWidget(anywidget.AnyWidget):
- _esm = """
- function render({ model, el }) {
- const button = document.createElement("button");
- const update = () => {
- button.innerHTML = `${model.get("msg")} ${model.get("count")} (js-none: ${Math.random().toFixed(3)})`;
- };
- button.addEventListener("click", () => {
- model.set("count", model.get("count") + 1);
- model.save_changes();
- });
- update();
- model.on("change:count", update);
- model.on("change:msg", update);
- el.classList.add("counter-widget");
- el.appendChild(button);
- }
- export default { render };
- """
- _css = """
- .counter-widget button { color: white; font-size: 1.75rem; background-color: #ea580c; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; }
- .counter-widget button:hover { background-color: #9a3412; }
- """
- count = traitlets.Int(0).tag(sync=True)
- msg = traitlets.Unicode("").tag(sync=True)
- return CounterWidget,
-
-
-def __(mo):
- mo.md(r"""## Just anywidget""")
- return
-
-
-def __(CounterWidget):
- counter = CounterWidget(count=42, msg="count is")
- return counter,
-
-
-def __(counter):
- counter
- return
-
-
-def __(counter, mo, random):
- def _one(v):
- counter.set_trait(
- "msg", f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"
- )
-
-
- def _two(v):
- counter.msg = f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"
-
-
- one = mo.ui.button(label="set_trait", on_change=_one)
- two = mo.ui.button(label="counter.msg = x", on_change=_two)
- mo.hstack([one, two]).left()
- return one, two
-
-
[email protected](hide_code=True)
-def __(mo):
- mo.md(r"""## Wrapped in mo.ui.anywidget""")
- return
-
-
-def __(CounterWidget, mo):
- wrapped_counter = mo.ui.anywidget(CounterWidget(count=42, msg="count is"))
- return wrapped_counter,
-
-
-def __(wrapped_counter):
- wrapped_counter
- return
-
-
-def __(mo, random, wrapped_counter):
- def _one(v):
- wrapped_counter.set_trait(
- "msg", f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"
- )
-
-
- def _two(v):
- wrapped_counter.msg = f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"
-
-
- def _three(v):
- wrapped_counter.widget.msg = (
- f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"
- )
-
-
- button_one = mo.ui.button(label="set_trait", on_change=_one)
- button_two = mo.ui.button(label="counter.msg = x", on_change=_two)
- button_three = mo.ui.button(label="counter.widgt.msg = x", on_change=_two)
- mo.hstack([button_one, button_two, button_three]).left()
- return button_one, button_three, button_two
-
-
-def __(wrapped_counter):
- # Should be: <class '...MarimoComm'>
- type(wrapped_counter.widget.comm)
- return
-
-
-if __name__ == "__main__":
- app.run()
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.py
index 841c46b0cc..de0b64d2a4 100644
--- a/marimo/_plugins/ui/_core/registry.py
+++ b/marimo/_plugins/ui/_core/registry.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import sys
import weakref
-from typing import Any, Dict, Iterable, Mapping, TypeVar, Union
+from typing import Any, Dict, Iterable, Mapping, Optional, TypeVar, Union
from marimo._runtime.context.types import ContextNotInitializedError
@@ -95,15 +95,35 @@ class UIElementRegistry:
bindings.add(name)
return bindings
- def _register_bindings(self, object_id: UIElementId) -> None:
+ def _register_bindings(
+ self, object_id: UIElementId, glbls: Optional[dict[str, Any]] = None
+ ) -> None:
from marimo._runtime.context.kernel_context import KernelRuntimeContext
ctx = get_context()
- if isinstance(ctx, KernelRuntimeContext):
+ if isinstance(ctx, KernelRuntimeContext) or glbls is not None:
+ if glbls is None:
+ glbls = ctx.globals
self._bindings[object_id] = self._find_bindings_in_namespace(
- object_id, ctx.globals
+ object_id, glbls
)
+ def register_scope(
+ self, glbls: dict[str, Any], defs: Optional[set[str]] = None
+ ) -> None:
+ if defs is None:
+ defs = set(glbls.keys())
+ for binding in defs:
+ lookup = glbls.get(binding, None)
+ if isinstance(lookup, UIElement):
+ self._register_bindings(lookup._id, glbls)
+
+ def lookup(self, name: str) -> Optional[UIElement[Any, Any]]:
+ for object_id, bindings in self._bindings.items():
+ if name in bindings:
+ return self.get_object(object_id)
+ return None
+
def get_object(self, object_id: UIElementId) -> UIElement[Any, Any]:
if object_id not in self._objects:
raise KeyError(f"UIElement with id {object_id} not found")
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index 88e30e9a17..f1d2091e33 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -124,12 +124,14 @@ def create_kernel_context(
parent: KernelRuntimeContext | None = None,
) -> KernelRuntimeContext:
from marimo._plugins.ui._core.registry import UIElementRegistry
+ from marimo._runtime.state import StateRegistry
from marimo._runtime.virtual_file import VirtualFileRegistry
return KernelRuntimeContext(
_kernel=kernel,
_app=app,
ui_element_registry=UIElementRegistry(),
+ state_registry=StateRegistry(),
function_registry=FunctionRegistry(),
cell_lifecycle_registry=CellLifecycleRegistry(),
virtual_file_registry=VirtualFileRegistry(),
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index 8b7eb653e1..b1b3aefa48 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -18,12 +18,12 @@ 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.state import State, StateRegistry
if TYPE_CHECKING:
from marimo._ast.app import InternalApp
from marimo._ast.cell import CellId_t
from marimo._messaging.types import Stream
- from marimo._runtime.state import State
@dataclass
@@ -34,7 +34,7 @@ class ScriptRuntimeContext(RuntimeContext):
def __post_init__(self) -> None:
self._cli_args: CLIArgs | None = None
- self._query_params = QueryParams({})
+ self._query_params = QueryParams({}, _registry=self.state_registry)
@property
def graph(self) -> DirectedGraph:
@@ -120,6 +120,7 @@ def initialize_script_context(app: InternalApp, stream: Stream) -> None:
runtime_context = ScriptRuntimeContext(
_app=app,
ui_element_registry=UIElementRegistry(),
+ state_registry=StateRegistry(),
function_registry=FunctionRegistry(),
cell_lifecycle_registry=CellLifecycleRegistry(),
virtual_file_registry=VirtualFileRegistry(),
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index 24a302dcb0..d83455db85 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -25,7 +25,7 @@ if TYPE_CHECKING:
from marimo._output.hypertext import Html
from marimo._plugins.ui._core.registry import UIElementRegistry
from marimo._runtime.params import CLIArgs, QueryParams
- from marimo._runtime.state import State
+ from marimo._runtime.state import State, StateRegistry
from marimo._runtime.virtual_file import VirtualFileRegistry
@@ -64,6 +64,7 @@ class ExecutionContext:
@dataclass
class RuntimeContext(abc.ABC):
ui_element_registry: UIElementRegistry
+ state_registry: StateRegistry
function_registry: FunctionRegistry
cell_lifecycle_registry: CellLifecycleRegistry
virtual_file_registry: VirtualFileRegistry
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 5263cac2e8..1acf41d200 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import threading
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Callable, List, Literal, Tuple
+from typing import TYPE_CHECKING, Any, Callable, List, Literal, Optional, Tuple
from marimo import _loggers
from marimo._ast.cell import (
@@ -11,13 +11,14 @@ from marimo._ast.cell import (
CellImpl,
)
from marimo._ast.compiler import code_key
-from marimo._ast.visitor import Name, VariableData
+from marimo._ast.visitor import ImportData, Name, VariableData
from marimo._runtime.executor import execute_cell, execute_cell_async
from marimo._utils.variables import is_mangled_local
if TYPE_CHECKING:
from collections.abc import Collection
+
Edge = Tuple[CellId_t, CellId_t]
# EdgeWithVar uses a list rather than a set for the variables linking the cells
# as sets are not JSON-serializable (required by static_notebook_template()).
@@ -316,6 +317,18 @@ class DirectedGraph:
queue.append(parent_id)
return False
+ def get_imports(
+ self, cell_id: Optional[CellId_t] = None
+ ) -> dict[Name, ImportData]:
+ imports = {}
+ cells = (
+ self.cells.values() if cell_id is None else [self.cells[cell_id]]
+ )
+ for cell in cells:
+ for imported in cell.imports:
+ imports[imported.definition] = imported
+ return imports
+
def get_multiply_defined(self) -> list[Name]:
names = []
for name, definers in self.definitions.items():
diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.py
index 3df9f2abe8..6653cb1853 100644
--- a/marimo/_runtime/executor.py
+++ b/marimo/_runtime/executor.py
@@ -2,9 +2,7 @@
from __future__ import annotations
import inspect
-import numbers
import re
-import weakref
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import TYPE_CHECKING, Any, Callable, Optional, Type
@@ -16,10 +14,13 @@ from marimo._runtime.copy import (
ZeroCopy,
shallow_copy,
)
+from marimo._runtime.primitives import (
+ CLONE_PRIMITIVES,
+ build_ref_predicate_for_primitives,
+)
from marimo._utils.variables import is_mangled_local, unmangle_local
if TYPE_CHECKING:
- from marimo._ast.visitor import Name, VariableData
from marimo._runtime.dataflow import DirectedGraph
@@ -37,7 +38,6 @@ UNCLONABLE_MODULES = set(
"numpy.lib.npyio",
]
)
-PRIMITIVES = (weakref.ref, str, numbers.Number, type(None))
EXECUTION_TYPES: dict[str, Type[Executor]] = {}
@@ -183,7 +183,10 @@ class StrictExecutor(Executor):
) -> Any:
# Manage globals and references, but refers to the default beyond that.
refs = graph.get_transitive_references(
- cell.refs, predicate=build_ref_predicate(glbls)
+ cell.refs,
+ predicate=build_ref_predicate_for_primitives(
+ glbls, CLONE_PRIMITIVES
+ ),
)
backup = StrictExecutor.sanitize_inputs(cell, refs, glbls)
try:
@@ -200,7 +203,10 @@ class StrictExecutor(Executor):
cell: CellImpl, glbls: dict[str, Any], graph: DirectedGraph
) -> Any:
refs = graph.get_transitive_references(
- cell.refs, predicate=build_ref_predicate(glbls)
+ cell.refs,
+ predicate=build_ref_predicate_for_primitives(
+ glbls, CLONE_PRIMITIVES
+ ),
)
backup = StrictExecutor.sanitize_inputs(cell, refs, glbls)
try:
@@ -309,77 +315,6 @@ class StrictExecutor(Executor):
glbls[df] = lcls[df]
-def build_ref_predicate(
- glbls: dict[str, Any],
-) -> Callable[[Name, VariableData], bool]:
- """
- Builds a predicate function to determine if a reference should be included
-
- Args:
- glbls: The global variables dictionary to base the predicate on
- Returns:
- A function that takes a variable name and associated data and
- returns True if its reference should be included in a reference search.
-
- All declared variables are tied together under the graph of required_refs.
- Strict execution gets the minimum graph of definitions for execution.
- Certain definitions, like lambdas, functions, and classes contain an
- executable body and require their `required_refs` to be scope (included in
- this graph). This function determines if a potential reference should be
- included in the graph based on its computed type. Consider:
-
- >>> def foo():
- ... return bar()
-
- here `foo` is a function with `bar` as a reference in the execution body,
- so if `foo` is a reference, both `bar` and `foo` should be included in the
- graph, otherwise we'll get a NameError on `bar` if `foo` is called.
- Compare that to:
-
- >>> x = foo()
-
- if `x` is the only reference, should `foo` be included in the graph? It
- depends on the context, so we defer to the type of `x` which has already
- been computed at this point. If `x` is a known 'primitive' type, and thus
- does not have an executable body, we can exclude `foo` from the graph.
- However, `foo` may return a object or another function, which in turn may
- have references; so if x doesn't match the very low bar 'primitive', its
- `required_refs` are included in the graph.
-
- NB: lambdas, as anonymous functions, do not have a name to refer to them-
- so visitor injects the dummy variable `_lambda` into the `required_refs` to
- denote their presence.
- """
-
- def check_ref(ref: Name) -> bool:
- return ref in glbls and (
- inspect.isfunction(glbls[ref])
- or inspect.ismodule(glbls[ref])
- or inspect.isclass(glbls[ref])
- or callable(glbls[ref])
- )
-
- def only_scoped_refs(ref: Name, data: VariableData) -> bool:
- # Weakref instances should be disassociated from related references,
- # as should other "primitives" as they are results and hopefully not
- # hiding some scoped reference. Other common types could be added here,
- # like numpy arrays that are not dtype=object, etc.. that are known not
- # to be dependent on the functions that created them.
-
- # This errs on the side of including too much, but that's a better user
- # experience than not having definitions available.
- return (
- ref in glbls
- and not isinstance(glbls[ref], PRIMITIVES)
- and (
- "_lambda" in data.required_refs
- or any(map(check_ref, data.required_refs | {ref}))
- )
- )
-
- return only_scoped_refs
-
-
def is_instance_by_name(obj: object, name: str) -> bool:
if not (hasattr(obj, "__module__") and hasattr(obj, "__class__")):
return False
diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.py
index f53614e8ca..895f1c89bc 100644
--- a/marimo/_runtime/params.py
+++ b/marimo/_runtime/params.py
@@ -18,7 +18,7 @@ from marimo._runtime.requests import (
SerializedCLIArgs,
SerializedQueryParams,
)
-from marimo._runtime.state import State
+from marimo._runtime.state import State, StateRegistry
@mddoc
@@ -31,8 +31,9 @@ class QueryParams(State[SerializedQueryParams]):
self,
params: Dict[str, Union[str, List[str]]],
stream: Optional[Stream] = None,
+ _registry: Optional[StateRegistry] = None,
):
- super().__init__(params)
+ super().__init__(params, _registry=_registry)
self._params = params
self._stream = stream
diff --git a/marimo/_runtime/primitives.py b/marimo/_runtime/primitives.py
new file mode 100644
index 0000000000..7c863944ed
--- /dev/null
+++ b/marimo/_runtime/primitives.py
@@ -0,0 +1,241 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import inspect
+import numbers
+import sys
+import weakref
+from typing import TYPE_CHECKING, Any, Callable, Optional, Union
+
+from marimo._ast.visitor import Name, VariableData
+
+if TYPE_CHECKING:
+ from marimo._runtime.dataflow import DirectedGraph
+
+PRIMITIVES: tuple[type, ...] = (bytes, str, numbers.Number, type(None))
+# Weakref instances should be disassociated from related references, as should
+# other "primitives" as they are results and hopefully not hiding some scoped
+# reference.
+CLONE_PRIMITIVES = (weakref.ref,) + PRIMITIVES
+
+if sys.version_info < (3, 9):
+ # Future does not seem to work for this in CI.
+ FN_CACHE_TYPE = Optional["dict[Union[Callable[..., Any], type], bool]"]
+else:
+ FN_CACHE_TYPE = Optional[dict[Union[Callable[..., Any], type], bool]]
+
+
+def is_external(value: Any) -> bool:
+ return "_marimo__cell_" not in inspect.getfile(value)
+
+
+def is_primitive(value: Any) -> bool:
+ # Tuples don't allow for write access
+ if isinstance(value, tuple):
+ return all(map(is_primitive, value))
+ return isinstance(value, PRIMITIVES)
+
+
+def is_primitive_type(value: type) -> bool:
+ return any(issubclass(value, primitive) for primitive in PRIMITIVES)
+
+
+def is_clone_primitive(value: Any) -> bool:
+ return isinstance(value, CLONE_PRIMITIVES)
+
+
+def is_data_primitive(value: Any) -> bool:
+ if is_primitive(value):
+ return True
+
+ # If a numpy array, ensure that it's not an object array.
+ if hasattr(value, "__array_interface__"):
+ dtype = getattr(value, "dtype", None)
+ return not (
+ dtype is not None
+ and hasattr(dtype, "hasobject")
+ and dtype.hasobject
+ )
+
+ # Otherwise may be a closely related array object like a pandas DataFrame.
+ return hasattr(value, "__array__") or hasattr(value, "toarray")
+
+
+def _is_primitive_container(
+ value: Any, predicate: Callable[[Any], bool]
+) -> bool:
+ visited = set()
+
+ def recurse_container(value: Any) -> bool:
+ if is_primitive(value):
+ return True
+
+ if id(value) in visited:
+ return True
+
+ if isinstance(value, dict):
+ visited.add(id(value))
+ return all(map(predicate, value.items()))
+ # Tuple has to be considered too, since a tuple can contain containers.
+ if isinstance(value, (set, list, tuple)):
+ visited.add(id(value))
+ return all(map(predicate, value))
+
+ return False
+
+ return recurse_container(value)
+
+
+def is_data_primitive_container(value: Any) -> bool:
+ return _is_primitive_container(value, is_data_primitive)
+
+
+def is_primitive_container(value: Any) -> bool:
+ return _is_primitive_container(value, is_primitive)
+
+
+def is_pure_scope(
+ ref: Name,
+ defs: dict[str, Any],
+ cache: FN_CACHE_TYPE = None,
+) -> bool:
+ return inspect.ismodule(defs[ref]) or is_pure_function(
+ ref, defs[ref], defs, cache
+ )
+
+
+def is_pure_function(
+ ref: Name,
+ value: Any,
+ defs: dict[str, Any],
+ cache: FN_CACHE_TYPE = None,
+ graph: Optional[DirectedGraph] = None,
+) -> bool:
+ if cache is None:
+ cache = {}
+ # Explicit removal of __hash__ indicates this is potentially mutable.
+ # (e.g. list)
+ if getattr(value, "__hash__", None) is None:
+ return False
+ if value in cache:
+ return cache[value]
+ # Trivial enough not to cache.
+ if inspect.isclass(value) or not callable(value):
+ return False
+ # builtin_function_or_method are C functions, which we assume to be pure
+ if inspect.isbuiltin(value):
+ return True
+
+ # Note: isfunction still covers lambdas, coroutines, etc.
+ if not inspect.isfunction(value):
+ return False
+
+ # We assume all external module function references to be pure. Cache can
+ # still be be invalidated by pin_modules attribute. Note this also captures
+ # cases like functors from an external module.
+ # TODO: Investigate embedded notebook values.
+ if getattr(value, "__module__", None) != "__main__":
+ return True
+
+ cache[value] = True # Prevent recursion
+
+ def cancel_predicate(ref: Name, _data: VariableData) -> bool:
+ if not cache[value]:
+ return False
+
+ # A pure function can only refer to other functions, classes, or
+ # modules.
+ # External variable reference makes it inherently impure.
+ if ref in defs:
+ # Recursion allows for effective DFS
+ if not (
+ inspect.ismodule(defs[ref])
+ or is_pure_function(ref, defs[ref], defs, cache, graph)
+ ):
+ cache[value] = False
+ return False
+ return True
+
+ if graph is not None:
+ graph.get_transitive_references(
+ {ref}, inclusive=False, predicate=cancel_predicate
+ )
+
+ return cache[value]
+
+
+def build_ref_predicate_for_primitives(
+ glbls: dict[str, Any],
+ primitives: Optional[tuple[type, ...]] = None,
+) -> Callable[[Name, VariableData], bool]:
+ """
+ Builds a predicate function to determine if a reference should be included
+
+ Args:
+ glbls: The global variables dictionary to base the predicate on
+ primitives: A tuple of types that should be considered as base types
+ Returns:
+ A function that takes a variable name and associated data and
+ returns True if its reference should be included in a reference search.
+
+ All declared variables are tied together under the graph of required_refs.
+ Strict execution gets the minimum graph of definitions for execution.
+ Certain definitions, like lambdas, functions, and classes contain an
+ executable body and require their `required_refs` to be scope (included in
+ this graph). This function determines if a potential reference should be
+ included in the graph based on its computed type. Consider:
+
+ >>> def foo():
+ ... return bar()
+
+ here `foo` is a function with `bar` as a reference in the execution body,
+ so if `foo` is a reference, both `bar` and `foo` should be included in the
+ graph, otherwise we'll get a NameError on `bar` if `foo` is called.
+ Compare that to:
+
+ >>> x = foo()
+
+ if `x` is the only reference, should `foo` be included in the graph? It
+ depends on the context, so we defer to the type of `x` which has already
+ been computed at this point. If `x` is a known 'primitive' type, and thus
+ does not have an executable body, we can exclude `foo` from the graph.
+ However, `foo` may return a object or another function, which in turn may
+ have references; so if x doesn't match the very low bar 'primitive', its
+ `required_refs` are included in the graph.
+
+ NB: The builtin `inspect.getclosurevars` exists, but it fails on some of
+ these edgecases.
+
+ NB: lambdas, as anonymous functions, do not have a name to refer to them-
+ so visitor injects the dummy variable `_lambda` into the `required_refs` to
+ denote their presence.
+ """
+
+ if primitives is None:
+ primitives = PRIMITIVES
+
+ def check_ref(ref: Name) -> bool:
+ return ref in glbls and (
+ inspect.isfunction(glbls[ref])
+ or inspect.ismodule(glbls[ref])
+ or inspect.isclass(glbls[ref])
+ or callable(glbls[ref])
+ )
+
+ def only_scoped_refs(ref: Name, data: VariableData) -> bool:
+ # TODO: Other common types could be added here, like numpy arrays that
+ # are not dtype=object, etc.. that are known not to be dependent on the
+ # functions that created them.
+
+ # This errs on the side of including too much, but that's a better user
+ # experience than not having definitions available.
+ return (
+ ref in glbls
+ and not isinstance(glbls[ref], primitives)
+ and (
+ "_lambda" in data.required_refs
+ or any(map(check_ref, data.required_refs | {ref}))
+ )
+ )
+
+ return only_scoped_refs
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 197eea1484..f7b995f0c4 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -26,7 +26,7 @@ from marimo._messaging.ops import (
from marimo._messaging.tracebacks import write_traceback
from marimo._output import formatting
from marimo._plugins.ui._core.ui_element import UIElement
-from marimo._runtime.context.types import get_global_context
+from marimo._runtime.context.types import get_context, get_global_context
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.runner import cell_runner
from marimo._tracer import kernel_tracer
@@ -169,6 +169,18 @@ def _store_reference_to_output(
cell.set_output(run_result.output)
+def _store_state_reference(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del run_result
+ # 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()))
+
+
@kernel_tracer.start_as_current_span("broadcast_outputs")
def _broadcast_outputs(
cell: CellImpl,
@@ -288,6 +300,7 @@ POST_EXECUTION_HOOKS: list[PostExecutionHookType] = [
_set_imported_defs,
_set_run_result_status,
_store_reference_to_output,
+ _store_state_reference,
_broadcast_variables,
_broadcast_datasets,
_broadcast_duckdb_tables,
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
index 1fbc6c8f7e..43801850f8 100644
--- a/marimo/_runtime/state.py
+++ b/marimo/_runtime/state.py
@@ -2,22 +2,114 @@
from __future__ import annotations
import types
-from typing import Callable, Generic, TypeVar
+import weakref
+from dataclasses import dataclass
+from typing import Any, Callable, Generic, Optional, TypeVar
+from uuid import uuid4
from marimo._output.rich_help import mddoc
from marimo._runtime.context import ContextNotInitializedError, get_context
T = TypeVar("T")
+Id = int
+
+
+@dataclass
+class StateItem(Generic[T]):
+ id: Id
+ 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 register(self, state: State[T], name: Optional[str] = None) -> None:
+ if name is None:
+ name = str(uuid4())
+ if id(state) in self._inv_states:
+ ref = next(iter(self._inv_states[id(state)]))
+ if self._states[ref].id != id(state):
+ for ref in self._inv_states[id(state)]:
+ del self._states[ref]
+ self._inv_states[id(state)].clear()
+ state_item = StateItem(id(state), weakref.ref(state))
+ self._states[name] = state_item
+ id_to_ref = self._inv_states.get(id(state), set())
+ id_to_ref.add(name)
+ self._inv_states[id(state)] = id_to_ref
+ finalizer = weakref.finalize(state, self._delete, name, state_item)
+ # No need to clean up the registry at program teardown
+ finalizer.atexit = False
+
+ def register_scope(
+ self, glbls: dict[str, Any], defs: Optional[set[str]] = None
+ ) -> None:
+ """Finds instances of state and scope, and adds them to registry if not
+ already present."""
+ if defs is None:
+ defs = set(glbls.keys())
+ for variable in defs:
+ lookup = glbls.get(variable, None)
+ if isinstance(lookup, State):
+ self.register(lookup, variable)
+
+ def _delete(self, name: str, state_item: StateItem[T]) -> None:
+ self._states.pop(name, None)
+ self._inv_states.pop(state_item.id, None)
+
+ def retain_active_states(self, active_variables: set[str]) -> None:
+ """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]
+ else:
+ active_state_ids.add(id(self._states[state_name]))
+
+ # 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]]:
+ if name in self._states:
+ return self._states[name].ref()
+ return None
+
+ def bound_names(self, state: State[T]) -> set[str]:
+ if id(state) in self._inv_states:
+ return self._inv_states[id(state)]
+ return set()
class State(Generic[T]):
"""Mutable reactive state"""
- def __init__(self, value: T, allow_self_loops: bool = False) -> None:
+ def __init__(
+ self,
+ value: T,
+ allow_self_loops: bool = False,
+ _registry: Optional[StateRegistry] = None,
+ ) -> None:
self._value = value
self.allow_self_loops = allow_self_loops
self._set_value = SetFunctor(self)
+ try:
+ if _registry is None:
+ _registry = get_context().state_registry
+ _registry.register(self)
+ except ContextNotInitializedError:
+ # Registration may be picked up later, but there is nothing to do
+ # at this point.
+ pass
+
def __call__(self) -> T:
return self._value
diff --git a/marimo/_save/ast.py b/marimo/_save/ast.py
index 5a6da6a9aa..9c55eabae1 100644
--- a/marimo/_save/ast.py
+++ b/marimo/_save/ast.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import ast
from typing import Any, Sequence, cast
+from marimo._utils.variables import unmangle_local
+
class BlockException(Exception):
pass
@@ -125,3 +127,16 @@ class ExtractWithBlock(ast.NodeTransformer):
raise BlockException(
"Saving on a shared line may lead to unexpected behavior."
)
+
+
+class DeprivateVisitor(ast.NodeTransformer):
+ """Removes the mangling of private variables from a module."""
+
+ def visit_Name(self, node: ast.Name) -> ast.Name:
+ node.id = unmangle_local(node.id).name
+ return node
+
+ def generic_visit(self, node: ast.AST) -> ast.AST:
+ if hasattr(node, "name") and node.name:
+ node.name = unmangle_local(node.name).name
+ return super().generic_visit(node)
diff --git a/marimo/_save/cache.py b/marimo/_save/cache.py
index f7fbd2588e..12519e7d8a 100644
--- a/marimo/_save/cache.py
+++ b/marimo/_save/cache.py
@@ -6,36 +6,113 @@ from collections import namedtuple
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal
-from marimo._runtime.context import get_context
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.context import ContextNotInitializedError, get_context
+from marimo._runtime.state import SetFunctor
if TYPE_CHECKING:
from marimo._ast.visitor import Name
-CacheType = Literal["ContentAddressed", "ExecutionPath", "Unknown"]
+CacheType = Literal[
+ "ContextExecutionPath",
+ "ContentAddressed",
+ "ExecutionPath",
+ "Pure",
+ "Unknown",
+]
# Easy visual identification of cache type.
CACHE_PREFIX: dict[CacheType, str] = {
+ "ContextExecutionPath": "X_",
"ContentAddressed": "C_",
"ExecutionPath": "E_",
+ "Pure": "P_",
"Unknown": "U_",
}
ValidCacheSha = namedtuple("ValidCacheSha", ("sha", "cache_type"))
+MetaKey = str # e.g. Literal["code", "output"]
+
+
+# BaseException because "raise _ as e" is utilized.
+class CacheException(BaseException):
+ pass
@dataclass
class Cache:
defs: dict[Name, Any]
hash: str
+ stateful_refs: set[str]
cache_type: CacheType
hit: bool
+ # meta corresponds to internally used data, kept as a dictionary to allow
+ # for backwards pickle compatibility with future entries.
+ # TODO: Utilize to store code and output in cache.
+ # TODO: Consider storing graph information such that execution history can
+ # be explored and visualized.
+ meta: dict[MetaKey, Any]
+
+ def restore(self, scope: dict[str, Any]) -> None:
+ """Restores values from cache, into scope."""
+ for var, lookup in self.contextual_defs():
+ scope[lookup] = self.defs[var]
+
+ defs = {**globals(), **scope}
+ for ref in self.stateful_refs:
+ if ref not in defs:
+ raise CacheException(
+ "Failure while restoring cached values. "
+ "Cache expected a reference to a "
+ f"variable that is not present ({ref})."
+ )
+ value = defs[ref]
+ if isinstance(value, SetFunctor):
+ value(self.defs[ref])
+ elif isinstance(value, UIElement):
+ value._update(self.defs[ref])
+ else:
+ raise CacheException(
+ "Failure while restoring cached values. "
+ "Unexpected stateful reference type "
+ f"({type(ref)}:{ref})."
+ )
+
+ def update(self, scope: dict[str, Any]) -> None:
+ """Loads values from scope, updating the cache."""
+ for var, lookup in self.contextual_defs():
+ self.defs[var] = scope[lookup]
+
+ defs = {**globals(), **scope}
+ for ref in self.stateful_refs:
+ if ref not in defs:
+ raise CacheException(
+ "Failure while saving cached values. "
+ "Cache expected a reference to a "
+ f"variable that is not present ({ref})."
+ )
+ value = defs[ref]
+ if isinstance(value, SetFunctor):
+ self.defs[ref] = value._state()
+ elif isinstance(value, UIElement):
+ self.defs[ref] = value.value
+ else:
+ raise CacheException(
+ "Failure while saving cached values. "
+ "Unexpected stateful reference type "
+ f"({type(ref)}:{ref})."
+ )
+ def contextual_defs(self) -> dict[tuple[Name, Name], Any]:
+ """Uses context to resolve private variable names."""
+ try:
+ context = get_context().execution_context
+ assert context is not None, "Context could not be resolved"
+ private_prefix = f"_cell_{context.cell_id}_"
+ except (ContextNotInitializedError, AssertionError):
+ private_prefix = r"^_cell_\w+_"
-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()
- }
+ return {
+ (var, re.sub(r"^_", private_prefix, var)): value
+ for var, value in self.defs.items()
+ if var not in self.stateful_refs
+ }
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index 4445189101..1d652210b3 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -4,31 +4,55 @@ from __future__ import annotations
import ast
import base64
import hashlib
-import numbers
+import struct
+import sys
import types
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Iterable, Optional
from marimo._ast.visitor import ScopedVisitor
-from marimo._save.cache import Cache, ValidCacheSha
-from marimo._utils.variables import is_local_then_mangle
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.context import ContextNotInitializedError, get_context
+from marimo._runtime.primitives import (
+ FN_CACHE_TYPE,
+ is_data_primitive,
+ is_data_primitive_container,
+ is_primitive,
+ is_pure_function,
+)
+from marimo._runtime.state import SetFunctor, State
+from marimo._save.ast import DeprivateVisitor
+from marimo._save.cache import Cache, CacheType
+from marimo._utils.variables import (
+ get_cell_from_local,
+ if_local_then_mangle,
+ unmangle_local,
+)
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
-BASE_PRIMITIVES = (str, numbers.Number, type(None))
+ # Union[list, torch.Tensor, jax.numpy.ndarray,
+ # np.ndarray, scipy.sparse.spmatrix]
+ Tensor = Any
-def hash_module(code: Optional[CodeType]) -> bytes:
+DEFAULT_HASH = "sha256"
+
+
+def hash_module(
+ code: Optional[CodeType], hash_type: str = DEFAULT_HASH
+) -> bytes:
+ hash_alg = hashlib.new(hash_type, usedforsecurity=False)
if not code:
- # SHA256 hash of 32 zero bytes, in the case of no code object
+ # Hash of zeros, in the case of no code object as a recognizable noop.
# Artifact of typing for mypy, but reasonable fallback.
- return b"0" * 32
-
- sha = hashlib.sha256()
+ return b"0" * len(hash_alg.digest())
def process(code_obj: CodeType) -> None:
# Recursively hash the constants that are also code objects
@@ -36,17 +60,19 @@ def hash_module(code: Optional[CodeType]) -> bytes:
if isinstance(const, types.CodeType):
process(const)
else:
- sha.update(str(const).encode("utf8"))
+ hash_alg.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)
+ hash_alg.update(bytes("|".join(code_obj.co_names), "utf8"))
+ hash_alg.update(code_obj.co_code)
process(code)
- return sha.digest()
+ return hash_alg.digest()
-def hash_raw_module(module: ast.Module) -> bytes:
+def hash_raw_module(
+ module: ast.Module, hash_type: str = DEFAULT_HASH
+) -> bytes:
# AST has to be compiled to code object prior to process.
return hash_module(
compile(
@@ -54,120 +80,535 @@ def hash_raw_module(module: ast.Module) -> bytes:
"<hash>",
mode="exec",
flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,
- )
+ ),
+ hash_type,
)
-def hash_cell_impl(cell: CellImpl) -> bytes:
- return hash_module(cell.body) + hash_module(cell.last_expr)
+def hash_cell_impl(cell: CellImpl, hash_type: str = DEFAULT_HASH) -> bytes:
+ return hash_module(cell.body, hash_type) + hash_module(
+ cell.last_expr, hash_type
+ )
+
+def standardize_tensor(tensor: Tensor) -> Optional[Tensor]:
+ # TODO: Consider moving to a more general utility module.
+ if hasattr(tensor, "__array__") or hasattr(tensor, "toarray"):
+ if not hasattr(tensor, "__array_interface__"):
+ DependencyManager.numpy.require(
+ "to access data buffer for hashing."
+ )
+ import numpy
-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]
+ # Capture those sparse cases
+ if hasattr(tensor, "toarray"):
+ tensor = tensor.toarray()
+ tensor = numpy.array(tensor)
+ return tensor
+ raise ValueError(
+ f"Expected an image object, but got {type(tensor)} instead."
)
- 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__"]:
+def type_sign(value: bytes, label: str) -> bytes:
+ # Appending all strings with a key disambiguates it from other types. e.g.
+ # when the string value is the same as a float pack, or is the literal
+ # ":none". If our content strings take the form: integrity + delimiter then
+ # these types of collisions become very hard.
+ #
+ # Note that this does not fully protect against cache poisoning, as an
+ # attacker can override python internals to provide a matched hash. A key
+ # signed cache result is the only way to properly protect against this.
+ #
+ # Additionally, (less meaningful, but still possible)- a byte collision can
+ # be manufactured by choosing data so long that the length of the data acts
+ # as the data injection.
+ #
+ # TODO: Benchmark something like `sha1 (integrity) + delimiter`, this
+ # method is chosen because it was assumed to be fast, but might be slow
+ # with a copy of large data.
+ return b"".join([value, bytes(len(value)), bytes(":" + label, "utf-8")])
+
+
+def iterable_sign(value: Iterable[Any], label: str) -> bytes:
+ values = list(value)
+ return b"".join(
+ [b"".join(values), bytes(len(values)), bytes(":" + label, "utf-8")]
+ )
+
+
+def primitive_to_bytes(value: Any) -> bytes:
+ if value is None:
+ return b":none"
+ if isinstance(value, str):
+ return type_sign(bytes(f"{value}", "utf-8"), "str")
+ if isinstance(value, float):
+ return type_sign(struct.pack("d", value), "float")
+ if isinstance(value, int):
+ return type_sign(struct.pack("q", value), "int")
+ if isinstance(value, tuple):
+ return iterable_sign(map(primitive_to_bytes, value), "tuple")
+ return type_sign(bytes(value), "bytes")
+
+
+def common_container_to_bytes(value: Any) -> bytes:
+ visited: dict[int, int] = {}
+
+ def recurse_container(value: Any) -> bytes:
+ if id(value) in visited:
+ return type_sign(bytes(visited[id(value)]), "id")
+ if isinstance(value, dict):
+ visited[id(value)] = len(visited)
+ return iterable_sign(
+ map(recurse_container, sorted(value.items())), "dict"
+ )
+ if isinstance(value, list):
+ visited[id(value)] = len(visited)
+ return iterable_sign(map(recurse_container, value), "list")
+ if isinstance(value, set):
+ visited[id(value)] = len(visited)
+ return iterable_sign(map(recurse_container, sorted(value)), "set")
+ # Tuple may be only data primitive, not fully primitive.
+ if isinstance(value, tuple):
+ return iterable_sign(map(recurse_container, value), "tuple")
+
+ if is_primitive(value):
+ return primitive_to_bytes(value)
+ return data_to_buffer(value)
+
+ return recurse_container(value)
+
+
+def data_to_buffer(data: Tensor) -> bytes:
+ data = standardize_tensor(data)
+ # From joblib.hashing
+ if data.shape == ():
+ # 0d arrays need to be flattened because viewing them as bytes
+ # raises a ValueError exception.
+ data_c_contiguous = data.flatten()
+ elif data.flags.c_contiguous:
+ data_c_contiguous = data
+ elif data.flags.f_contiguous:
+ data_c_contiguous = data.T
+ else:
+ # Cater for non-single-segment arrays, this creates a copy, and thus
+ # alleviates this issue. Note: There might be a more efficient way of
+ # doing this, check for joblib updates.
+ data_c_contiguous = data.flatten()
+ return type_sign(memoryview(data_c_contiguous.view("uint8")), "data")
+
+
+class BlockHasher:
+ def __init__(
+ self,
+ module: ast.Module,
+ graph: DirectedGraph,
+ cell_id: CellId_t,
+ scope: dict[str, Any],
+ *,
+ context: Optional[ast.Module] = None,
+ pin_modules: bool = False,
+ hash_type: str = DEFAULT_HASH,
+ content_hash: bool = True,
+ ) -> None:
+ """Hash the context of the module, and return a cache object.
+
+ Hashing occurs 3 combined methods, content addressed, and execution
+ path:
+
+ 1) "Pure" hashing is used when a block has no references. The hash is
+ computed from the code itself.
+
+ 2) "Content Addressed" hashing is used when all references are known
+ and are shown to be primitive types (like a "pure" function).
+
+ 3) "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. NB. The ContextExecutionPath is an extended case of
+ ExecutionPath hashing, just utilizing additional context.
+
+ Args:
+ - module: The code content to create a hash for (e.g.
+ for persistent_cache, the body of the `With` statement).
+ - graph: The dataflow graph of the notebook.
+ - cell_id: The cell id attached to the module.
+ - scope: 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.
+ - 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.
+
+ """
+
+ # 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)
+
+ self.graph = graph
+ self.cell_id = cell_id
+ self.pin_modules = pin_modules
+ self.fn_cache: FN_CACHE_TYPE = {}
+
+ # Empty name, so we can match and fill in cell context on load.
+ self.visitor = ScopedVisitor("", ignore_local=True)
+ self.visitor.visit(module)
+ # Determine immediate references
+ 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(
+ 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)
+ # 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.
+
+ # Attempt content hash on the cell references
+ if refs and content_hash:
+ 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
+ )
+ self.stateful_refs |= stateful_refs
+
+ # If there are still unaccounted for references, then fallback on
+ # execution
+ # hashing.
+ if refs:
+ cache_type = "ExecutionPath"
+ # Execution path hash
+ refs = self.hash_and_dequeue_execution_refs(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)
+
+ # 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("=")
+ )
+
+ def extract_ref_state_and_normalize_scope(
+ self,
+ refs: set[Name],
+ scope: dict[str, Any],
+ ctx: Optional[RuntimeContext] = None,
+ ) -> tuple[set[Name], set[Name]]:
+ """
+ Preprocess the scope and references, and extract state references.
+
+ This method performs the following operations:
+ 1. Removes references that are not present in the scope.
+ 2. Identifies and returns stateful references.
+ 3. Adjusts the scope, replacing UI elements and state setters with
+ their corresponding values.
+
+ Args:
+ refs: A set of reference names.
+ scope: A dictionary representing the current scope.
+ ctx: An optional runtime context for stateful lookup.
+
+ Returns:
+ tuple of:
+ - The filtered references.
+ - The stateful references.
+ """
+ refs = set(refs)
+ stateful_refs = set()
+
+ # State Setters that are not directly consumed, are not needed.
+ for ref in self.visitor.refs:
+ # If the setter is consumed, let the hash be tied to the state
+ # value.
+ if ref in scope and isinstance(scope[ref], SetFunctor):
+ stateful_refs.add(ref)
+ scope[ref] = scope[ref]._state
+
+ for ref in set(refs):
+ if ref in scope.get("__builtins__", ()):
+ 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
+
+ # 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()
+
+ # 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
+ # If the UI is directly consumed, then hold on to the reference
+ # for proper cache update.
+ stateful_refs.add(ref)
+ return refs, stateful_refs
+
+ def hash_and_dequeue_content_refs(
+ self, refs: set[Name], scope: dict[Name, Any]
+ ) -> set[Name]:
+ """Use hashable references to update the hash object and dequeue them.
+
+ NB. "Hashable" types are primitives, data primitives, and pure
+ functions. With modules being "hashed" by version number, or ignored.
+
+ Args:
+ refs: A set of reference names unaccounted for.
+ scope: A dictionary representing the current scope.
+
+ Returns a filtered list of remaining references that were not utilized
+ in updating the hash.
+ """
+ refs = set(refs)
+ # Content addressed hash is valid if every reference is accounted for
+ # and can be shown to be a primitive value.
+ imports = self.graph.get_imports()
+ for local_ref in sorted(refs):
+ ref = if_local_then_mangle(local_ref, self.cell_id)
+ if ref in imports:
+ # TODO: There may be a way to tie this in with module watching.
+ # e.g. module watcher could mutate the version number based
+ # last updated timestamp.
+ version = ""
+ if self.pin_modules:
+ module = sys.modules[imports[ref].namespace]
+ version = getattr(module, "__version__", "")
+ self.hash_alg.update(
+ f"module:{ref}:{version}".encode("utf8")
+ )
+ # 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)
+ continue
+ if local_ref not in scope:
+ # ref is somehow not defined, because of execution path
+ # so do not utilize content hash in this case.
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")
+ value = scope[local_ref]
+
+ if is_primitive(value):
+ self.hash_alg.update(primitive_to_bytes(value))
+ elif is_data_primitive(value):
+ self.hash_alg.update(data_to_buffer(value))
+ elif is_data_primitive_container(value):
+ self.hash_alg.update(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)
+ )
+ # An external module variable is assumed to be pure, with module
+ # pinning being the mechanism for invalidation.
+ elif getattr(value, "__module__", "__main__") == "__main__":
+ continue
+ # Fall through means that the references should be dequeued.
+ refs.remove(local_ref)
+ return refs
+
+ def hash_and_dequeue_stateful_content_refs(
+ self, refs: set[Name], scope: dict[str, Any], ctx: RuntimeContext
+ ) -> tuple[set[Name], set[Name]]:
+ """Determines and uses stateful references that impact the code block.
+
+ Args:
+ refs: A set of reference names.
+ scope: A dictionary representing the current scope.
+ ctx: Runtime context for stateful lookup.
+
+ Returns:
+ tuple of:
+ - The updated references.
+ - 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(
+ refs, inclusive=False
+ )
+ # Filter for relevant stateful cases.
+ refs |= set(
+ filter(
+ lambda ref: (
+ ctx.state_registry.lookup(ref) is not None
+ or ctx.ui_element_registry.lookup(ref) is not None
+ ),
+ transitive_state_refs,
+ )
+ )
+ # Need to run extract again for the expanded ref set.
+ 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
+
+ def hash_and_dequeue_execution_refs(self, refs: set[Name]) -> set[Name]:
+ """Determines and uses the hash of refs' cells to update the hash.
+
+ Args:
+ refs: List of references to account for in cell lookup.
+
+ Returns a list of references that were not utilized in updating the
+ 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.
+ """
+ refs = set(refs)
+ # Execution path works by just analyzing the input cells to hash.
+ ancestors = self.graph.ancestors(self.cell_id)
+ # Prune to only the ancestors that are tied to the references.
+ ref_cells = set().union(
+ *[self.graph.definitions.get(ref, set()) for ref in refs]
+ )
+ to_hash = ancestors & ref_cells
+ for ancestor_id in sorted(to_hash):
+ cell_impl = self.graph.cells[ancestor_id]
+ self.hash_alg.update(hash_cell_impl(cell_impl, self.hash_alg.name))
+ for ref in cell_impl.defs:
+ # Look for both, since mangle reference depends on the context
+ # of the definition.
+ if ref in refs:
+ refs.remove(ref)
+ unmangled_ref, _ = unmangle_local(ref)
+ if unmangled_ref in refs:
+ refs.remove(unmangled_ref)
+ return refs
+
+ def hash_and_verify_context_refs(
+ self, refs: set[Name], context: Optional[ast.Module]
+ ) -> None:
+ """Utilizes the provided context to update the hash with sanity check.
+
+ If there are remaining references, they must be part of the provided
+ context. This ensures this is the case, and updates the hash.
+
+ Args:
+ refs: List of references to account for in cell lookup.
+ 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.
+ """
+ # 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."
+ "This is unexpected, please report this issue to "
+ "https://github.com/marimo-team/marimo/issues"
+ )
+
+ ref_cells = set().union(
+ *[self.graph.definitions.get(ref, set()) for ref in refs]
+ )
+ ref_cells |= set(
+ [
+ cell
+ for ref in refs
+ if (cell := get_cell_from_local(ref, self.cell_id))
+ ]
+ )
+ assert len(ref_cells) == 1, (
+ "Inconsistent references, cannot determine execution path. "
+ f"Got {ref_cells} expected set({self.cell_id}). "
+ "This is unexpected, please report this issue to "
+ "https://github.com/marimo-team/marimo/issues"
+ )
+ assert ref_cells == {self.cell_id}, (
+ "Unexpected execution cell residual "
+ f"{ref_cells.pop()} expected {self.cell_id}."
+ "This is unexpected, please report this issue to "
+ "https://github.com/marimo-team/marimo/issues"
+ )
+ self.hash_alg.update(hash_raw_module(context, self.hash_alg.name))
+ # refs have been accounted for at this point. Nothing to return
def cache_attempt_from_hash(
module: ast.Module,
graph: DirectedGraph,
cell_id: CellId_t,
- defs: dict[str, Any],
+ scope: dict[str, Any],
*,
context: Optional[ast.Module] = None,
+ pin_modules: bool = False,
+ hash_type: str = DEFAULT_HASH,
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.
+ """Hash a code block with context from the same cell, and return 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("=")
+
+ hasher = BlockHasher(
+ module=module,
+ graph=graph,
+ cell_id=cell_id,
+ scope=scope,
+ context=context,
+ pin_modules=pin_modules,
+ hash_type=hash_type,
)
- return loader.cache_attempt(visitor.defs, hashed_context, cache_type)
+ return loader.cache_attempt(
+ hasher.defs,
+ hasher.hash,
+ hasher.stateful_refs,
+ hasher.cache_type,
+ )
diff --git a/marimo/_save/loaders.py b/marimo/_save/loaders.py
index 31ca7e23d3..b516561d57 100644
--- a/marimo/_save/loaders.py
+++ b/marimo/_save/loaders.py
@@ -43,17 +43,35 @@ class Loader(ABC):
return self.save_path / f"{prefix}{hashed_context}"
def cache_attempt(
- self, defs: set[Name], hashed_context: str, cache_type: CacheType
+ self,
+ defs: set[Name],
+ hashed_context: str,
+ stateful_refs: set[Name],
+ 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
+ {d: None for d in defs},
+ hashed_context,
+ stateful_refs,
+ 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)
+ assert set(defs | stateful_refs) == set(
+ loaded.defs
+ ), INCONSISTENT_CACHE_BOILER_PLATE
+ return Cache(
+ loaded.defs,
+ hashed_context,
+ stateful_refs,
+ cache_type,
+ True,
+ loaded.meta,
+ )
@abstractmethod
def cache_hit(self, hashed_context: str, cache_type: CacheType) -> bool:
@@ -83,7 +101,8 @@ class PickleLoader(Loader):
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))
+ 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(
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index a6a5443f58..86d1c0502c 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -5,6 +5,7 @@ import ast
import io
import sys
import traceback
+from sys import maxsize as MAXINT
from typing import (
TYPE_CHECKING,
Any,
@@ -16,7 +17,7 @@ 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._save.cache import Cache, contextual_defs
+from marimo._save.cache import Cache, CacheException
from marimo._save.hash import cache_attempt_from_hash
from marimo._save.loaders import Loader, PickleLoader
@@ -41,11 +42,6 @@ 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.
@@ -66,6 +62,7 @@ class persistent_cache(object):
*,
save_path: str = "outputs",
name: str,
+ pin_modules: bool = False,
_loader: Optional[Loader] = None,
) -> None:
self.name = name
@@ -79,6 +76,9 @@ class persistent_cache(object):
self._entered_trace = False
self._old_trace: Optional[TraceFunction] = None
self._frame: Optional[FrameType] = None
+ self._body_start: int = MAXINT
+ # TODO: Consider having a user level setting.
+ self.pin_modules = pin_modules
def __enter__(self) -> Self:
sys.settrace(lambda *_args, **_keys: None)
@@ -87,10 +87,10 @@ class persistent_cache(object):
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
+ frame.f_trace = self._trace
return self
- def trace(
+ def _trace(
self, with_frame: FrameType, _event: str, _arg: Any
) -> Union[TraceFunction | None]:
# General flow is as follows:
@@ -103,20 +103,19 @@ class persistent_cache(object):
# 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.
+ # This behavior arguably a python bug.
+ # Note the behavior does subtly change in 3.14, but will still be
+ # captured by this check.
if self._cache and self._cache.hit:
- raise SkipWithBlock()
+ if with_frame.f_lineno >= self._body_start:
+ raise SkipWithBlock()
+
+ stack = traceback.extract_stack()
# This only executes on the first line of code in the block. If the
# cache is hit, the block terminates early with a SkipWithBlock
@@ -132,10 +131,7 @@ class persistent_cache(object):
f"{UNEXPECTED_FAILURE_BOILERPLATE}",
)
graph = ctx.graph
- cell_id = (
- ctx.execution_context.cell_id
- or ctx.execution_context.cell_id
- )
+ cell_id = ctx.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]
)
@@ -147,15 +143,15 @@ class persistent_cache(object):
{**globals(), **with_frame.f_locals},
loader=self._loader,
context=pre_module,
+ pin_modules=self.pin_modules,
)
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.
+ # Raising on the first valid line, prevents a discrepancy where
+ # whitespace in `With`, changes behavior.
+ self._body_start = save_module.body[0].lineno
if self._cache and self._cache.hit:
- if lineno >= save_module.body[0].lineno:
+ if lineno >= self._body_start:
raise SkipWithBlock()
return self._old_trace
self._skipped = False
@@ -187,8 +183,7 @@ class persistent_cache(object):
# 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]
+ self._cache.restore(self._frame.f_locals)
# Return true to suppress the SkipWithBlock exception.
return True
@@ -205,8 +200,7 @@ class persistent_cache(object):
# 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]
+ self._cache.update(self._frame.f_locals)
try:
self._loader.save_cache(self._cache)
diff --git a/marimo/_utils/variables.py b/marimo/_utils/variables.py
index c97a71d742..e5be8e2dc4 100644
--- a/marimo/_utils/variables.py
+++ b/marimo/_utils/variables.py
@@ -2,24 +2,32 @@
from __future__ import annotations
import re
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from marimo._ast.cell import CellId_t
-def is_local_then_mangle(ref: str, cell_id: CellId_t) -> str:
+from collections import namedtuple
+
+UnmagledLocal = namedtuple("UnmagledLocal", "name cell")
+
+
+def if_local_then_mangle(ref: str, cell_id: CellId_t) -> str:
if is_local(ref):
- if ref.startswith("_cell"):
+ if is_mangled_local(ref):
return ref
return f"_cell_{cell_id}{ref}"
return ref
-def unmangle_local(name: str) -> tuple[str, str]:
- if not is_mangled_local(name):
- return name, ""
- return re.sub(r"^_cell_\w+_", "_", name), name.split("_")[2]
+def unmangle_local(name: str, cell_id: CellId_t = "") -> UnmagledLocal:
+ if not is_mangled_local(name, cell_id):
+ return UnmagledLocal(name, "")
+ private_prefix = r"^_cell_\w+?_"
+ if cell_id:
+ private_prefix = f"^_cell_{cell_id}_"
+ return UnmagledLocal(re.sub(private_prefix, "_", name), name.split("_")[2])
def is_mangled_local(name: str, cell_id: CellId_t = "") -> bool:
@@ -28,3 +36,10 @@ def is_mangled_local(name: str, cell_id: CellId_t = "") -> bool:
def is_local(name: str) -> bool:
return name == "__" or (name.startswith("_") and not name.startswith("__"))
+
+
+def get_cell_from_local(
+ name: str, cell_id: CellId_t = ""
+) -> Optional[CellId_t]:
+ local = unmangle_local(if_local_then_mangle(name, cell_id)).cell
+ return local if local else None
diff --git a/tests/_save/mocks.py b/tests/_save/mocks.py
index 7ab83dd491..0b99f3374b 100644
--- a/tests/_save/mocks.py
+++ b/tests/_save/mocks.py
@@ -12,6 +12,7 @@ class MockLoader(Loader):
name: str = "mock",
save_path: str = "",
data: Optional[Dict[str, Any]] = None,
+ stateful_refs: Optional[set[str]] = None,
) -> None:
self.name = name
self.save_path = save_path
@@ -19,13 +20,21 @@ class MockLoader(Loader):
self._cache_hit = data is not None
self._loaded = False
self._saved = False
+ self._stateful_refs = stateful_refs or set()
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)
+ return Cache(
+ self._data,
+ hashed_context,
+ self._stateful_refs,
+ 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
index c24968b259..0d7a9cc620 100644
--- a/tests/_save/test_cache.py
+++ b/tests/_save/test_cache.py
@@ -7,6 +7,7 @@ import textwrap
from marimo._ast.app import App
from marimo._runtime.requests import ExecutionRequest
from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
class TestScriptCache:
@@ -89,7 +90,9 @@ class TestAppCache:
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
- with persistent_cache(name="one") as cache:
+ with persistent_cache(
+ name="one", _loader=MockLoader()
+ ) as cache:
Y = 9
X = 10
Z = 3
@@ -157,7 +160,7 @@ class TestAppCache:
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
- with persistent_cache(name="one"):
+ with persistent_cache(name="one", _loader=MockLoader()):
# Comment
# whitespace
@@ -171,3 +174,180 @@ class TestAppCache:
assert k.errors == {}
assert k.globals["X"] == 1
assert k.globals["Y"] == 2
+
+
+class TestStateCache:
+ async def test_set_state_works_normally(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ create_class = """
+ class A:
+ def __eq__(self, other):
+ # shouldn't be triggered by marimo
+ import sys
+ sys.exit()
+ a = A()
+ """
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get(create_class),
+ exec_req.get("state, set_state = mo.state(None)"),
+ exec_req.get("x = state()"),
+ exec_req.get(
+ """
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(
+ name="cache", _loader=MockLoader()
+ ) as cache:
+ set_state(a)
+ """
+ ),
+ ]
+ )
+
+ assert id(k.globals["x"]) == id(k.globals["a"])
+ # Set as a def, because it is stateful
+ assert id(k.globals["cache"]._cache.defs["set_state"]) == id(
+ k.globals["a"]
+ )
+
+ async def test_set_state_hits_cache(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(7)"),
+ exec_req.get("rerun, set_rerun = mo.state(True)"),
+ exec_req.get("impure = []"),
+ exec_req.get("redo = rerun()"),
+ exec_req.get(
+ """
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(
+ name="cache", _loader=MockLoader(),
+ ) as cache:
+ set_state(9)
+
+ if redo:
+ set_rerun(False)
+ impure.append(cache._cache.hash)
+ """
+ ),
+ ]
+ )
+
+ # Should be hit because of rerun
+ assert len(k.globals["impure"]) == 2
+ assert k.globals["impure"][0] == k.globals["impure"][1]
+ assert k.globals["state"]() == 9
+
+ async def test_set_state_invalidates(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("impure = []; impure_value = []"),
+ exec_req.get("state, set_state = mo.state(0)"),
+ exec_req.get("x = state()"),
+ exec_req.get(
+ """
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(
+ name="cache", _loader=MockLoader()
+ ) as cache:
+ a = x + 1
+
+ if len(impure) < 4:
+ impure.append(cache._cache.hash)
+ impure_value.append(a)
+ set_state(a % 3)
+ """
+ ),
+ ]
+ )
+
+ assert len(k.globals["impure"]) == 4
+ assert len(set(k.globals["impure"])) == 3
+ assert k.globals["impure"][0] == k.globals["impure"][-1]
+
+ assert set(k.globals["impure_value"]) == {1, 2, 3}
+
+ assert k.globals["a"] == 2
+ assert k.globals["state"]() == 1
+
+ async def test_set_state_loads(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(11)"),
+ exec_req.get(
+ """
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ with persistent_cache(
+ name="cache",
+ _loader=MockLoader(
+ data={"set_state": 7, "a": 9},
+ stateful_refs={"set_state"},
+ )
+ ) as cache:
+ # Ensure the block is never hit
+ raise Exception()
+ a = 1
+ set_state(1)
+ """
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages
+
+ assert k.globals["a"] == 9
+ assert k.globals["state"]() == 7
+
+
+class TestUICache:
+ async def test_ui_loads(
+ 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
+
+ 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)
+
+ """
+ ),
+ ]
+ )
+
+ assert not k.stderr.messages
+
+ assert k.globals["slider"].value == 7
+ assert k.globals["a"] == 9
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index 7cab27a483..2cb6cdea13 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -2,12 +2,33 @@
from __future__ import annotations
+from typing import Any
+
import pytest
from marimo._ast.app import App
+from marimo._dependencies.dependencies import DependencyManager
class TestHash:
+ @staticmethod
+ def test_pure_hash() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @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 = [1, 2, 3]
+ Z = len(Y)
+ assert cache._cache.cache_type == "Pure"
+ return Y, Z
+
+ app.run()
+
@staticmethod
def test_content_hash() -> None:
app = App()
@@ -18,10 +39,11 @@ class TestHash:
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
+ a = 1
with persistent_cache(name="one", _loader=MockLoader()) as cache:
- Y = 8
+ Y = a
assert cache._cache.cache_type == "ContentAddressed"
- return Y
+ return (Y,)
app.run()
@@ -35,26 +57,24 @@ class TestHash:
app._anonymous_file = True
@app.cell
- def load() -> tuple[int]:
+ def load() -> tuple[Any]:
from marimo._save.save import persistent_cache
from tests._save.mocks import MockLoader
- expected_hash = "vi8ruEJL5Wja4sNnDwJZV8b0FGEOHOn_LOJY8RG51W4"
+ expected_hash = "rzWe8aalExwCRLmrdG0NkCp0QbSupaZdiimloFs9SKw"
return expected_hash, persistent_cache, MockLoader
@app.cell
- def one(expected_hash, persistent_cache, MockLoader) -> tuple[int]:
+ def one(expected_hash, persistent_cache, MockLoader) -> None:
_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
+ assert _cache._cache.hash == expected_hash, _cache._cache.hash
@app.cell
def two(expected_hash, persistent_cache, MockLoader) -> tuple[int]:
@@ -68,12 +88,11 @@ class TestHash:
# More Comments
_X = 10 + _a
assert _X == 7
- print(_cache._cache.hash)
assert _cache._cache.cache_type == "ContentAddressed"
- assert _cache._cache.hash == expected_hash
+ assert _cache._cache.hash == expected_hash, _cache._cache.hash
# and a post block difference
Z = 11
- return Z
+ return (Z,)
app.run()
@@ -91,8 +110,8 @@ class TestHash:
with persistent_cache(name="one", _loader=MockLoader()) as cache:
Y = 8 + len(non_primitive)
- assert cache._cache.cache_type == "ExecutionPath"
- return Y
+ assert cache._cache.cache_type == "ContextExecutionPath"
+ return (Y,)
app.run()
@@ -114,22 +133,18 @@ class TestHash:
@app.cell
def one(persistent_cache, MockLoader, shared) -> tuple[int]:
- _a = [1]
+ _a = [1, object()]
with persistent_cache(
name="one", _loader=MockLoader(data={"_X": 7})
) as _cache:
- _X = (
- 10
- + _a[0] # Comment
- - len(shared)
- )
+ _X = 10 + _a[0] - len(shared) # Comment
assert _X == 7
- print(_cache._cache.hash)
+ # Cannot be reused/ shared, because it will change the hash.
assert (
_cache._cache.hash
- == "84XqUk17Yiuz_jlAVbtdCOvWHrUFj-YApa7-0rB8Kl8"
- )
- assert _cache._cache.cache_type == "ExecutionPath"
+ == "ZOoW-62h9ubJQ92u9h1UWydCsuwtXafS2tmDUcH8dLc"
+ ), _cache._cache.hash
+ assert _cache._cache.cache_type == "ContextExecutionPath"
return
@app.cell
@@ -137,8 +152,8 @@ class TestHash:
# The same as cell one, but with this comment
_a = [
1, # Comment
+ object(),
]
-
# Some white space
with persistent_cache(
name="one", _loader=MockLoader(data={"_X": 7})
@@ -146,14 +161,246 @@ class TestHash:
# 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"
+ == "ZOoW-62h9ubJQ92u9h1UWydCsuwtXafS2tmDUcH8dLc"
+ ), _cache._cache.hash
+ assert _cache._cache.cache_type == "ContextExecutionPath"
# and a post block difference
Z = 11
- return Z
+ return (Z,)
+
+ app.run()
+
+ @staticmethod
+ def test_transitive_content_hash() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @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 = len(shared)
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ Y = 8 + _a
+ assert cache._cache.cache_type == "ContentAddressed"
+ return (Y,)
+
+ app.run()
+
+ @staticmethod
+ def test_function_ui_content_hash() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import marimo as mo
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ slider = mo.ui.slider(1, 10)
+
+ def shared() -> str:
+ return "x" * slider.value
+
+ return persistent_cache, MockLoader, shared, slider
+
+ @app.cell
+ def one(persistent_cache, MockLoader, shared, slider) -> tuple[Any]:
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ _Y = len(shared())
+ slider._update(7)
+ assert cache._cache.cache_type == "ExecutionPath"
+ return (cache,)
+
+ @app.cell
+ def two(persistent_cache, MockLoader, shared, cache) -> tuple[Any]:
+ with persistent_cache(name="two", _loader=MockLoader()) as cache2:
+ _Y = len(shared())
+ assert cache2._cache.cache_type == "ExecutionPath"
+ assert cache2._cache.hash != cache._cache.hash
+ return (cache2,)
+
+ app.run()
+
+ @staticmethod
+ def test_function_state_content_hash() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import marimo as mo
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ state, set_state = mo.state(0)
+
+ def shared(state) -> str:
+ return "x" * state()
+
+ return persistent_cache, MockLoader, shared, state, set_state
+
+ @app.cell
+ def one(
+ persistent_cache, MockLoader, shared, state, set_state
+ ) -> tuple[Any]:
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ _Y = len(shared(state))
+ set_state(1)
+ assert cache._cache.cache_type == "ContentAddressed"
+ return (cache,)
+
+ @app.cell
+ def two(
+ persistent_cache, MockLoader, shared, state, cache
+ ) -> tuple[Any]:
+ with persistent_cache(name="two", _loader=MockLoader()) as cache2:
+ _Y = len(shared(state))
+ assert cache2._cache.cache_type == "ContentAddressed"
+ assert cache2._cache.hash != cache._cache.hash
+ return (cache2,)
+
+ app.run()
+
+ @staticmethod
+ def test_transitive_execution_path_when_state_dependent() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import marimo as mo
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ state, set_state = mo.state(0)
+
+ def shared() -> str:
+ return "x" * state()
+
+ return persistent_cache, MockLoader, shared, state, set_state
+
+ @app.cell
+ def one(persistent_cache, MockLoader, shared, set_state) -> tuple[Any]:
+ with persistent_cache(name="one", _loader=MockLoader()) as cache:
+ _Y = len(shared())
+ set_state(1)
+ assert cache._cache.cache_type == "ExecutionPath"
+ return (cache,)
+
+ @app.cell
+ def two(persistent_cache, MockLoader, shared, cache) -> tuple[Any]:
+ with persistent_cache(name="two", _loader=MockLoader()) as cache2:
+ _Y = len(shared())
+ assert cache2._cache.cache_type == "ExecutionPath"
+ assert cache2._cache.hash != cache._cache.hash
+ return (cache2,)
+
+ app.run()
+
+ @staticmethod
+ def test_version_pinning() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import marimo as mo
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ mo.__version__ = "0.0.0"
+
+ return mo, persistent_cache, MockLoader
+
+ @app.cell
+ def one(mo, persistent_cache, MockLoader) -> tuple[Any]:
+ with persistent_cache(
+ name="one", _loader=MockLoader(), pin_modules=True
+ ) as cache:
+ _Y = len(mo.__version__)
+ mo.__version__ = "0.0.1"
+ assert cache._cache.cache_type == "ContentAddressed"
+ return (cache,)
+
+ @app.cell
+ def two(mo, persistent_cache, MockLoader, cache) -> tuple[Any]:
+ with persistent_cache(
+ name="two", _loader=MockLoader(), pin_modules=True
+ ) as cache2:
+ _Y = len(mo.__version__)
+ mo.__version__ = "0.0.0"
+ assert cache2._cache.cache_type == "ContentAddressed"
+ assert cache2._cache.hash != cache._cache.hash
+ return (cache2,)
+
+ app.run()
+
+
+class TestDataHash:
+ @staticmethod
+ @pytest.mark.skipif(
+ not DependencyManager.numpy.has(),
+ reason="optional dependencies not installed",
+ )
+ # Pin to a particular python version for differences in underlying library
+ # implementations / memory layout.
+ @pytest.mark.skipif(
+ "sys.version_info < (3, 11) or sys.version_info >= (3, 12)"
+ )
+ def test_numpy_hash() -> None:
+ app = App()
+ app._anonymous_file = True
+
+ @app.cell
+ def load() -> tuple[Any]:
+ import numpy as np
+
+ from marimo._save.save import persistent_cache
+ from tests._save.mocks import MockLoader
+
+ expected_hash = "MsiRwkuTRK94PyMbWFPVGgYtpz-TNWoQhE7X87FXK2o"
+ return MockLoader, persistent_cache, expected_hash, np
+
+ @app.cell
+ def one(MockLoader, persistent_cache, expected_hash, np) -> tuple[int]:
+ _a = np.ones((16, 16)) * 2
+ with persistent_cache(name="one", _loader=MockLoader()) as _cache:
+ _A = np.sum(_a)
+ one = _A
+
+ assert _cache._cache.cache_type == "ContentAddressed"
+ assert (
+ _cache._cache.hash == expected_hash
+ ), f"expected_hash != {_cache._cache.hash}"
+ return (one,)
+
+ @app.cell
+ def two(MockLoader, persistent_cache, expected_hash, np) -> tuple[int]:
+ _a = np.ones((16, 16)) + np.ones((16, 16))
+
+ with persistent_cache(name="two", _loader=MockLoader()) as _cache:
+ _A = np.sum(_a)
+ two = _A
+
+ assert _cache._cache.cache_type == "ContentAddressed"
+ assert (
+ _cache._cache.hash == expected_hash
+ ), f"expected_hash != {_cache._cache.hash}"
+ return (two,)
+
+ @app.cell
+ def three(one, two) -> None:
+ assert one == two
+ assert one == 512
app.run()