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
Ensure kernel takes code from runs only (#11574)
Trevor Manz150a0577f850
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.pyindex ce5d8539ef..605632dbe7 100644--- a/marimo/_runtime/commands.py+++ b/marimo/_runtime/commands.py@@ -384,10 +384,11 @@ class EditCellsCommand(Command):"""Apply one edit of the notebook's cells to the kernel.Sent when the notebook changes without a run, as a host edit does.- Changed code is registered without running, so no later run uses- code the notebook no longer has. Deletions and configs take effect- together, before any cell runs because of them, so a cell the edit- deletes or disables does not run when a cell it depended on goes.+ The kernel replaces code it holds for cells that have not run yet;+ a cell that has run takes new code from its next run. Deletions and+ configs take effect together, before any cell runs because of them,+ so a cell the edit deletes or disables does not run when a cell it+ depended on goes.Attributes:codes: New code for each cell the edit created or changed.diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 74eb5d7bab..4411b883b1 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -2003,27 +2003,20 @@ class Kernel:async def edit_cells(self, request: EditCellsCommand) -> None:"""Apply a notebook edit to the graph, then run what follows from it.- Changed code is registered as stale, not run. The kernel only- takes code for cells it has: a cell it has never seen arrives- with the run that first carries it, and code pending from an- instantiation without a run is replaced in place. Deletions and- configs then apply together, and only their consequences run:- cells that depended on a deleted cell, and under autorun, stale- cells the edit enabled.+ Code arrives with runs. A cell the kernel has run keeps its code+ until the next run carries new code, so typing is never compiled+ here. Only code pending from an instantiation that has not run+ is replaced, so that run uses what the notebook has. Deletions+ and configs apply together, and only their consequences run.+ Those are the cells that depended on a deleted cell and, under+ autorun, stale cells the edit enabled, which run the code the+ kernel holds for them."""- edits: list[ExecuteCellCommand] = []for cell_id, code in request.codes.items():- command = ExecuteCellCommand(cell_id=cell_id, code=code)- if cell_id in self.graph.cells:- edits.append(command)- elif cell_id in self._uninstantiated_execution_requests:- self._uninstantiated_execution_requests[cell_id] = command- if edits:- self.mutate_graph(- edits,- deletion_requests=[],- cells_starting_stale={edit.cell_id for edit in edits},- )+ if cell_id in self._uninstantiated_execution_requests:+ self._uninstantiated_execution_requests[cell_id] = (+ ExecuteCellCommand(cell_id=cell_id, code=code)+ )deletions = [DeleteCellCommand(cell_id=cell_id)for cell_id in request.delete_ids@@ -2299,8 +2292,7 @@ class Kernel:stale_cells: set[CellId_t] = set()for cell_id, config in configs.items():metadata = self.cell_metadata.setdefault(cell_id, CellMetadata())- previous = metadata.config- merged = CellConfig.from_dict(previous.asdict())+ merged = CellConfig.from_dict(metadata.config.asdict())merged.configure(config)metadata.config = mergedcell = self.graph.cells.get(cell_id)diff --git a/marimo/_server/host/document.py b/marimo/_server/host/document.pyindex 205c9d36a3..51d730138b 100644--- a/marimo/_server/host/document.py+++ b/marimo/_server/host/document.py@@ -118,10 +118,12 @@ def apply_to_session(session: Session, document: Document) -> None:The session tells its consumers, so the frontend sees the edit andthe host backend mirrors it back as a no-op. The kernel is told of- the edit as one command, so nothing runs code the document no longer- has: changed code is registered without running, and a cell the edit- deletes or disables is gone before any run the deletion causes. The- app config is the session's own and is left alone.+ the edit as one command. Deletions and configs take effect before+ any run the edit causes, so a cell the edit deletes or disables does+ not run when a cell it depended on goes. Code reaches the kernel for+ cells that have never run, so their first run uses it. A cell that+ has run keeps its code until its next run, and enabling it runs that+ code. The app config is the session's own and is left alone."""transaction, command = apply_to_document(session.document, document)if transaction is None:diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 49f4e47fff..5b8deeca67 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -2242,25 +2242,76 @@ except NameError:assert "c" in k.globalsassert "d" not in k.globals- async def test_edit_cells_registers_code_without_running(+ async def test_edit_cells_leaves_run_code_to_the_next_run(self, any_kernel: Kernel) -> None:k = any_kernelawait k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])+ # Typing in progress is not compiled, so it raises no error.await k.edit_cells(EditCellsCommand(- codes={"0": "x = 2", "1": "y = 3"}, configs={}, delete_ids=[]+ codes={"0": "import ", "1": "y = 3"}, configs={}, delete_ids=[]))cell = k.graph.cells["0"]- assert cell.code == "x = 2"- assert cell.stale+ assert cell.code == "x = 1"+ assert not cell.stale+ assert not k.errorsassert "y" not in k.globals# A cell the kernel has never seen arrives with its first run.assert "1" not in k.graph.cells+ async def test_edit_cells_enabling_a_cell_keeps_the_code_the_kernel_holds(+ self, any_kernel: Kernel+ ) -> None:+ k = any_kernel+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])+ await k.set_cell_config(+ UpdateCellConfigCommand(configs={"0": {"disabled": True}})+ )++ await k.edit_cells(+ EditCellsCommand(+ codes={"0": "x = 2"},+ configs={"0": {"disabled": False}},+ delete_ids=[],+ )+ )++ # The edited code is a draft until a run carries it.+ cell = k.graph.cells["0"]+ assert not cell.config.disabled+ assert cell.code == "x = 1"+ assert k.globals["x"] == 1++ async def test_edit_cells_pending_code_runs_as_an_ancestor(+ self, any_kernel: Kernel+ ) -> None:+ k = any_kernel+ await k.instantiate(+ CreateNotebookCommand(+ execution_requests=(+ ExecuteCellCommand(cell_id="0", code="x = 0"),+ ExecuteCellCommand(cell_id="1", code="y = x"),+ ),+ cell_ids=("0", "1"),+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(+ []+ ),+ auto_run=False,+ )+ )++ await k.edit_cells(+ EditCellsCommand(codes={"0": "x = 5"}, configs={}, delete_ids=[])+ )+ await k.run([ExecuteCellCommand(cell_id="1", code="y = x")])++ assert k.globals["x"] == 5+ assert k.globals["y"] == 5+async def test_edit_cells_replaces_pending_code(self, any_kernel: Kernel) -> None:diff --git a/tests/_runtime/test_source_adoption.py b/tests/_runtime/test_source_adoption.pynew file mode 100644index 0000000000..fb62748f52--- /dev/null+++ b/tests/_runtime/test_source_adoption.py@@ -0,0 +1,189 @@+# Copyright 2026 Marimo. All rights reserved.+"""Which source the kernel runs, and when it takes new source.++The kernel adopts a cell's source only from a run that carries it. Cells+that have never run keep the source they were loaded with until a run+needs them. These tests pin that contract, so the commands that deliver+source can change without changing what runs.+"""++from __future__ import annotations++from marimo._runtime.commands import (+ CreateNotebookCommand,+ DeleteCellCommand,+ ExecuteCellCommand,+ UpdateCellConfigCommand,+ UpdateUIElementCommand,+)+from marimo._runtime.runtime import Kernel+from marimo._types.ids import CellId_t+from tests.conftest import MockedKernel++A, B, C = CellId_t("a"), CellId_t("b"), CellId_t("c")+++def run(cell_id: CellId_t, code: str) -> ExecuteCellCommand:+ return ExecuteCellCommand(cell_id=cell_id, code=code)+++async def load(k: Kernel, *cells: tuple[CellId_t, str]) -> None:+ """Instantiate without running, so every cell is pending."""+ await k.instantiate(+ CreateNotebookCommand(+ execution_requests=tuple(run(cid, code) for cid, code in cells),+ cell_ids=tuple(cid for cid, _ in cells),+ set_ui_element_value_request=(+ UpdateUIElementCommand.from_ids_and_values([])+ ),+ auto_run=False,+ )+ )+++async def test_a_run_adopts_source_for_its_targets_only(k: Kernel) -> None:+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ # A is edited to `x = 10` without a run. Only B's run reaches the kernel.+ await k.run([run(B, "y = x + 100")])+ assert k.graph.cells[A].code == "x = 1"+ assert k.globals["y"] == 101+++async def test_a_run_with_changed_source_reruns_children(k: Kernel) -> None:+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.run([run(A, "x = 5")])+ assert k.globals["y"] == 6+ # Running unchanged source runs it again.+ k.globals["y"] = None+ await k.run([run(A, "x = 5")])+ assert k.globals["y"] == 6+++async def test_a_run_with_changed_source_marks_children_stale_lazily(+ lazy_kernel: Kernel,+) -> None:+ k = lazy_kernel+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.run([run(A, "x = 5")])+ assert k.graph.cells[B].stale+ assert k.globals["y"] == 2+++async def test_a_run_registers_never_run_ancestors_with_pending_source(+ k: Kernel,+) -> None:+ await load(k, (A, "x = 7"), (B, "y = x + 1"), (C, "z = 42"))+ assert not k.graph.cells+ await k.run([run(B, "y = x + 1")])+ assert k.globals["y"] == 8+ assert set(k.graph.cells) == {A, B}+ assert set(k._uninstantiated_execution_requests) == {C}+++async def test_a_never_run_ancestor_that_does_not_parse_is_skipped(+ k: Kernel,+) -> None:+ """Known limit. Its names are unknown, so it is not seen as an ancestor."""+ await load(k, (A, "x = ("), (B, "y = x + 1"))+ await k.run([run(B, "y = x + 1")])+ assert k.graph.cells[B].run_result_status == "exception"+ assert A in k._uninstantiated_execution_requests+ assert not k.errors+++async def test_deleting_a_cell_reruns_its_children(k: Kernel) -> None:+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.delete_cell(DeleteCellCommand(cell_id=A))+ assert "x" not in k.globals+ assert k.graph.cells[B].run_result_status == "exception"+++async def test_deleting_a_cell_marks_its_children_stale_lazily(+ lazy_kernel: Kernel,+) -> None:+ k = lazy_kernel+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.delete_cell(DeleteCellCommand(cell_id=A))+ assert k.graph.cells[B].stale+ assert k.globals["y"] == 2+++async def test_enabling_a_stale_cell_runs_its_adopted_source(+ k: Kernel,+) -> None:+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.set_cell_config(+ UpdateCellConfigCommand(configs={B: {"disabled": True}})+ )+ await k.run([run(A, "x = 2")])+ assert "y" not in k.globals+ assert k.graph.cells[B].stale+ # B is edited to `y = x + 10` without a run before it is enabled.+ await k.set_cell_config(+ UpdateCellConfigCommand(configs={B: {"disabled": False}})+ )+ assert k.globals["y"] == 3+++async def test_source_submitted_to_a_disabled_cell_is_adopted_not_run(+ k: Kernel,+) -> None:+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.set_cell_config(+ UpdateCellConfigCommand(configs={A: {"disabled": True}})+ )+ await k.run([run(A, "x = 5")])+ assert k.graph.cells[A].code == "x = 5"+ assert k.cell_metadata[A].code == "x = 5"+ assert k.graph.cells[A].stale+ assert "x" not in k.globals+ await k.set_cell_config(+ UpdateCellConfigCommand(configs={A: {"disabled": False}})+ )+ assert k.globals["y"] == 6+++async def test_a_syntax_error_keeps_the_adopted_source(k: Kernel) -> None:+ await k.run([run(A, "x = 1"), run(B, "y = x + 1")])+ await k.run([run(A, "x = (")])+ assert A not in k.graph.cells+ assert k.cell_metadata[A].code == "x = ("+ assert A not in k._uninstantiated_execution_requests+ assert A in k.errors+ assert "x" not in k.globals+ assert k.graph.cells[B].run_result_status == "exception"+++async def test_markdown_cells_are_rendered_at_load_without_being_adopted(+ mocked_kernel: MockedKernel,+) -> None:+ k = mocked_kernel.k+ await load(k, (A, "import marimo as mo"), (B, 'mo.md("hello")'))+ assert set(k._uninstantiated_execution_requests) == {A}+ assert B not in k.graph.cells+ metadata = k.cell_metadata.get(B)+ assert metadata is None or metadata.code is None+ outputs = [+ op+ for op in mocked_kernel.stream.parsed_operations+ if getattr(op, "cell_id", None) == B+ and getattr(op, "output", None) is not None+ ]+ assert outputs+++async def test_unrelated_cells_run_in_registration_order_which_drifts(+ k: Kernel,+) -> None:+ """Known looseness. Re-registering a cell moves it to the end."""+ await k.run(+ [+ run(C, "log = []"),+ run(A, 'log.append("a")'),+ run(B, 'log.append("b")'),+ ]+ )+ assert k.globals["log"] == ["a", "b"]+ await k.run([run(A, 'log.append("a")\nedited = True')])+ await k.run([run(C, "log = []")])+ assert k.globals["log"] == ["b", "a"]diff --git a/tests/_server/host/test_host_document.py b/tests/_server/host/test_host_document.pyindex 93082aa28b..7e9e45dd9a 100644--- a/tests/_server/host/test_host_document.py+++ b/tests/_server/host/test_host_document.py@@ -39,12 +39,24 @@ def test_deleting_all_cells_broadcasts_the_final_order() -> None:assert session.document.cell_ids == []-async def test_enabling_an_edited_cell_does_not_run_old_code() -> None:[email protected]("edited_earlier", [False, True])+async def test_enabling_a_cell_runs_the_code_the_kernel_holds(+ edited_earlier: bool,+) -> None:cell_id = CellId_t("a")old_code, new_code = 'print("old")', 'print("new")'session = FakeSession()+ # The edit changes the code and enables the cell, or an earlier edit+ # changed the code, which the kernel did not take, and this one enables.session.document = NotebookDocument(- [NotebookCell(cell_id, old_code, "_", CellConfig(disabled=True))]+ [+ NotebookCell(+ cell_id,+ new_code if edited_earlier else old_code,+ "_",+ CellConfig(disabled=True),+ )+ ])document = Document([DocumentCell(cell_id, new_code)], {})@@ -58,7 +70,7 @@ async def test_enabling_an_edited_cell_does_not_run_old_code() -> None:for command in session.commands:await runtime.kernel.handle_message(command)- assert "old" not in "".join(runtime.stdout.messages)+ assert "".join(runtime.stdout.messages) == "old\n"@pytest.mark.parametrize(diff --git a/tests/_server/host/test_host_execution.py b/tests/_server/host/test_host_execution.pyindex a4df7380e7..0be264d5e7 100644--- a/tests/_server/host/test_host_execution.py+++ b/tests/_server/host/test_host_execution.py@@ -170,9 +170,8 @@ async def test_scratch_outcomes_from_the_kernel(assert outcome["error"]["message"][email protected]("delete", [False, True], ids=["edit", "delete"])-async def test_cell_runs_preserve_order_with_later_edits(- live_host: tuple[Starlette, str, Response], delete: bool+async def test_cell_runs_preserve_order_with_later_deletions(+ live_host: tuple[Starlette, str, Response],) -> None:app, notebook_id, events = live_hostnotebook = await app.state.host_context.bridge.host.notebook(notebook_id)@@ -204,15 +203,7 @@ async def test_cell_runs_preserve_order_with_later_edits(app, "POST", runs, headers=key("run"), body=body)assert accepted.status == 202, accepted.body- change = (- {"kind": "delete_cell", "id": cell.id, "base_etag": "*"}- if delete- else {- "kind": "put_cell",- "base_etag": "*",- "cell": {"id": cell.id, "code": "example = 99"},- }- )+ change = {"kind": "delete_cell", "id": cell.id, "base_etag": "*"}edited = await finished(app,"POST",@@ -223,11 +214,7 @@ async def test_cell_runs_preserve_order_with_later_edits(assert edited.status == 200, edited.bodyawait completed(accepted)- assertion = (- f"assert {cell.id!r} not in _graph.cells"- if delete- else f"assert _graph.cells[{cell.id!r}].code == 'example = 99'"- )+ assertion = f"assert {cell.id!r} not in _graph.cells"checked = await finished(app,"POST",@@ -250,10 +237,7 @@ async def test_cell_runs_preserve_order_with_later_edits()== "succeeded")- current = notebook.document.cell(cell.id)- assert (None if current is None else current.code) == (- None if delete else "example = 99"- )+ assert notebook.document.cell(cell.id) is None@pytest.mark.parametrize(