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 stale variable dependencies in frontend (#5719)
Trevor Manzfa23ce8f617f
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex d23f8c4aa1..ab3bc7fe8d 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -13,7 +13,7 @@ import sysimport threadingimport timeimport traceback-from copy import copy, deepcopy+from copy import copyfrom functools import cached_propertyfrom multiprocessing import connectionfrom pathlib import Path@@ -1113,8 +1113,6 @@ class Kernel:LOGGER.debug("Current set of errors: %s", self.errors)cells_before_mutation = set(self.graph.cells.keys())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)@@ -1271,27 +1269,22 @@ class Kernel:cell_id=cid,)- # Only broadcast Variables message if definitions changed- edges_after = self.graph.children- definitions_after = set(self.graph.definitions.keys())- if (- edges_before != edges_after- or definitions_before != definitions_after- ):- Variables(- variables=[- VariableDeclaration(- name=variable,- declared_by=list(declared_by),- used_by=list(- self.graph.get_referring_cells(- variable, language="python"- )- ),- )- for variable, declared_by in self.graph.definitions.items()- ]- ).broadcast()+ # Always broadcast Variables message after graph mutation to ensure+ # frontend has the latest dependency information+ Variables(+ variables=[+ VariableDeclaration(+ name=variable,+ declared_by=list(declared_by),+ used_by=list(+ self.graph.get_referring_cells(+ variable, language="python"+ )+ ),+ )+ for variable, declared_by in self.graph.definitions.items()+ ]+ ).broadcast()stale_cells = (set(diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 0a2f1da5e6..d18a7d7250 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -2949,7 +2949,7 @@ class TestStateTransitions:assert k.graph.cells[er_2.cell_id].runtime_state == "idle"@staticmethod- async def test_variables_broadcast_only_on_change(+ async def test_variables_broadcast_always(mocked_kernel: MockedKernel, exec_req: ExecReqProvider) -> None:k = mocked_kernel.k@@ -2963,10 +2963,10 @@ class TestStateTransitions:)assert initial_messages == 1- # Re-running same cell shouldn't broadcast Variables+ # Re-running same cell should now broadcast Variablesstream.messages.clear()await k.run([er])- assert not any(m[0] == "variables" for m in stream.messages)+ assert sum(1 for m in stream.messages if m[0] == "variables") == 1# Adding a new variable should broadcast Variablesstream.messages.clear()@@ -2979,17 +2979,67 @@ class TestStateTransitions:await k.run([exec_req.get("z = y")])assert sum(1 for m in stream.messages if m[0] == "variables") == 1- # Modifying value without changing edges/defs shouldn't broadcast+ # Modifying value without changing edges/defs should now broadcaststream.messages.clear()er_2.code = "y = 2"await k.run([exec_req.get_with_id(er_2.cell_id, er_2.code)])- assert not any(m[0] == "variables" for m in stream.messages)+ assert sum(1 for m in stream.messages if m[0] == "variables") == 1# Deleting a cell should broadcast Variablesstream.messages.clear()await k.delete_cell(DeleteCellRequest(cell_id=er_2.cell_id))assert sum(1 for m in stream.messages if m[0] == "variables") == 1+ @staticmethod+ async def test_variables_broadcast_on_usage_change(+ mocked_kernel: MockedKernel, exec_req: ExecReqProvider+ ) -> None:+ """Test that changing which variables a cell uses triggers a broadcast.++ This captures the bug where editing a cell to use fewer variables+ from an imported module wouldn't update the frontend's dependency info.+ """+ k = mocked_kernel.k+ stream = mocked_kernel.stream++ # Cell 1: Define multiple variables+ await k.run([exec_req.get("a = 1\nb = 2")])+ stream.messages.clear()++ # Cell 2: Use both variables+ er_2 = exec_req.get("print(a)\nprint(b)")+ await k.run([er_2])+ variables_msg_count = sum(+ 1 for m in stream.messages if m[0] == "variables"+ )+ assert variables_msg_count == 1++ # Check that both a and b show cell 2 in their used_by+ variables_msg = next(m for m in stream.messages if m[0] == "variables")+ variables = variables_msg[1]["variables"]+ var_a = next(v for v in variables if v["name"] == "a")+ var_b = next(v for v in variables if v["name"] == "b")+ assert er_2.cell_id in var_a["used_by"]+ assert er_2.cell_id in var_b["used_by"]++ # Edit cell 2 to only use variable 'a'+ stream.messages.clear()+ await k.run([exec_req.get_with_id(er_2.cell_id, "print(a)")])++ # Should broadcast Variables because usage changed+ variables_msg_count = sum(+ 1 for m in stream.messages if m[0] == "variables"+ )+ assert variables_msg_count == 1++ # Check that only a shows cell 2 in used_by now+ variables_msg = next(m for m in stream.messages if m[0] == "variables")+ variables = variables_msg[1]["variables"]+ var_a = next(v for v in variables if v["name"] == "a")+ var_b = next(v for v in variables if v["name"] == "b")+ assert er_2.cell_id in var_a["used_by"]+ assert er_2.cell_id not in var_b["used_by"]+class TestErrorHandling:async def test_error_handling(