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: partially instantiate notebooks when autorun on startup is disabled (#3316)

Akshay Agrawalb7d47e48d215
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 5e0473680f..d418d2e575 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -427,6 +427,12 @@ class Kernel:
sys.path.insert(0, "")
self.graph = dataflow.DirectedGraph()
+ # When autorun on startup is disabled, this holds cells that have
+ # not yet been run; these cells are removed when they or their
+ # descendants are run
+ self._uninstantiated_execution_requests: dict[
+ CellId_t, ExecutionRequest
+ ] = {}
self.cell_metadata: dict[CellId_t, CellMetadata] = {
cell_id: CellMetadata(config=config)
for cell_id, config in cell_configs.items()
@@ -1071,9 +1077,12 @@ class Kernel:
# status
cell.set_runtime_state("disabled-transitively")
+ # The error is up-to-date, since we just processed the graph
if cell is not None:
- # The error is up-to-date, since we just processed the graph
cell.set_stale(False)
+ else:
+ # On syntax errors, we don't have a cell object.
+ CellOp.broadcast_stale(cell_id=cid, stale=False)
CellOp.broadcast_error(
data=self.errors[cid],
@@ -1274,6 +1283,9 @@ class Kernel:
async def delete_cell(self, request: DeleteCellRequest) -> None:
"""Delete a cell from kernel and graph."""
cell_id = request.cell_id
+ if cell_id in self._uninstantiated_execution_requests:
+ del self._uninstantiated_execution_requests[cell_id]
+
if cell_id in self.graph.cells:
await self._run_cells(
self.mutate_graph(
@@ -1290,15 +1302,71 @@ class Kernel:
The cells may be cells already existing in the graph or new cells.
Adds the cells in `execution_requests` to the graph before running
- them.
+ them. If the cells have uninstantiated ancestors, these are also run,
+ allowing frontends to incrementally instantiate a notebook.
Cells may use top-level await, which is why this function is async.
"""
- if self.last_interrupt_timestamp is None:
- # No interruption has occurred, so we can run all requests
+
+ async def _run_with_uninstantiated_requests(
+ execution_requests: Sequence[ExecutionRequest],
+ ) -> None:
+ if not self._uninstantiated_execution_requests:
+ await self._run_cells(
+ self.mutate_graph(execution_requests, deletion_requests=[])
+ )
+ return
+
+ execution_requests_cell_ids = {
+ er.cell_id for er in execution_requests
+ }
+ graph = dataflow.DirectedGraph()
+ for cid, er in list(
+ self._uninstantiated_execution_requests.items()
+ ):
+ if cid in execution_requests_cell_ids:
+ # Running a previously uninstantiated cell; just remove
+ # it from our cache of uninstantiated execution requests.
+ del self._uninstantiated_execution_requests[cid]
+ continue
+
+ try:
+ cell = compile_cell(er.code, cell_id=er.cell_id)
+ except Exception:
+ # The cell was not parsable.
+ continue
+ graph.register_cell(cell_id=cid, cell=cell)
+
+ # Collect uninstantiated ancestors
+ ancestors: set[CellId_t] = set()
+ for er in execution_requests:
+ try:
+ cell = compile_cell(er.code, cell_id=er.cell_id)
+ except Exception:
+ continue
+ graph.register_cell(cell_id=er.cell_id, cell=cell)
+ ancestors |= graph.ancestors(er.cell_id)
+
+ # We run all uninstantiated ancestors of the requested cells
+ previously_uninstantiated_requests: list[ExecutionRequest] = []
+ for ancestor_cid in ancestors:
+ if ancestor_cid in self._uninstantiated_execution_requests:
+ previously_uninstantiated_requests.append(
+ self._uninstantiated_execution_requests[ancestor_cid]
+ )
+ del self._uninstantiated_execution_requests[ancestor_cid]
+
await self._run_cells(
- self.mutate_graph(execution_requests, deletion_requests=[])
+ self.mutate_graph(
+ list(execution_requests)
+ + previously_uninstantiated_requests,
+ deletion_requests=[],
+ )
)
+
+ if self.last_interrupt_timestamp is None:
+ # No interruption has occurred, so we can run all requests
+ await _run_with_uninstantiated_requests(execution_requests)
return
# Filter out requests that were created before the last interruption
@@ -1325,9 +1393,7 @@ class Kernel:
else:
filtered_requests.append(request)
- await self._run_cells(
- self.mutate_graph(filtered_requests, deletion_requests=[])
- )
+ await _run_with_uninstantiated_requests(filtered_requests)
@kernel_tracer.start_as_current_span("rename_file")
async def rename_file(self, filename: str) -> None:
@@ -1383,9 +1449,18 @@ class Kernel:
@kernel_tracer.start_as_current_span("run_stale_cells")
async def run_stale_cells(self) -> None:
cells_to_run: set[CellId_t] = set()
+ if self._uninstantiated_execution_requests:
+ cells_to_run |= set(self._uninstantiated_execution_requests.keys())
+ self.mutate_graph(
+ list(self._uninstantiated_execution_requests.values()),
+ deletion_requests=[],
+ )
+ self._uninstantiated_execution_requests = {}
+
for cid, cell_impl in self.graph.cells.items():
if cell_impl.stale and not self.graph.is_disabled(cid):
cells_to_run.add(cid)
+
await self._run_cells(
dataflow.transitive_closure(
self.graph,
@@ -1725,14 +1800,10 @@ class Kernel:
During instantiation, UIElements can check for an initial value
with `get_initial_value`
"""
- # Already instantiated
if self.graph.cells:
del request
LOGGER.debug("App already instantiated.")
- return
-
- # Run cells if auto_run is True
- if request.auto_run:
+ elif request.auto_run:
self.reset_ui_initializers()
for (
object_id,
@@ -1741,13 +1812,12 @@ class Kernel:
self.ui_initializers[object_id] = initial_value
await self.run(request.execution_requests)
self.reset_ui_initializers()
- return
-
- # Otherwise, just register the cells
- self.mutate_graph(request.execution_requests, deletion_requests=[])
- # and set everything to stale
- for cell_id in self.graph.cells:
- self.graph.cells[cell_id].set_stale(stale=True)
+ else:
+ self._uninstantiated_execution_requests = {
+ er.cell_id: er for er in request.execution_requests
+ }
+ for cid in self._uninstantiated_execution_requests:
+ CellOp.broadcast_stale(cell_id=cid, stale=True)
async def install_missing_packages(
self, request: InstallMissingPackagesRequest
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index c301489eb0..2139f7fbdb 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -345,12 +345,48 @@ class TestExecution:
assert k.globals["s"].value == 2
async def test_instantiate_autorun_false(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.instantiate(
+ CreationRequest(
+ execution_requests=(
+ ExecutionRequest(cell_id="0", code="x=0"),
+ er1 := ExecutionRequest(cell_id="1", code="y=x+1"),
+ er2 := ExecutionRequest(cell_id="2", code="z=x+2"),
+ ),
+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ []
+ ),
+ auto_run=False,
+ )
+ )
+ assert not k.errors
+ assert "x" not in k.globals
+ assert "y" not in k.globals
+ assert len(k._uninstantiated_execution_requests) == 3
+
+ # Expect the first cell to implicitly be included in the run ...
+ await k.run([er1])
+ assert k.globals["y"] == 1
+
+ # But z should still not be defined
+ assert "z" not in k.globals
+ assert len(k._uninstantiated_execution_requests) == 1
+
+ # After running er2, no cells should be left uninstantiated
+ await k.run([er2])
+ assert k.globals["z"] == 2
+ assert not k._uninstantiated_execution_requests
+
+ async def test_instantiate_autorun_false_run_stale(
+ self, any_kernel: Kernel
+ ) -> None:
k = any_kernel
await k.instantiate(
CreationRequest(
execution_requests=(
ExecutionRequest(cell_id="0", code="x=0"),
ExecutionRequest(cell_id="1", code="y=x+1"),
+ ExecutionRequest(cell_id="2", code="z=x+2"),
),
set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
[]
@@ -361,10 +397,73 @@ class TestExecution:
assert not k.errors
assert "x" not in k.globals
assert "y" not in k.globals
+ assert len(k._uninstantiated_execution_requests) == 3
- # Expect the first cell to implicitly be included in the run
- await k.run([ExecutionRequest(cell_id="1", code="y=x+1")])
+ await k.run_stale_cells()
assert k.globals["y"] == 1
+ assert k.globals["z"] == 2
+ assert not k._uninstantiated_execution_requests
+
+ async def test_instantiate_autorun_false_delete_cells(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.instantiate(
+ CreationRequest(
+ execution_requests=(
+ ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="y=x+1"),
+ ExecutionRequest(cell_id="2", code="z=x+2"),
+ ),
+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ []
+ ),
+ auto_run=False,
+ )
+ )
+ assert len(k._uninstantiated_execution_requests) == 3
+
+ await k.delete_cell(DeleteCellRequest(cell_id="0"))
+ assert len(k._uninstantiated_execution_requests) == 2
+
+ await k.delete_cell(DeleteCellRequest(cell_id="1"))
+ assert len(k._uninstantiated_execution_requests) == 1
+
+ await k.delete_cell(DeleteCellRequest(cell_id="2"))
+ assert not k._uninstantiated_execution_requests
+
+ async def test_instantiate_autorun_false_run_different_code(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.instantiate(
+ CreationRequest(
+ execution_requests=(
+ ExecutionRequest(cell_id="0", code="x=0"),
+ er1 := ExecutionRequest(cell_id="1", code="y=x+1"),
+ er2 := ExecutionRequest(cell_id="2", code="z=x+2"),
+ ),
+ set_ui_element_value_request=SetUIElementValueRequest.from_ids_and_values(
+ []
+ ),
+ auto_run=False,
+ )
+ )
+ assert len(k._uninstantiated_execution_requests) == 3
+
+ # modify an uninstantiated cell before running it; make sure the old
+ # er gets evicted.
+ await k.run([ExecutionRequest(cell_id="0", code="x = 1")])
+ assert len(k._uninstantiated_execution_requests) == 2
+ assert k.globals["x"] == 1
+
+ await k.run([er1])
+ assert len(k._uninstantiated_execution_requests) == 1
+ assert k.globals["y"] == 2
+
+ await k.run([er2])
+ assert not k._uninstantiated_execution_requests
+ assert k.globals["z"] == 3
# Test errors in marimo semantics
async def test_kernel_simultaneous_multiple_definition_error(