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.

fix: Issue side effects to invalidate cache blocks (#4848)

Dylan Madisetti0706f7a35d43
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 6c9fdce99d..51f16fb5d9 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -32,6 +32,7 @@ from marimo._runtime.context.kernel_context import KernelRuntimeContext
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._runtime.side_effect import SideEffect
from marimo._server.model import SessionMode
from marimo._sql.engines.duckdb import (
INTERNAL_DUCKDB_ENGINE,
@@ -243,6 +244,32 @@ def _store_state_reference(
)
+@kernel_tracer.start_as_current_span("issue_exception_side_effect")
+def _issue_exception_side_effect(
+ _cell: CellImpl,
+ _runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ ctx = get_context()
+ if run_result.exception is not None:
+ exception = run_result.exception
+ key = type(exception).__name__
+ traceback = getattr(exception, "__traceback__", None)
+ if traceback:
+ # Side effect hash is the exception name
+ # AND the instruction pointer.
+ # Side effect has to be relatively robust to code changes
+ # - Bars line number since comments should not effect
+ # - Bars stacktrace since file path should be agnostic
+ # Code content is already utilized in hash, and tb_lasti is the
+ # bytecode instruction pointer. So if the code is the same, then the
+ # difference can be captured by where in the evaluation the exception
+ # was raised.
+ key += f":{traceback.tb_lasti}"
+ # NB. This is on a cell level.
+ ctx.cell_lifecycle_registry.add(SideEffect(key))
+
+
@kernel_tracer.start_as_current_span("broadcast_outputs")
def _broadcast_outputs(
cell: CellImpl,
@@ -392,6 +419,7 @@ POST_EXECUTION_HOOKS: list[PostExecutionHookType] = [
_set_run_result_status,
_store_reference_to_output,
_store_state_reference,
+ _issue_exception_side_effect,
_broadcast_variables,
_broadcast_datasets,
_broadcast_data_source_connection,
diff --git a/marimo/_runtime/side_effect.py b/marimo/_runtime/side_effect.py
new file mode 100644
index 0000000000..14249a9cd4
--- /dev/null
+++ b/marimo/_runtime/side_effect.py
@@ -0,0 +1,37 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import hashlib
+from typing import TYPE_CHECKING
+
+from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
+
+if TYPE_CHECKING:
+ from marimo._runtime.context.types import RuntimeContext
+
+
+class SideEffect(CellLifecycleItem):
+ def __init__(self, key: str) -> None:
+ self._key = key
+
+ @property
+ def key(self) -> str:
+ assert self._key is not None
+ return self._key
+
+ @property
+ def hash(self) -> bytes:
+ """Hash the lookup to a consistent size."""
+ return hashlib.sha256(self._key.encode()).digest()
+
+ def create(self, context: RuntimeContext | None) -> None:
+ """NoOp for side effect.
+ Typically hook to expose the object to the context, but the existence of
+ the object is enough for side effect tracking.
+ """
+
+ def dispose(self, context: RuntimeContext, deletion: bool) -> bool: # noqa: ARG002
+ """Clean up and mark the object for deletion"""
+ # Side effects can always be disposed since they are just a cell level
+ # marker that some event has occurred.
+ return True
diff --git a/marimo/_save/hash.py b/marimo/_save/hash.py
index 47d3afc596..4419674b9e 100644
--- a/marimo/_save/hash.py
+++ b/marimo/_save/hash.py
@@ -28,6 +28,7 @@ from marimo._runtime.primitives import (
is_primitive,
is_pure_function,
)
+from marimo._runtime.side_effect import SideEffect
from marimo._runtime.state import SetFunctor, State
from marimo._save.cache import Cache, CacheType
from marimo._types.ids import CellId_t
@@ -422,6 +423,10 @@ class BlockHasher:
# execution hashing.
if refs:
cache_type = "ExecutionPath"
+ if ctx:
+ self.collect_and_hash_side_effects(
+ self.cells_from_refs(refs), ctx
+ )
refs = self.hash_and_dequeue_execution_refs(refs)
self.execution_refs -= refs | self.content_refs
@@ -432,6 +437,8 @@ class BlockHasher:
# provided context.
if refs:
cache_type = "ContextExecutionPath"
+ if ctx:
+ self.collect_and_hash_side_effects({self.cell_id}, ctx)
self.hash_and_verify_context_refs(refs, context)
self.context_refs -= refs | self.content_refs | self.execution_refs
@@ -817,15 +824,7 @@ class BlockHasher:
provided, as those references should be accounted for in that context.
"""
self._hash = None
-
- refs = set(refs)
- # Execution path works by just analyzing the input cells to hash.
- ancestors = self.graph.ancestors(self.cell_id)
- # 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
+ to_hash = self.cells_from_refs(refs)
for ancestor_id in to_hash:
cell_impl = self.graph.cells[ancestor_id]
for ref in cell_impl.defs:
@@ -893,6 +892,40 @@ class BlockHasher:
self.hash_alg.update(hash_raw_module(context, self.hash_alg.name))
# refs have been accounted for at this point. Nothing to return
+ def collect_and_hash_side_effects(
+ self, cell_ids: set[CellId_t], ctx: RuntimeContext
+ ) -> None:
+ """Collect side effects from the context.
+
+ Args:
+ cell_ids: A set of cell ids to collect side effects from.
+ ctx: The runtime context to use for collection.
+ """
+ side_effects = []
+ for cell_id in cell_ids:
+ if cell_id in ctx.cell_lifecycle_registry.registry:
+ registry = ctx.cell_lifecycle_registry.registry[cell_id]
+ side_effects.extend(
+ [
+ obj.hash
+ for obj in registry
+ if isinstance(obj, SideEffect)
+ ]
+ )
+
+ # Hash the side effects
+ self.hash_alg.update(b"".join(sorted(side_effects)))
+
+ def cells_from_refs(self, refs: set[Name]) -> set[CellId_t]:
+ 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]
+ )
+ return ancestors & ref_cells
+
def cache_attempt_from_hash(
module: ast.Module,
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index b143d49315..73fc21dfa6 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -30,6 +30,7 @@ from marimo._ast.transformers import (
from marimo._ast.variables import is_mangled_local, unmangle_local
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime.context import get_context
+from marimo._runtime.side_effect import SideEffect
from marimo._runtime.state import State
from marimo._save.cache import Cache, CacheException
from marimo._save.hash import (
@@ -93,6 +94,7 @@ class _cache_call:
self.hash_type = hash_type
self._frame_offset = frame_offset
self._loader_partial = loader_partial
+ self._last_hash: Optional[str] = None
if _fn is None:
self.fn = None
else:
@@ -193,9 +195,10 @@ class _cache_call:
arg_dict = {f"{ARG_PREFIX}{k}": v for (k, v) in zip(self._args, args)}
kwargs_copy = {f"{ARG_PREFIX}{k}": v for (k, v) in kwargs.items()}
# Capture the call case
+ ctx = get_context()
scope = {
**self.scope,
- **get_context().globals,
+ **ctx.globals,
**arg_dict,
**kwargs_copy,
}
@@ -209,14 +212,26 @@ class _cache_call:
as_fn=True,
)
- if attempt.hit:
- attempt.restore(scope)
- return attempt.meta["return"]
- response = self.fn(*args, **kwargs)
- # stateful variables may be global
- scope = {k: v for k, v in scope.items() if k in attempt.stateful_refs}
- attempt.update(scope, meta={"return": response})
- self.loader.save_cache(attempt)
+ failed = False
+ self._last_hash = attempt.hash
+ try:
+ if attempt.hit:
+ attempt.restore(scope)
+ return attempt.meta["return"]
+ response = self.fn(*args, **kwargs)
+ # stateful variables may be global
+ scope = {
+ k: v for k, v in scope.items() if k in attempt.stateful_refs
+ }
+ attempt.update(scope, meta={"return": response})
+ self.loader.save_cache(attempt)
+ except Exception as e:
+ failed = True
+ raise e
+ finally:
+ # NB. Exceptions raise their own side effects.
+ if not failed:
+ ctx.cell_lifecycle_registry.add(SideEffect(attempt.hash))
return response
@@ -302,6 +317,7 @@ class _cache_context(SkipContext):
# 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 >= self._body_start:
self.skip()
@@ -329,39 +345,53 @@ class _cache_context(SkipContext):
f"Unexpected block format {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
- self._cache.restore(self._frame.f_locals)
- # Return true to suppress the SkipWithBlock exception.
- return True
-
+ # Cache hit is acceptable, because SkipWithBlock is raised.
# NB: exception is a type.
- if exception:
+ if exception and (self._cache is None or not self._cache.hit):
if isinstance(instance, BaseException):
raise instance from CacheException("Failure during save.")
raise exception
- # Fill the cache object and save.
if self._cache is None or self._frame is None:
raise CacheException(
f"Cache was not correctly set {UNEXPECTED_FAILURE_BOILERPLATE}"
)
- self._cache.update(self._frame.f_locals)
+ failed = False
try:
- self._loader.save_cache(self._cache)
+ # Backfill the loaded values into global scope.
+ if self._cache.hit:
+ assert self._frame is not None, UNEXPECTED_FAILURE_BOILERPLATE
+ self._cache.restore(self._frame.f_locals)
+ # Return true to suppress the SkipWithBlock exception.
+ return True
+
+ # Fill the cache object and save.
+ self._cache.update(self._frame.f_locals)
+
+ 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())
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())
+ failed = True
+ raise e
+ finally:
+ if not failed:
+ # Conditional because pendantically, the side effect is on restore /
+ # save respectively, and exceptions should raise their own.
+ ctx = get_context()
+ ctx.cell_lifecycle_registry.add(SideEffect(self._cache.hash))
+
return False
diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.py
index db5f590388..0708d384ec 100644
--- a/tests/_save/test_hash.py
+++ b/tests/_save/test_hash.py
@@ -7,6 +7,8 @@ from typing import Any
import pytest
from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
class TestHash:
@@ -834,3 +836,310 @@ class TestDataHash:
)
assert _A == 28
return (two,)
+
+
+class TestSideEffects:
+ @staticmethod
+ async def test_side_effect_cache_different(
+ k: Kernel, exec_req: ExecReqProvider, tmp_path
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'
+ ),
+ exec_req.get("""
+ from tests._save.loaders.mocks import MockLoader
+ import marimo as mo
+ from pathlib import Path
+
+ state, set_state = mo.state(0)
+ hashes = []
+ """),
+ exec_req.get("""
+ with mo.cache("prim") as prim_cache:
+ non_primitive = [object(), len(hashes)]
+ state
+ """),
+ exec_req.get("""
+ with mo.persistent_cache("get_v", save_path=tmp_path_fixture) as v_cache:
+ v = non_primitive[1]
+ """),
+ ]
+ )
+ await k.run(
+ [
+ exec_req.get("""
+ if len(hashes) < 1:
+ assert non_primitive[1] == 0
+ set_state(1)
+ hashes.append((v_cache.cache_type, v_cache._cache.hash))
+ hashes.append((prim_cache.cache_type, prim_cache._cache.hash))
+ """),
+ ]
+ )
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
+ v = k.globals["v"]
+ hashes = k.globals["hashes"]
+ non_primitive = k.globals["non_primitive"]
+ assert len(hashes) == 4
+ assert hashes[1] != hashes[3]
+ assert hashes[0] != hashes[2]
+ assert non_primitive[1] == 2 == v
+
+ @staticmethod
+ async def test_side_effect_cache_context(
+ k: Kernel, exec_req: ExecReqProvider, tmp_path
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'
+ ),
+ exec_req.get("""
+ from tests._save.loaders.mocks import MockLoader
+ import marimo as mo
+ from pathlib import Path
+
+ state, set_state = mo.state(0)
+ hashes = []
+ """),
+ exec_req.get("""
+ with mo.cache("prim") as prim_cache:
+ non_primitive = [object(), len(hashes)]
+
+ with mo.persistent_cache("get_v", save_path=tmp_path_fixture) as v_cache:
+ v = non_primitive[1]
+ state
+ """),
+ ]
+ )
+ await k.run(
+ [
+ exec_req.get("""
+ if len(hashes) < 1:
+ assert non_primitive[1] == 0
+ set_state(1)
+ hashes.append((v_cache.cache_type, v_cache._cache.hash))
+ hashes.append((prim_cache.cache_type, prim_cache._cache.hash))
+ """),
+ ]
+ )
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
+ v = k.globals["v"]
+ hashes = k.globals["hashes"]
+ non_primitive = k.globals["non_primitive"]
+ assert len(hashes) == 4
+ assert hashes[1] != hashes[3]
+ assert hashes[0] != hashes[2]
+ assert non_primitive[1] == 2 == v
+
+ @staticmethod
+ async def test_side_effect_exception(
+ k: Kernel, exec_req: ExecReqProvider, tmp_path
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'
+ ),
+ exec_req.get("""
+ from tests._save.loaders.mocks import MockLoader
+ import marimo as mo
+ from pathlib import Path
+
+ state, set_state = mo.state(1)
+ hashes = []
+ """),
+ exec_req.get("""
+ non_primitive = [object(), 0]
+ ref = 1
+ 1 / state() # Throw an exception when 0
+ non_primitive = [object(), 1]
+ """),
+ ]
+ )
+ assert not k.stderr.messages, k.stderr
+ await k.run(
+ [
+ req := exec_req.get("""
+ with mo.persistent_cache("get_v", save_path=tmp_path_fixture) as v_cache:
+ v = non_primitive[1] + ref
+ """),
+ exec_req.get("""
+ if len(hashes) < 1:
+ set_state(0)
+ hashes.append((v_cache.cache_type, v_cache._cache.hash, v))
+ """),
+ ]
+ )
+ await k.run([req])
+
+ assert not k.stdout.messages, k.stdout
+ assert "ZeroDivisionError" in str(k.stderr), k.stderr
+
+ hashes = k.globals["hashes"]
+ non_primitive = k.globals["non_primitive"]
+
+ v = k.globals["v"]
+
+ assert len(hashes) == 2
+ assert non_primitive[1] == 0
+ assert v == 1
+ assert hashes[0] != hashes[1]
+
+ @staticmethod
+ async def test_side_effect_decorator_different(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("""
+ from tests._save.loaders.mocks import MockLoader
+ import marimo as mo
+ import weakref
+
+ state, set_state = mo.state(0)
+ hashes = []
+ """),
+ exec_req.get("""
+ @mo.cache
+ def prim_cache():
+ return [weakref.ref(object), len(hashes)]
+ non_primitive = prim_cache()
+ state
+ """),
+ exec_req.get("""
+ @mo.cache
+ def v_cache():
+ return non_primitive[1]
+ v = v_cache()
+ """),
+ ]
+ )
+ await k.run(
+ [
+ exec_req.get("""
+ if len(hashes) < 1:
+ assert non_primitive[1] == 0
+ set_state(1)
+ hashes.append(v_cache._last_hash)
+ hashes.append(prim_cache._last_hash)
+ """),
+ ]
+ )
+ assert not k.stdout.messages, k.stdout
+ assert not k.stderr.messages, k.stderr
+ v = k.globals["v"]
+ hashes = k.globals["hashes"]
+ non_primitive = k.globals["non_primitive"]
+ assert len(hashes) == 4
+ assert hashes[1] != hashes[3]
+ assert hashes[0] != hashes[2]
+ assert non_primitive[1] == 2 == v
+
+ @staticmethod
+ async def test_side_effect_decorator_context(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ # Actually doesn't test side effects, because there's
+ # no "context" level hash for functions. Placed here incase the
+ # functionality does change in the future.
+ await k.run(
+ [
+ exec_req.get("""
+ from tests._save.loaders.mocks import MockLoader
+ import marimo as mo
+ import weakref
+
+ state, set_state = mo.state(0)
+ hashes = []
+ """),
+ exec_req.get("""
+ @mo.cache
+ def prim_cache():
+ return [weakref.ref(object), len(hashes)]
+ non_primitive = prim_cache()
+
+ @mo.cache
+ def v_cache():
+ return non_primitive[1]
+ v = v_cache()
+ state
+ """),
+ ]
+ )
+ await k.run(
+ [
+ exec_req.get("""
+ if len(hashes) < 1:
+ assert non_primitive[1] == 0
+ set_state(1)
+ hashes.append(v_cache._last_hash)
+ hashes.append(prim_cache._last_hash)
+ """),
+ ]
+ )
+ assert not k.stdout.messages, k.stdout
+ assert k.stderr.messages, k.stderr
+ assert "Content addressed hash could not be utilized" in str(
+ k.stderr
+ ), k.stderr
+
+ @staticmethod
+ async def test_side_effect_decorator_exception(
+ k: Kernel, exec_req: ExecReqProvider, tmp_path
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ f'tmp_path_fixture = Path("{tmp_path.as_posix()}")'
+ ),
+ exec_req.get("""
+ from tests._save.loaders.mocks import MockLoader
+ import marimo as mo
+ from pathlib import Path
+
+ state, set_state = mo.state(1)
+ hashes = []
+ """),
+ exec_req.get("""
+ non_primitive = [object(), 0]
+ ref = 1
+ 1 / state() # Throw an exception when 0
+ non_primitive = [object(), 1]
+ """),
+ ]
+ )
+ assert not k.stderr.messages, k.stderr
+ await k.run(
+ [
+ req := exec_req.get("""
+ @mo.cache
+ def v_cache():
+ return non_primitive[1] + ref
+ v = v_cache()
+ """),
+ exec_req.get("""
+ if len(hashes) < 1:
+ set_state(0)
+ hashes.append((v_cache._last_hash, v))
+ """),
+ ]
+ )
+ await k.run([req])
+
+ assert not k.stdout.messages, k.stdout
+ assert "ZeroDivisionError" in str(k.stderr), k.stderr
+
+ hashes = k.globals["hashes"]
+ non_primitive = k.globals["non_primitive"]
+
+ v = k.globals["v"]
+
+ assert len(hashes) == 2
+ assert non_primitive[1] == 0
+ assert v == 1
+ assert hashes[0] != hashes[1]