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: app.embed(defs={'mine': value}) (#7146)

Dylan Madisetti38e767efcc84
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index d702cc6733..d789fc3aa1 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -336,15 +336,15 @@ class App:
```
@app.cell
- def __(mo):
+ def _(mo):
# ...
@app.cell()
- def __(mo):
+ def _(mo):
# ...
@app.cell(disabled=True)
- def __(mo):
+ def _(mo):
# ...
```
@@ -756,7 +756,10 @@ class App:
return await app_kernel_runner.function_call(request)
@mddoc
- async def embed(self) -> AppEmbedResult:
+ async def embed(
+ self,
+ defs: dict[str, Any] | None = None,
+ ) -> AppEmbedResult:
"""Embed a notebook into another notebook.
The `embed` method lets you embed the output of a notebook
@@ -806,12 +809,26 @@ class App:
```python
one = app.clone()
+ ```
+
+ ```python
r1 = await one.embed()
```
```python
two = app.clone()
+ ```
+
+ ```python
r2 = await two.embed()
+ ```
+
+ Args:
+ defs (dict[str, Any]):
+ You may pass values for any variable definitions as keyword
+ arguments. marimo will use these values instead of executing
+ the cells that would normally define them. Cells that depend
+ on these variables will use your provided values.
Returns:
An object `result` with two attributes: `result.output` (visual
@@ -820,21 +837,49 @@ class App:
"""
from marimo._plugins.stateless.flex import vstack
+ from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context.utils import running_in_notebook
self._maybe_initialize()
+ if defs is not None and any(
+ isinstance(v, UIElement) for k, v in list(defs.items())
+ ):
+ raise ValueError(
+ "Substituting UI Elements for variables is not allowed."
+ )
+
if running_in_notebook():
- # TODO(akshayka): raise a RuntimeError if called in the cell
- # that defined the name bound to this App, if any
+ ctx = get_context()
+ for var, v in ctx.globals.items():
+ if (
+ (v is self or getattr(v, "app", None) is self)
+ and ctx.execution_context is not None
+ and ctx.execution_context.cell_id
+ in ctx.graph.get_defining_cells(var)
+ ):
+ raise RuntimeError(
+ "App.embed() cannot be called in the cell that "
+ "imports the app. Call embed() in another cell."
+ )
+
app_kernel_runner = self._get_kernel_runner()
outputs: dict[CellId_t, Any]
glbls: dict[str, Any]
- if not app_kernel_runner.outputs:
- outputs, glbls = await app_kernel_runner.run(
- set(self._execution_order)
+
+ if not app_kernel_runner.are_outputs_cached(defs):
+ app_kernel_runner.register_defs(defs)
+ # Inject provided defs into the kernel's globals
+ if defs:
+ app_kernel_runner.globals.update(defs)
+
+ cells_to_run = set(
+ dataflow.prune_cells_for_overrides(
+ self._graph, self._execution_order, defs or {}
+ )
)
+ outputs, glbls = await app_kernel_runner.run(cells_to_run)
else:
outputs, glbls = (
app_kernel_runner.outputs,
@@ -851,10 +896,10 @@ class App:
defs=self._globals_to_defs(glbls),
)
else:
- flat_outputs, defs = self.run()
+ flat_outputs, computed_defs = self.run(defs=defs or {})
return AppEmbedResult(
output=vstack([o for o in flat_outputs if o is not None]),
- defs=defs,
+ defs=computed_defs,
)
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index b95d92dce4..bde24641f6 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -40,6 +40,7 @@ class AppKernelRunner:
self.app = app
self._outputs: dict[CellId_t, Any] = {}
+ self._previously_seen_defs: dict[str, Any] | None = None
ctx = get_context()
if not isinstance(ctx, KernelRuntimeContext):
@@ -113,6 +114,13 @@ class AppKernelRunner:
def outputs(self) -> dict[CellId_t, Any]:
return self._outputs
+ def are_outputs_cached(self, defs: dict[str, Any] | None) -> bool:
+ # The equality check is brittle but hashing isn't great either ...
+ return (defs == self._previously_seen_defs) and len(self.outputs) > 0
+
+ def register_defs(self, defs: dict[str, Any] | None) -> None:
+ self._previously_seen_defs = defs
+
@property
def globals(self) -> dict[str, Any]:
return self._kernel.globals
@@ -125,8 +133,21 @@ class AppKernelRunner:
is not None
]
- with self._runtime_context.install():
- await self._kernel.run(execution_requests)
+ execution_mode = self._kernel.reactive_execution_mode
+ try:
+ graph = self._kernel.graph
+ # The _only_ cells that run should be the ones in
+ # cells_to_run. For this reason we set the execution
+ # mode to lazy. We also make all cells stale to ensure
+ # that ancestors aren't run.
+ for c in graph.cells.values():
+ c.set_stale(stale=False, broadcast=False)
+ self._kernel.reactive_execution_mode = "lazy"
+ with self._runtime_context.install():
+ await self._kernel.run(execution_requests)
+ finally:
+ self._kernel.reactive_execution_mode = execution_mode
+
return self.outputs, self._kernel.globals
async def set_ui_element_value(
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index 013e910f70..ddce9273a3 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any, Callable, Optional
-from marimo._ast.errors import IncompleteRefsError
from marimo._ast.names import SETUP_CELL_NAME
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.types import NoopStream
@@ -49,37 +48,15 @@ class AppScriptRunner:
self._glbls = glbls if glbls else {}
# Prune cells that define provided refs
- cells_to_prune: set[CellId_t] = set()
- if self._glbls:
- refs = set(self._glbls.keys())
- for ref_name in refs:
- if ref_name in self.app.graph.definitions:
- defining_cells = self.app.graph.get_defining_cells(
- ref_name
- )
- cells_to_prune.update(defining_cells)
-
- # Validate that all definitions from pruned cells are provided
- missing_defs: set[str] = set()
- for cell_id in cells_to_prune:
- cell = self.app.graph.cells[cell_id]
- # Check all definitions this cell would have provided
- for missing in cell.defs - refs:
- missing_defs.add(missing)
-
- if missing_defs:
- raise IncompleteRefsError(
- f"When providing refs that override cell definitions, you must "
- f"provide all definitions from those cells. Missing: {sorted(missing_defs)}. "
- f"Provided refs: {sorted(refs)}."
- )
+ pruned_execution_order = dataflow.prune_cells_for_overrides(
+ self.app.graph, self.app.execution_order, self._glbls
+ )
self.cells_to_run = [
cid
- for cid in self.app.execution_order
+ for cid in pruned_execution_order
if app.cell_manager.cell_data_at(cid).cell is not None
and not self.app.graph.is_disabled(cid)
- and cid not in cells_to_prune
]
self._executor = get_executor(ExecutionConfig())
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 769fd5c7b0..4148c7a24b 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -806,6 +806,70 @@ def topological_sort(
return sorted_cell_ids
+def prune_cells_for_overrides(
+ graph: DirectedGraph,
+ execution_order: Collection[CellId_t],
+ overrides: dict[str, Any],
+) -> list[CellId_t]:
+ """Prune cells from execution when their definitions are overridden.
+
+ When variable definitions are provided externally (overrides), this function
+ identifies cells that would normally define those variables and removes them
+ from the execution order. It also validates that all definitions from pruned
+ cells are provided in the overrides.
+
+ Args:
+ graph: The dataflow graph containing cell dependencies
+ execution_order: Ordered collection of cells to execute
+ overrides: Dictionary mapping variable names to their override values
+
+ Returns:
+ Filtered execution order excluding cells whose definitions are overridden
+
+ Raises:
+ IncompleteRefsError: If overrides don't provide all definitions from
+ pruned cells (e.g., a cell defines both x and y, but only x is
+ provided in overrides)
+
+ Example:
+ If cell A defines variables x and y, and overrides = {"x": 1, "y": 2},
+ then cell A will be pruned from execution_order. However, if overrides
+ only contains {"x": 1}, an IncompleteRefsError is raised because y is
+ missing.
+ """
+ if not overrides:
+ return list(execution_order)
+
+ cells_to_prune: set[CellId_t] = set()
+ refs = set(overrides.keys())
+
+ # Find cells that define the overridden variables
+ for ref_name in refs:
+ if ref_name in graph.definitions:
+ defining_cells = graph.get_defining_cells(ref_name)
+ cells_to_prune.update(defining_cells)
+
+ # Validate that all definitions from pruned cells are provided
+ missing_defs: set[str] = set()
+ for cell_id in cells_to_prune:
+ cell = graph.cells[cell_id]
+ # Check all definitions this cell would have provided
+ for missing in cell.defs - refs:
+ missing_defs.add(missing)
+
+ if missing_defs:
+ from marimo._ast.errors import IncompleteRefsError
+
+ raise IncompleteRefsError(
+ f"When providing refs that override cell definitions, you must "
+ f"provide all definitions from those cells. Missing: {sorted(missing_defs)}. "
+ f"Provided refs: {sorted(refs)}."
+ )
+
+ # Return filtered execution order
+ return [cid for cid in execution_order if cid not in cells_to_prune]
+
+
def import_block_relatives(
graph: DirectedGraph, cid: CellId_t, children: bool
) -> set[CellId_t]:
diff --git a/marimo/_smoke_tests/appcomp/inner.py b/marimo/_smoke_tests/appcomp/inner.py
index be06dd1fa0..abefecde8f 100644
--- a/marimo/_smoke_tests/appcomp/inner.py
+++ b/marimo/_smoke_tests/appcomp/inner.py
@@ -19,8 +19,13 @@ def _(mo):
@app.cell
-def _(mo):
- x = mo.ui.number(1, 10)
+def _():
+ x_initial_value = 1
+ return (x_initial_value,)
+
+def _(mo, x_initial_value):
+ x = mo.ui.number(x_initial_value, 10)
return (x,)
@@ -41,7 +46,6 @@ def _(y):
y
return
-
@app.cell
def _(x, y):
x.value + y.value
diff --git a/marimo/_smoke_tests/appcomp/main.py b/marimo/_smoke_tests/appcomp/main.py
index e06c58f0c1..b9b8e4aadd 100644
--- a/marimo/_smoke_tests/appcomp/main.py
+++ b/marimo/_smoke_tests/appcomp/main.py
@@ -2,7 +2,7 @@
import marimo
-__generated_with = "0.15.5"
+__generated_with = "0.18.4"
app = marimo.App(width="medium")
@@ -14,7 +14,9 @@ def _():
@app.cell(hide_code=True)
def _(mo):
- mo.md("## Render the same app multiple times")
+ mo.md("""
+ ## Render the same app multiple times
+ """)
return
@@ -37,9 +39,53 @@ def _(result):
return
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ ## Clone an app
+ """)
+ return
+
+
+def _(app):
+ clone = app.clone()
+ return (clone,)
+
+
+async def _(clone):
+ clone_result = await clone.embed()
+ clone_result.output
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""
+ ## Parametrize an app
+ """)
+ return
+
+
+def _(app):
+ parametrized_app = app.clone()
+ return (parametrized_app,)
+
+
@app.cell
+async def _(parametrized_app):
+ _result = await parametrized_app.embed(defs={"x_initial_value": 0})
+ _result.output
+ return
+
+
[email protected](hide_code=True)
def _(mo):
- mo.md("## Render an app inside tabs")
+ mo.md("""
+ ## Render an app inside tabs
+ """)
return
@@ -52,7 +98,9 @@ async def _(app, mo):
@app.cell
def _(mo):
- mo.md(rf"## Render an app that uses function calls")
+ mo.md(rf"""
+ ## Render an app that uses function calls
+ """)
return
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index f77903a605..a294f61137 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -1017,6 +1017,256 @@ class TestAppComposition:
assert result.output.text == vstack(["hello", "world"]).text
assert not result.defs
+ async def test_app_embed_with_defs(self) -> None:
+ """Test embed() with defs parameter to override cell definitions."""
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int]:
+ x = 10
+ return (x,)
+
+ @app.cell
+ def __(x: int) -> tuple[int]:
+ y = x * 2
+ return (y,)
+
+ @app.cell
+ def __(y: int) -> None:
+ f"Result: {y}"
+
+ # Test without override
+ result = await app.embed()
+ assert result.defs["x"] == 10
+ assert result.defs["y"] == 20
+ assert "Result: 20" in result.output.text
+
+ # Test with override - cell defining x should be pruned
+ result = await app.embed(defs={"x": 100})
+ assert result.defs["x"] == 100
+ assert result.defs["y"] == 200
+ assert "Result: 200" in result.output.text
+
+ async def test_app_embed_with_defs_ui_element_not_allowed(self) -> None:
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int]:
+ x = 10
+ return (x,)
+
+ import marimo as mo
+
+ with pytest.raises(ValueError) as excinfo:
+ await app.embed(defs={"x": mo.ui.slider(1, 10)})
+
+ assert "Substituting UI Elements for variables is not allowed" in str(excinfo.value)
+
+ async def test_app_embed_with_defs_multiple_vars(self) -> None:
+ """Test embed() with defs overriding a cell that defines multiple variables."""
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int, int]:
+ a = 5
+ b = 10
+ return a, b
+
+ @app.cell
+ def __(a: int, b: int) -> None:
+ f"Sum: {a + b}"
+
+ # Test without override
+ result = await app.embed()
+ assert result.defs["a"] == 5
+ assert result.defs["b"] == 10
+ assert "Sum: 15" in result.output.text
+
+ # Test with override - must provide both a and b
+ result = await app.embed(defs={"a": 100, "b": 200})
+ assert result.defs["a"] == 100
+ assert result.defs["b"] == 200
+ assert "Sum: 300" in result.output.text
+
+ async def test_app_embed_with_defs_incomplete_refs_error(self) -> None:
+ """Test that embed() raises IncompleteRefsError for partial overrides."""
+ from marimo._ast.errors import IncompleteRefsError
+
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int, int]:
+ x = 1
+ y = 2
+ return x, y
+
+ @app.cell
+ def __(x: int, y: int) -> None:
+ f"{x} + {y}"
+
+ # Should raise error when only providing x but not y
+ with pytest.raises(IncompleteRefsError) as exc_info:
+ await app.embed(defs={"x": 100})
+
+ assert "y" in str(exc_info.value)
+ assert "Missing: ['y']" in str(exc_info.value)
+
+ async def test_app_embed_with_defs_multiple_cells(self) -> None:
+ """Test embed() with defs pruning multiple cells."""
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int]:
+ a = 1
+ return (a,)
+
+ @app.cell
+ def __() -> tuple[int]:
+ b = 2
+ return (b,)
+
+ @app.cell
+ def __(a: int, b: int) -> tuple[int]:
+ c = a + b
+ return (c,)
+
+ @app.cell
+ def __(c: int) -> None:
+ f"Result: {c}"
+
+ # Override both a and b - should prune first two cells
+ result = await app.embed(defs={"a": 10, "b": 20})
+ assert result.defs["a"] == 10
+ assert result.defs["b"] == 20
+ assert result.defs["c"] == 30
+ assert "Result: 30" in result.output.text
+
+ async def test_app_embed_with_defs_partial_pruning(self) -> None:
+ """Test embed() with defs pruning only some cells."""
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int]:
+ x = 5
+ return (x,)
+
+ @app.cell
+ def __() -> tuple[int]:
+ y = 10
+ return (y,)
+
+ @app.cell
+ def __(x: int, y: int) -> None:
+ f"x={x}, y={y}"
+
+ # Override only x - should prune only first cell
+ result = await app.embed(defs={"x": 100})
+ assert result.defs["x"] == 100
+ assert result.defs["y"] == 10 # y cell still ran
+ assert "x=100, y=10" in result.output.text
+
+ async def test_app_embed_with_defs_stale_outputs(self) -> None:
+ """Test that embed() doesn't return stale cached outputs with different defs."""
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int]:
+ x = 10
+ return (x,)
+
+ @app.cell
+ def __(x: int) -> None:
+ "x is small" if x == 10 else "x is large"
+
+ # First call - no override
+ result_initial = await app.embed()
+ assert result_initial.defs["x"] == 10
+ assert "x is small" in result_initial.output.text
+
+ # Second call - with first override
+ result_override = await app.embed(defs={"x": 100})
+ assert result_override.defs["x"] == 100
+ assert "x is large" in result_override.output.text
+ assert "x is small" not in result_override.output.text
+
+ # Third call - with second override
+ result_override2 = await app.embed(defs={"x": 200})
+ assert result_override2.defs["x"] == 200
+ assert "x is large" in result_override2.output.text
+ assert "x is small" not in result_override2.output.text
+
+ # Check that initial result wasn't mutated by subsequent calls
+ assert result_initial.defs["x"] == 10
+ assert "x is small" in result_initial.output.text
+ assert "x is large" not in result_initial.output.text
+
+ async def test_app_embed_with_defs_stale_outputs_kernel(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test embed() with different defs through kernel (tests caching code path)."""
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from marimo import App
+
+ app = App()
+
+ @app.cell
+ def __() -> tuple[int]:
+ x = 10
+ return (x,)
+
+ @app.cell
+ def __(x: int) -> None:
+ "x is small" if x == 10 else "x is large"
+ """
+ ),
+ exec_req.get(
+ """
+ # First call - no override
+ result_initial = await app.embed()
+ """
+ ),
+ exec_req.get(
+ """
+ # Second call - with first override
+ result_override = await app.embed(defs={"x": 100})
+ """
+ ),
+ exec_req.get(
+ """
+ # Third call - with second override
+ result_override2 = await app.embed(defs={"x": 200})
+ """
+ ),
+ ]
+ )
+ assert not k.errors
+
+ result_initial = k.globals["result_initial"]
+ result_override = k.globals["result_override"]
+ result_override2 = k.globals["result_override2"]
+
+ # Check first result - output then defs
+ assert "x is small" in result_initial.output.text
+ assert result_initial.defs["x"] == 10
+
+ # Check second result with first override - output then defs
+ assert "x is large" in result_override.output.text
+ assert "x is small" not in result_override.output.text
+ assert result_override.defs["x"] == 100
+
+ # Check third result with second override - output then defs
+ assert "x is large" in result_override2.output.text
+ assert "x is small" not in result_override2.output.text
+ assert result_override2.defs["x"] == 200
+
+ # Check that initial result wasn't mutated by subsequent calls
+ assert "x is small" in result_initial.output.text
+ assert "x is large" not in result_initial.output.text
+ assert result_initial.defs["x"] == 10
+
@pytest.mark.xfail(
True, reason="Flaky in CI, can't repro locally", strict=False
)
@@ -1255,6 +1505,40 @@ class TestAppComposition:
assert k.globals["cloned"].defs.get("this_is_foo_path").stem == directory
+ @staticmethod
+ async def test_app_embed_same_cell_in_kernel(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from tests._ast.app_data import notebook_filename
+ app = await notebook_filename.app.embed()
+ app
+ """
+ ),
+ ]
+ )
+ assert "App.embed() cannot be called" in k.stderr.messages[0]
+
+ @staticmethod
+ async def test_app_embed_same_cell_in_kernel_direct(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from tests._ast.app_data.notebook_filename import app
+ await app.embed()
+ """
+ ),
+ ]
+ )
+ assert "App.embed() cannot be called" in k.stderr.messages[0]
+
+
class TestAppKernelRunnerRegistry:
def test_get_runner(self, k: Kernel) -> None:
# `k` fixture installs a context, needed for AppKernelRunner
diff --git a/tests/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.py
index cf9e8730b1..d8eab1ffb5 100644
--- a/tests/_runtime/test_dataflow.py
+++ b/tests/_runtime/test_dataflow.py
@@ -1405,3 +1405,187 @@ def test_directed_graph_copy_no_filename() -> None:
# Verify the copied graph has the same structure
assert len(copied_graph.cells) == 1
assert "0" in copied_graph.cells
+
+
+def test_prune_cells_for_overrides_empty() -> None:
+ """Test prune_cells_for_overrides with no overrides returns all cells."""
+ graph = dataflow.DirectedGraph()
+
+ # Create cells: x = 0, y = x, z = y
+ cell_0 = parse_cell("x = 0")
+ graph.register_cell("0", cell_0)
+
+ cell_1 = parse_cell("y = x")
+ graph.register_cell("1", cell_1)
+
+ cell_2 = parse_cell("z = y")
+ graph.register_cell("2", cell_2)
+
+ execution_order = ["0", "1", "2"]
+
+ # Test with empty overrides
+ result = dataflow.prune_cells_for_overrides(graph, execution_order, {})
+ assert result == ["0", "1", "2"]
+
+
+def test_prune_cells_for_overrides_single_cell() -> None:
+ """Test pruning a single cell that defines a single variable."""
+ graph = dataflow.DirectedGraph()
+
+ # Create cells: x = 0, y = x, z = y
+ cell_0 = parse_cell("x = 0")
+ graph.register_cell("0", cell_0)
+
+ cell_1 = parse_cell("y = x")
+ graph.register_cell("1", cell_1)
+
+ cell_2 = parse_cell("z = y")
+ graph.register_cell("2", cell_2)
+
+ execution_order = ["0", "1", "2"]
+
+ # Override x - should prune cell 0
+ result = dataflow.prune_cells_for_overrides(
+ graph, execution_order, {"x": 100}
+ )
+ assert result == ["1", "2"]
+
+
+def test_prune_cells_for_overrides_multiple_defs() -> None:
+ """Test pruning a cell that defines multiple variables."""
+ graph = dataflow.DirectedGraph()
+
+ # Create cell that defines both x and y
+ cell_0 = parse_cell("x = 0\ny = 1")
+ graph.register_cell("0", cell_0)
+
+ # Cell that uses x and y
+ cell_1 = parse_cell("z = x + y")
+ graph.register_cell("1", cell_1)
+
+ execution_order = ["0", "1"]
+
+ # Override both x and y - should prune cell 0
+ result = dataflow.prune_cells_for_overrides(
+ graph, execution_order, {"x": 100, "y": 200}
+ )
+ assert result == ["1"]
+
+
+def test_prune_cells_for_overrides_incomplete_refs_error() -> None:
+ """Test that incomplete overrides raise IncompleteRefsError."""
+ from marimo._ast.errors import IncompleteRefsError
+
+ graph = dataflow.DirectedGraph()
+
+ # Create cell that defines both x and y
+ cell_0 = parse_cell("x = 0\ny = 1")
+ graph.register_cell("0", cell_0)
+
+ # Cell that uses x and y
+ cell_1 = parse_cell("z = x + y")
+ graph.register_cell("1", cell_1)
+
+ execution_order = ["0", "1"]
+
+ # Override only x (not y) - should raise error
+ with pytest.raises(IncompleteRefsError) as exc_info:
+ dataflow.prune_cells_for_overrides(graph, execution_order, {"x": 100})
+
+ assert "y" in str(exc_info.value)
+ assert "Missing: ['y']" in str(exc_info.value)
+ assert "Provided refs: ['x']" in str(exc_info.value)
+
+
+def test_prune_cells_for_overrides_multiple_cells() -> None:
+ """Test pruning multiple cells when overriding multiple variables."""
+ graph = dataflow.DirectedGraph()
+
+ # Create separate cells for x and y
+ cell_0 = parse_cell("x = 0")
+ graph.register_cell("0", cell_0)
+
+ cell_1 = parse_cell("y = 1")
+ graph.register_cell("1", cell_1)
+
+ # Cell that uses both x and y
+ cell_2 = parse_cell("z = x + y")
+ graph.register_cell("2", cell_2)
+
+ execution_order = ["0", "1", "2"]
+
+ # Override both x and y - should prune cells 0 and 1
+ result = dataflow.prune_cells_for_overrides(
+ graph, execution_order, {"x": 100, "y": 200}
+ )
+ assert result == ["2"]
+
+
+def test_prune_cells_for_overrides_partial_override() -> None:
+ """Test partial override where only some cells are pruned."""
+ graph = dataflow.DirectedGraph()
+
+ # Create separate cells for x and y
+ cell_0 = parse_cell("x = 0")
+ graph.register_cell("0", cell_0)
+
+ cell_1 = parse_cell("y = 1")
+ graph.register_cell("1", cell_1)
+
+ # Cell that uses both x and y
+ cell_2 = parse_cell("z = x + y")
+ graph.register_cell("2", cell_2)
+
+ execution_order = ["0", "1", "2"]
+
+ # Override only x - should prune only cell 0
+ result = dataflow.prune_cells_for_overrides(
+ graph, execution_order, {"x": 100}
+ )
+ assert result == ["1", "2"]
+
+
+def test_prune_cells_for_overrides_nonexistent_variable() -> None:
+ """Test overriding a variable that doesn't exist in the graph."""
+ graph = dataflow.DirectedGraph()
+
+ # Create cells: x = 0, y = x
+ cell_0 = parse_cell("x = 0")
+ graph.register_cell("0", cell_0)
+
+ cell_1 = parse_cell("y = x")
+ graph.register_cell("1", cell_1)
+
+ execution_order = ["0", "1"]
+
+ # Override a variable that doesn't exist - should not prune anything
+ result = dataflow.prune_cells_for_overrides(
+ graph, execution_order, {"nonexistent": 100}
+ )
+ assert result == ["0", "1"]
+
+
+def test_prune_cells_for_overrides_preserves_order() -> None:
+ """Test that pruning preserves the original execution order."""
+ graph = dataflow.DirectedGraph()
+
+ # Create cells in specific order
+ cell_0 = parse_cell("a = 0")
+ graph.register_cell("0", cell_0)
+
+ cell_1 = parse_cell("b = 1")
+ graph.register_cell("1", cell_1)
+
+ cell_2 = parse_cell("c = 2")
+ graph.register_cell("2", cell_2)
+
+ cell_3 = parse_cell("d = a + c")
+ graph.register_cell("3", cell_3)
+
+ execution_order = ["0", "1", "2", "3"]
+
+ # Override b - should prune only cell 1, preserving order
+ result = dataflow.prune_cells_for_overrides(
+ graph, execution_order, {"b": 100}
+ )
+ assert result == ["0", "2", "3"]
diff --git a/tests/_runtime/test_trace.py b/tests/_runtime/test_trace.py
index 187917a3b3..8d93a66322 100644
--- a/tests/_runtime/test_trace.py
+++ b/tests/_runtime/test_trace.py
@@ -302,10 +302,17 @@ class TestEmbedTrace:
from tests._runtime.script_data import (
script_exception_with_output
)
+ """
+ ),
+ ),
+ ExecutionRequest(
+ cell_id="1",
+ code=textwrap.dedent(
+ """
await script_exception_with_output.app.embed()
"""
),
- )
+ ),
]
)