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: allow caching on embedded apps (#5957)

Dylan Madisettib96bd39ae231
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 780327dab5..2c8cf939a9 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -21,9 +21,9 @@ from typing import (
cast,
overload,
)
-from uuid import uuid4
from marimo._ast.app_config import _AppConfig
+from marimo._ast.cell_id import external_prefix
from marimo._ast.variables import BUILTINS
from marimo._convert.converters import MarimoConvert
from marimo._schemas.serialization import (
@@ -236,7 +236,7 @@ class App:
# nested applications get a unique cell prefix to disambiguate
# their graph from other graphs
get_context()
- cell_prefix = str(uuid4())
+ cell_prefix = external_prefix()
else:
cell_prefix = ""
@@ -283,7 +283,7 @@ class App:
"""
app = App()
app._filename = self._filename
- app._cell_manager = CellManager(prefix=str(uuid4()))
+ app._cell_manager = CellManager(prefix=external_prefix())
for cell_id, code, name, config in zip(
self._cell_manager.cell_ids(),
self._cell_manager.codes(),
diff --git a/marimo/_ast/cell_id.py b/marimo/_ast/cell_id.py
new file mode 100644
index 0000000000..7cb7a77749
--- /dev/null
+++ b/marimo/_ast/cell_id.py
@@ -0,0 +1,60 @@
+# Copyright 2025 Marimo. All rights reserved.
+import random
+import string
+from uuid import UUID, uuid4
+
+from marimo._types.ids import CellId_t
+
+
+class CellIdGenerator:
+ def __init__(self, prefix: str = "") -> None:
+ self.prefix = prefix
+ self.random_seed = random.Random(42)
+ self.seen_ids: set[CellId_t] = set()
+
+ def create_cell_id(self) -> CellId_t:
+ """Create a new unique cell ID.
+
+ Returns:
+ CellId_t: A new cell ID consisting of the manager's prefix followed by 4 random letters.
+ """
+ attempts = 0
+ while attempts < 100:
+ # 4 random letters
+ _id = self.prefix + "".join(
+ self.random_seed.choices(string.ascii_letters, k=4)
+ )
+ if _id not in self.seen_ids:
+ self.seen_ids.add(CellId_t(_id))
+ return CellId_t(_id)
+ attempts += 1
+
+ raise ValueError(
+ f"Failed to create a unique cell ID after {attempts} attempts"
+ )
+
+
+def external_prefix() -> str:
+ """Get the prefix for external cell IDs."""
+ return str(uuid4())
+
+
+def is_external_cell_id(cell_id: CellId_t) -> bool:
+ """
+ Check if cell_id is external (cloned app).
+
+ Uses the fact that external cell IDs are UUIDs.
+
+ >>> is_external_cell_id("c9bf9e57-1685-4c89-bafb-ff5af830be8aHbol")
+ True
+ >>> is_external_cell_id("Hbol")
+ False
+ """
+
+ # UUIDs are 36 characters long, including hyphens
+ uuid_to_test = str(cell_id)[:36]
+ try:
+ uuid_obj = UUID(uuid_to_test, version=4)
+ except ValueError:
+ return False
+ return str(uuid_obj) == uuid_to_test
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index 281909c0b9..b6643f4beb 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -2,8 +2,6 @@
from __future__ import annotations
import os
-import random
-import string
import sys
from typing import (
TYPE_CHECKING,
@@ -19,6 +17,7 @@ else:
from marimo import _loggers
from marimo._ast.cell import Cell, CellConfig
+from marimo._ast.cell_id import CellIdGenerator
from marimo._ast.compiler import (
cell_factory,
context_cell_factory,
@@ -49,34 +48,6 @@ Obj: TypeAlias = "Cls | Fn[P, R]"
LOGGER = _loggers.marimo_logger()
-class CellIdGenerator:
- def __init__(self, prefix: str = "") -> None:
- self.prefix = prefix
- self.random_seed = random.Random(42)
- self.seen_ids: set[CellId_t] = set()
-
- def create_cell_id(self) -> CellId_t:
- """Create a new unique cell ID.
-
- Returns:
- CellId_t: A new cell ID consisting of the manager's prefix followed by 4 random letters.
- """
- attempts = 0
- while attempts < 100:
- # 4 random letters
- _id = self.prefix + "".join(
- self.random_seed.choices(string.ascii_letters, k=4)
- )
- if _id not in self.seen_ids:
- self.seen_ids.add(CellId_t(_id))
- return CellId_t(_id)
- attempts += 1
-
- raise ValueError(
- f"Failed to create a unique cell ID after {attempts} attempts"
- )
-
-
class CellManager:
"""A manager for cells in a marimo notebook.
diff --git a/marimo/_save/save.py b/marimo/_save/save.py
index 9279ef69a0..5952d0d1c1 100644
--- a/marimo/_save/save.py
+++ b/marimo/_save/save.py
@@ -22,6 +22,7 @@ from typing import (
overload,
)
+from marimo._ast.cell_id import is_external_cell_id
from marimo._ast.transformers import (
ARG_PREFIX,
CacheExtractWithBlock,
@@ -141,20 +142,24 @@ class _cache_call:
def _set_context(self, fn: Callable[..., Any]) -> None:
ctx = safe_get_context()
+
# If we are loaded from a module, then we have no context.
+ # Default to this case for typing.
+ self._external = True
+ cell_id = CellId_t("")
+ graph: Optional[DirectedGraph] = None
+ glbls = {}
if ctx and ctx.execution_context is not None:
- cell_id = (
+ maybe_cell_id = (
ctx.cell_id or ctx.execution_context.cell_id or CellId_t("")
)
- graph = ctx.graph
- glbls = ctx.globals
- self._external = False
- else:
- # We are in a loaded context.
- cell_id = CellId_t("")
- graph = None
- glbls = {}
- self._external = True
+ # If the cell ID is "external", that means it's not from the main
+ # graph but rather from an embedded graph.
+ self._external = is_external_cell_id(maybe_cell_id)
+ if not self._external:
+ graph = ctx.graph
+ glbls = ctx.globals
+ cell_id = maybe_cell_id
self.__wrapped__ = fn
sig = inspect.signature(fn)
diff --git a/tests/_save/external_decorators/app.py b/tests/_save/external_decorators/app.py
new file mode 100644
index 0000000000..4d999919a8
--- /dev/null
+++ b/tests/_save/external_decorators/app.py
@@ -0,0 +1,21 @@
+import marimo
+
+__generated_with = "0.14.16"
+app = marimo.App(width="medium")
+
+with app.setup:
+ import marimo as mo
+
+
+def _():
+ @mo.cache
+ def cache(x):
+ return x + 1
+
+ bar = cache(1)
+ return (bar, cache)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_save/test_external_decorators.py b/tests/_save/test_external_decorators.py
index 07a1f979f3..5bf178d304 100644
--- a/tests/_save/test_external_decorators.py
+++ b/tests/_save/test_external_decorators.py
@@ -228,3 +228,121 @@ class TestDecoratorTransitiveFns:
f"Expected different hashes for different impure dependencies, "
f"got {hash1} == {hash2}"
)
+
+
+class TestAsExternalApp:
+ @staticmethod
+ async def test_as_external_app(app) -> None:
+ with app.setup:
+ from tests._save.external_decorators.app import (
+ app as ex_app,
+ )
+
+ @app.cell
+ def _():
+ _, defs = ex_app.run()
+ assert defs["bar"] == 2
+ assert defs["cache"](1) == 2
+ return
+
+ @staticmethod
+ async def test_as_external_app_in_kernel(
+ lazy_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = lazy_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="setup",
+ code=textwrap.dedent(
+ """
+ from tests._save.external_decorators.app import (
+ app as ex_app,
+ )
+ """
+ ),
+ ),
+ exec_req.get(
+ """
+ _, defs = ex_app.run()
+ assert defs["bar"] == 2
+ assert defs["cache"](1) == 2
+ resolved = True
+ """
+ ),
+ ]
+ )
+ assert k.globals.get("resolved", False), k.stderr
+
+ @staticmethod
+ async def test_as_external_app_embedded(app) -> None:
+ with app.setup:
+ from tests._save.external_decorators.app import (
+ app as ex_app,
+ )
+
+ @app.cell
+ async def _():
+ r1 = await ex_app.embed()
+ assert r1.defs["bar"] == 2
+ assert r1.defs["cache"](1) == 2
+ return
+
+ @staticmethod
+ async def test_as_external_app_embedded_cloned(app) -> None:
+ with app.setup:
+ from tests._save.external_decorators.app import (
+ app as ex_app,
+ )
+
+ @app.cell
+ async def _():
+ r2 = await ex_app.clone().embed()
+ assert r2.defs["bar"] == 2
+ assert r2.defs["cache"](1) == 2
+ return
+
+ @staticmethod
+ async def test_as_external_app_embedded_in_kernel(
+ lazy_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = lazy_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="setup",
+ code=textwrap.dedent(
+ """
+ from tests._save.external_decorators.app import (
+ app as ex_app,
+ )
+ """
+ ),
+ ),
+ exec_req.get(
+ """
+ r1 = await ex_app.embed()
+ assert r1.defs["bar"] == 2
+ assert r1.defs["cache"](1) == 2
+ """
+ ),
+ exec_req.get(
+ """
+ r2 = await ex_app.clone().embed()
+ assert r2.defs["bar"] == 2
+ assert r2.defs["cache"](1) == 2
+ """
+ ),
+ exec_req.get(
+ """
+ r1, r2
+ resolved = True
+ """
+ ),
+ ]
+ )
+ assert k.globals.get("resolved", False), k.stderr
+ assert k.globals["r1"].defs["bar"] == 2
+ assert k.globals["r1"].defs["cache"](1) == 2
+ assert k.globals["r2"].defs["bar"] == 2
+ assert k.globals["r2"].defs["cache"](1) == 2