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: cell staleness when autorun on startup is off (#3926)
Akshay Agrawal2777496990d3
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 01ea148ecf..5769821d6c 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -362,13 +362,16 @@ class CellImpl:) -> None:self._run_result_status.state = run_result_status- def set_stale(self, stale: bool, stream: Stream | None = None) -> None:+ def set_stale(+ self, stale: bool, stream: Stream | None = None, broadcast: bool = True+ ) -> None:from marimo._messaging.ops import CellOpself._stale.state = stale- CellOp.broadcast_stale(- cell_id=self.cell_id, stale=stale, stream=stream- )+ if broadcast:+ CellOp.broadcast_stale(+ cell_id=self.cell_id, stale=stale, stream=stream+ )def set_output(self, output: Any) -> None:self._output.output = outputdiff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.pyindex bad6c85999..59a9134fe6 100644--- a/marimo/_runtime/app/kernel_runner.py+++ b/marimo/_runtime/app/kernel_runner.py@@ -101,7 +101,7 @@ class AppKernelRunner:# Register cells through the kernel runner, so that compilation only# occurs once.for cell_id, cell in app.cell_manager.valid_cells():- self._kernel._register_cell(cell_id, cell._cell)+ self._kernel._register_cell(cell_id, cell._cell, stale=False)@propertydef outputs(self) -> dict[CellId_t, Any]:diff --git a/marimo/_runtime/runner/hooks_preparation.py b/marimo/_runtime/runner/hooks_preparation.pyindex cf0725b966..9eebb30cdf 100644--- a/marimo/_runtime/runner/hooks_preparation.py+++ b/marimo/_runtime/runner/hooks_preparation.py@@ -30,8 +30,7 @@ def _update_stale_statuses(runner: cell_runner.Runner) -> None:else:graph.cells[cid].set_runtime_state(status="queued")if graph.cells[cid].stale:- if runner.execution_mode == "autorun":- graph.cells[cid].set_stale(stale=False)+ graph.cells[cid].set_stale(stale=False)PREPARATION_HOOKS: list[PreparationHookType] = [_update_stale_statuses]diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex c2f1000889..7731cea53a 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -717,7 +717,12 @@ class Kernel:reload=False,)- def _register_cell(self, cell_id: CellId_t, cell: CellImpl) -> None:+ def _register_cell(+ self,+ cell_id: CellId_t,+ cell: CellImpl,+ stale: bool,+ ) -> None:if cell_id in self.cell_metadata:# If we already have a config for this cell id, restore it# This can happen when a cell was previously deactivated (due to a@@ -728,6 +733,8 @@ class Kernel:self.cell_metadata[cell_id] = CellMetadata()self.graph.register_cell(cell_id, cell)+ if stale:+ self.graph.cells[cell_id].set_stale(stale=True, broadcast=False)# leaky abstraction: the graph doesn't know about stale modules, so# we have to check for them here.module_reloader = self.module_reloader@@ -768,7 +775,11 @@ class Kernel:return cell, errordef _try_registering_cell(- self, cell_id: CellId_t, code: str, carried_imports: list[ImportData]+ self,+ cell_id: CellId_t,+ code: str,+ carried_imports: list[ImportData],+ stale: bool,) -> Optional[Error]:"""Attempt to register a cell with given id and code.@@ -780,12 +791,12 @@ class Kernel:cell, error = self._try_compiling_cell(cell_id, code, carried_imports)if cell is not None:- self._register_cell(cell_id, cell)+ self._register_cell(cell_id, cell, stale)return errordef _maybe_register_cell(- self, cell_id: CellId_t, code: str+ self, cell_id: CellId_t, code: str, stale: bool) -> tuple[set[CellId_t], Optional[Error]]:"""Register a cell (given by id, code) if not already registered.@@ -827,7 +838,7 @@ class Kernel:previous_children = self._deactivate_cell(cell_id)error = self._try_registering_cell(- cell_id, code, carried_imports=carried_imports+ cell_id, code, carried_imports=carried_imports, stale=stale)if error is not None and previous_cell is not None:# The frontend keeps the cell around in the case of a@@ -1017,6 +1028,7 @@ class Kernel:self,execution_requests: Sequence[ExecutionRequest],deletion_requests: Sequence[DeleteCellRequest],+ cells_starting_stale: set[CellId_t] | None = None,) -> set[CellId_t]:"""Add and remove cells to/from the graph.@@ -1042,6 +1054,9 @@ class Kernel:cells_with_errors_before_mutation = set(self.errors.keys())edges_before = deepcopy(self.graph.children)definitions_before = set(self.graph.definitions.keys())+ cells_starting_stale = (+ set() if cells_starting_stale is None else cells_starting_stale+ )# The set of cells that were successfully registeredregistered_cell_ids: set[CellId_t] = set()@@ -1056,7 +1071,7 @@ class Kernel:# Register and delete cellsfor er in execution_requests:old_children, error = self._maybe_register_cell(- er.cell_id, er.code+ er.cell_id, er.code, stale=er.cell_id in cells_starting_stale)cells_that_were_children_of_mutated_cells |= old_childrenif error is None:@@ -1428,12 +1443,16 @@ class Kernel:er.cell_id for er in execution_requests}graph = dataflow.DirectedGraph()+ # cells in execution_requests that should be initially marked as+ # stale:+ cells_starting_stale: set[CellId_t] = set()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.+ cells_starting_stale.add(cid)del self._uninstantiated_execution_requests[cid]continue@@ -1461,6 +1480,7 @@ class Kernel:previously_uninstantiated_requests.append(self._uninstantiated_execution_requests[ancestor_cid])+ cells_starting_stale.add(ancestor_cid)del self._uninstantiated_execution_requests[ancestor_cid]await self._run_cells(@@ -1468,6 +1488,7 @@ class Kernel:list(execution_requests)+ previously_uninstantiated_requests,deletion_requests=[],+ cells_starting_stale=cells_starting_stale,))@@ -1561,6 +1582,7 @@ class Kernel:self.mutate_graph(list(self._uninstantiated_execution_requests.values()),deletion_requests=[],+ cells_starting_stale=cells_to_run,)self._uninstantiated_execution_requests = {}diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.pyindex 45022673d4..6faeecec55 100644--- a/tests/_runtime/reload/test_module_watcher.py+++ b/tests/_runtime/reload/test_module_watcher.py@@ -458,7 +458,9 @@ async def test_reload_with_modified_cell(assert not k.graph.cells[er_3.cell_id].stale# modify the first cell and make sure it is still marked as stale;- k._maybe_register_cell(er_1.cell_id, f"from {py_modname} import foo; 1")+ k._maybe_register_cell(+ er_1.cell_id, f"from {py_modname} import foo; 1", stale=False+ )assert er_1.cell_id in k.graph.get_stale()diff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.pyindex f2393c3b7e..7471b4914b 100644--- a/tests/_runtime/test_manage_script_metadata.py+++ b/tests/_runtime/test_manage_script_metadata.py@@ -54,7 +54,7 @@ async def test_manage_script_metadata_uv())# Add marimo, skip os- k._maybe_register_cell("0", "import marimo as mo\nimport os")+ k._maybe_register_cell("0", "import marimo as mo\nimport os", stale=False)with open(filename) as f: # noqa: ASYNC230contents = f.read()@@ -63,7 +63,7 @@ async def test_manage_script_metadata_uv(assert '"os",' not in contents# Add markdown- k._maybe_register_cell("1", "import markdown")+ k._maybe_register_cell("1", "import markdown", stale=False)with open(filename) as f: # noqa: ASYNC230contents = f.read()@@ -72,7 +72,7 @@ async def test_manage_script_metadata_uv(assert '"markdown==' in contents# Remove marimo, it's still in requirements- k._maybe_register_cell("0", "import os")+ k._maybe_register_cell("0", "import os", stale=False)with open(filename) as f: # noqa: ASYNC230contents = f.read()@@ -104,7 +104,7 @@ async def test_manage_script_metadata_uv_deletion()# Add marimo, skip os- k._maybe_register_cell("0", "import marimo as mo\nimport os")+ k._maybe_register_cell("0", "import marimo as mo\nimport os", stale=False)with open(filename) as f: # noqa: ASYNC230contents = f.read()@@ -112,7 +112,7 @@ async def test_manage_script_metadata_uv_deletion(assert '"os",' not in contents# Add markdown- k._maybe_register_cell("1", "import markdown")+ k._maybe_register_cell("1", "import markdown", stale=False)with open(filename) as f: # noqa: ASYNC230contents = f.read()@@ -162,7 +162,7 @@ async def test_manage_script_metadata_uv_off()# Add- k._maybe_register_cell("0", "import marimo as mo\nimport os")+ k._maybe_register_cell("0", "import marimo as mo\nimport os", stale=False)with open(filename) as f: # noqa: ASYNC230assert "" == f.read()@@ -190,7 +190,7 @@ async def test_manage_script_metadata_uv_no_filename()# Add- k._maybe_register_cell("0", "import marimo as mo\nimport os")+ k._maybe_register_cell("0", "import marimo as mo\nimport os", stale=False)with open(filename) as f: # noqa: ASYNC230assert "" == f.read()@@ -218,7 +218,7 @@ async def test_manage_script_metadata_pip_noop()# Add- k._maybe_register_cell("0", "import marimo as mo\nimport os")+ k._maybe_register_cell("0", "import marimo as mo\nimport os", stale=False)with open(filename) as f: # noqa: ASYNC230assert "" == f.read()diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 581ec515e0..7222abfd3f 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -24,9 +24,7 @@ from marimo._messaging.ops import CellOpfrom marimo._messaging.types import NoopStreamfrom marimo._plugins.ui._core.ids import IDProviderfrom marimo._plugins.ui._core.ui_element import UIElement-from marimo._runtime.context.kernel_context import (- initialize_kernel_context,-)+from marimo._runtime.context.kernel_context import initialize_kernel_contextfrom marimo._runtime.context.types import teardown_contextfrom marimo._runtime.dataflow import EdgeWithVarfrom marimo._runtime.patches import create_main_module@@ -41,6 +39,7 @@ from marimo._runtime.requests import (from marimo._runtime.runtime import Kernel, notebook_dir, notebook_locationfrom marimo._runtime.scratch import SCRATCH_CELL_IDfrom marimo._server.model import SessionMode+from marimo._utils import parse_dataclassfrom marimo._utils.parse_dataclass import parse_rawfrom tests.conftest import ExecReqProvider, MockedKernel@@ -405,6 +404,74 @@ class TestExecution:assert k.globals["z"] == 2assert not k._uninstantiated_execution_requests+ async def test_instantiate_autorun_false_run_all(+ self, any_kernel: Kernel+ ) -> None:+ k = any_kernel+ await k.instantiate(+ CreationRequest(+ execution_requests=(+ er1 := ExecutionRequest(cell_id="0", code="x=0"),+ er2 := ExecutionRequest(cell_id="1", code="y=x+1"),+ er3 := 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++ await k.run([er1, er2, er3])+ assert k.globals["y"] == 1+ assert k.globals["z"] == 2+ assert not k._uninstantiated_execution_requests++ async def test_instantiate_autorun_false_set_not_stale(+ self, any_kernel: Kernel+ ) -> None:+ """Tests that cells are set to not stale before they start running."""+ k = any_kernel+ await k.instantiate(+ CreationRequest(+ execution_requests=(+ er1 := 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 not k.errors+ assert "x" not in k.globals+ assert "y" not in k.globals+ assert len(k._uninstantiated_execution_requests) == 3++ await k.run([er1])+ cell_ops = [+ parse_dataclass.parse_raw(msg[1], CellOp)+ for msg in k.stream.messages+ if msg[0] == "cell-op"+ ]+ er1_set_not_stale_before_run = False+ for op in cell_ops:+ if op.cell_id == er1.cell_id and op.status == "running":+ break+ if (+ op.cell_id == er1.cell_id+ and op.stale_inputs is not None+ and not op.stale_inputs+ ):+ er1_set_not_stale_before_run = True+ assert er1_set_not_stale_before_run+async def test_instantiate_autorun_false_delete_cells(self, any_kernel: Kernel) -> None: