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.

Invalidate cell state before running queued cells (#807)

Akshay Agrawaled5821376158
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 91cd55de8e..16886a514c 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -633,6 +633,12 @@ class Kernel:
self.graph.cells[cid].set_status(status="stale")
else:
self.graph.cells[cid].set_status(status="queued")
+ # State clean-up: don't leak names, UI elements, ...
+ #
+ # Clean-up state for all cells upfront, before running
+ # cells, to relieve memory pressure
+ self._invalidate_cell_state(cid)
+
runner = cell_runner.Runner(
cell_ids=cell_ids,
graph=self.graph,
@@ -651,12 +657,11 @@ class Kernel:
# which is incorrect
# TODO(akshayka): pdb support
LOGGER.debug("final set of cells to run %s", runner.cells_to_run)
+
while runner.pending():
cell_id = runner.pop_cell()
if runner.cancelled(cell_id):
continue
- # State clean-up: don't leak names, UI elements, ...
- self._invalidate_cell_state(cell_id)
cell = self.graph.cells[cell_id]
if cell.stale:
continue
@@ -754,9 +759,8 @@ class Kernel:
if runner.cells_to_run:
assert runner.interrupted
for cid in runner.cells_to_run:
- # `cid` was not run. Its defs should be deleted.
+ # `cid` was not run
self.graph.cells[cid].set_status("idle")
- self._invalidate_cell_state(cid)
CellOp.broadcast_error(
data=[MarimoInterruptionError()],
# these cells are transitioning from queued to stopped
@@ -769,9 +773,8 @@ class Kernel:
for raising_cell in runner.cells_cancelled:
for cid in runner.cells_cancelled[raising_cell]:
- # `cid` was not run. Its defs should be deleted.
+ # `cid` was not run
self.graph.cells[cid].set_status("idle")
- self._invalidate_cell_state(cid)
exception = runner.exceptions[raising_cell]
data: Error
if isinstance(exception, MarimoStopError):
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index d80835c61b..f37268ea75 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -778,3 +778,18 @@ def test_file_path(k: Kernel, exec_req: ExecReqProvider) -> None:
)
assert k.globals["x"] == "/app/test.py"
+
+
+def test_cell_state_invalidated(k: Kernel, exec_req: ExecReqProvider) -> None:
+ k.run(
+ [
+ (er_1 := exec_req.get("x = 0")),
+ (exec_req.get("x; y = 1")),
+ ]
+ )
+ assert k.globals["y"] == 1
+
+ # "y" should not have run, and its global state should have been
+ # invalidated
+ k.run([ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")])
+ assert "y" not in k.globals