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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: mo.cache returning stale values (#8411)
ffmiruz2940d158d196
diff --git a/marimo/_ast/transformers.py b/marimo/_ast/transformers.pyindex a573de5d09..e3adef575d 100644--- a/marimo/_ast/transformers.py+++ b/marimo/_ast/transformers.py@@ -467,11 +467,43 @@ class DeprivateVisitor(ast.NodeTransformer):class RemoveReturns(ast.NodeTransformer):+ def __init__(self):+ self._has_name = False++ def visit_Name(self, node: ast.Name) -> ast.Name:+ self._has_name = True+ return node+# NB: Won't work for generators since not replacing Yield.# Note that functools caches the generator, which is then dequeue'd,# so in that sense, it doesn't work either.- def visit_Return(self, node: ast.Return) -> ast.Expr:- expr = ast.Expr(value=cast(ast.expr, node.value))- expr.lineno = node.lineno- expr.col_offset = node.col_offset- return expr+ def visit_Return(self, node: ast.Return) -> ast.Expr | ast.Assign:+ value = node.value or ast.Constant(value=None)++ self._has_name = False+ super().generic_visit(node)+ # TODO(dmadisetti): consider removing on breaking cache update to+ # prevent collisions.+ # e.g. missed case:+ #+ # def f(): foo+ # vs+ # def f(): return foo+ if self._has_name:+ expr = ast.Expr(value=cast(ast.expr, value))+ expr.lineno = node.lineno+ expr.col_offset = node.col_offset+ return expr++ # Convert "return expr" to "* = expr" to preserve constant values+ # in bytecode. "*" is not a valid identifier so it cannot collide.+ target = ast.Name(id="*", ctx=ast.Store())+ target.lineno = node.lineno+ target.col_offset = node.col_offset+ assign = ast.Assign(+ targets=[target],+ value=cast(ast.expr, value),+ )+ assign.lineno = node.lineno+ assign.col_offset = node.col_offset+ return assigndiff --git a/tests/_ast/test_transformers.py b/tests/_ast/test_transformers.pyindex c26cdc209f..764430cf53 100644--- a/tests/_ast/test_transformers.py+++ b/tests/_ast/test_transformers.py@@ -382,6 +382,86 @@ def test_func():) # The value should still be there as an expression+class TestRemoveReturnsBareName:+ """return <Name> should become an Expr (the name is already captured)."""++ def test_return_name(self) -> None:+ tree = ast.parse("x = 1\nreturn x")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "return" not in code+ assert "x = 1" in code+++class TestRemoveReturnsConstant:+ """return <constant> must be preserved in bytecode (regression #8364)."""++ def test_return_int(self) -> None:+ tree = ast.parse("return 42")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "* = 42" in code++ def test_return_constant_expr(self) -> None:+ """return 11 + 19 — no Name, so must preserve via assignment."""+ tree = ast.parse("return 11 + 19")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "* = " in code+ assert "11" in code+ assert "19" in code+++class TestRemoveReturnsPureLambda:+ """return (lambda: <const>) has no Name — must preserve via assignment."""++ def test_return_pure_lambda(self) -> None:+ tree = ast.parse("return (lambda: 1)")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "* = " in code+ assert "lambda" in code++ def test_return_lambda_with_name(self) -> None:+ """return (lambda: x) — the lambda body references a Name."""+ tree = ast.parse("return (lambda: x)")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "return" not in code+ assert "x" in code+++class TestRemoveReturnsExprWithName:+ """return <expr containing Name> should become an Expr."""++ def test_return_binop_with_name(self) -> None:+ tree = ast.parse("return x + 1")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "return" not in code+ assert "x" in code++ def test_return_call(self) -> None:+ """return fn(x) — Call with Name args."""+ tree = ast.parse("return fn(x)")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "return" not in code+ assert "fn" in code+ assert "x" in code+++class TestRemoveReturnsBareReturn:+ """A bare `return` (no value) should not crash."""++ def test_bare_return(self) -> None:+ tree = ast.parse("return")+ result = RemoveReturns().visit(tree)+ code = ast.unparse(result)+ assert "return" not in code+ assert "* = None" in code++def test_extract_with_block_simple() -> None:"""Test ExtractWithBlock with a simple with statement."""code = """diff --git a/tests/_save/test_cache_invalidation.py b/tests/_save/test_cache_invalidation.pynew file mode 100644index 0000000000..da0ab0935e--- /dev/null+++ b/tests/_save/test_cache_invalidation.py@@ -0,0 +1,165 @@+# Copyright 2026 Marimo. All rights reserved.+"""Tests for cache invalidation when function body changes."""++from __future__ import annotations++import textwrap++from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++class TestCacheInvalidation:+ async def test_numeric_return_invalidation(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ """@mo.cache with numeric return types must invalidate on body change."""+ # First run: return 11 + 19 = 30+ await k.run(+ [+ exec_req.get_with_id(+ cell_id="0",+ code=textwrap.dedent("""+ import marimo as mo++ @mo.cache+ def query():+ return 11 + 19++ result = query()+ """),+ ),+ ]+ )++ assert k.globals["result"] == 30+ first_hash = k.globals["query"]._last_hash++ # Second run: return 5 + 3 = 8 (same cell, different code)+ await k.run(+ [+ exec_req.get_with_id(+ cell_id="0",+ code=textwrap.dedent("""+ import marimo as mo++ @mo.cache+ def query():+ return 5 + 3++ result = query()+ """),+ ),+ ]+ )++ second_hash = k.globals["query"]._last_hash++ # Hashes should be different+ assert first_hash != second_hash, (+ "Hash should change when function body changes"+ )+ # Should get 8, not stale 30+ assert k.globals["result"] == 8, (+ f"Expected 8, got {k.globals['result']} (stale cache)"+ )++ async def test_string_return_invalidation(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ """@mo.cache with string return types must invalidate on body change."""+ # First run+ await k.run(+ [+ exec_req.get_with_id(+ cell_id="0",+ code=textwrap.dedent("""+ import marimo as mo++ @mo.cache+ def query():+ return "hello"++ result = query()+ """),+ ),+ ]+ )++ assert k.globals["result"] == "hello"+ first_hash = k.globals["query"]._last_hash++ # Second run: different function body+ await k.run(+ [+ exec_req.get_with_id(+ cell_id="0",+ code=textwrap.dedent("""+ import marimo as mo++ @mo.cache+ def query():+ return "world"++ result = query()+ """),+ ),+ ]+ )++ second_hash = k.globals["query"]._last_hash++ # Hashes should be different+ assert first_hash != second_hash, (+ "Hash should change when function body changes"+ )+ assert k.globals["result"] == "world", (+ f"Expected 'world', got {k.globals['result']} (stale cache)"+ )++ async def test_float_return_invalidation(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ """@mo.cache with float return types must invalidate on body change."""+ # First run: return 1.5 + 2.5 = 4.0+ await k.run(+ [+ exec_req.get_with_id(+ cell_id="0",+ code=textwrap.dedent("""+ import marimo as mo++ @mo.cache+ def query():+ return 1.5 + 2.5++ result = query()+ """),+ ),+ ]+ )++ assert k.globals["result"] == 4.0++ # Second run: return 0.1 + 0.2 ≈ 0.3+ await k.run(+ [+ exec_req.get_with_id(+ cell_id="0",+ code=textwrap.dedent("""+ import marimo as mo++ @mo.cache+ def query():+ return 0.1 + 0.2++ result = query()+ """),+ ),+ ]+ )++ # Should get approximately 0.3, not stale 4.0+ assert abs(k.globals["result"] - 0.3) < 0.0001, (+ f"Expected ~0.3, got {k.globals['result']} (stale cache)"+ )diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex de9f3bb069..c77bfcd1ba 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -2284,6 +2284,61 @@ va_hits = varargs.hits)+def _hash_fn(fn: object) -> bytes:+ """Run the full get_hashable_ast -> compile -> hash pipeline."""+ from marimo._ast.transformers import get_hashable_ast+ from marimo._save.hash import hash_raw_module++ assert callable(fn)+ return hash_raw_module(get_hashable_ast(fn))+++class TestRemoveReturnsBytecode:+ """Bytecode-level tests for RemoveReturns (regression #8364)."""++ def test_different_name_exprs_different_hash(self) -> None:+ """Changing the returned expression must change the hash."""++ def fn_add(x: int, y: int) -> int:+ return x + y++ def fn_sub(x: int, y: int) -> int:+ return x - y++ assert _hash_fn(fn_add) != _hash_fn(fn_sub)++ def test_different_constants_different_hash(self) -> None:+ """Different numeric returns must hash differently."""++ def fn_a() -> int:+ return 11 + 19++ def fn_b() -> int:+ return 11 + 29++ assert _hash_fn(fn_a) != _hash_fn(fn_b)++ def test_different_single_constants_different_hash(self) -> None:+ def fn_a() -> int:+ return 42++ def fn_b() -> int:+ return 99++ assert _hash_fn(fn_a) != _hash_fn(fn_b)++ def test_different_pure_lambdas_different_hash(self) -> None:+ """Pure lambdas with different bodies must hash differently."""++ def fn_a() -> object:+ return lambda: 1++ def fn_b() -> object:+ return lambda: 2++ assert _hash_fn(fn_a) != _hash_fn(fn_b)++def test_decorator_params_affect_hash() -> None:"""Verify that changing decorator parameters changes the function hash.