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.

Improvement: annotate cycles with variable names (#1304)

fuenfundachtzig5fa04ce8f4cc
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 80ea506f96..c49fe49a9c 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -63,11 +63,15 @@ export const MarimoErrorOutput = ({
<Fragment key={idx}>
<p className="mt-4">{"This cell is in a cycle:"}</p>
<ul className="list-disc">
- {error.edges.map((edge) => (
+ {error.edges_with_vars.map((edge) => (
<li className={liStyle} key={`${edge[0]}-${edge[1]}`}>
<CellLinkError cellId={edge[0]} />
- {" -> "}
- <CellLinkError cellId={edge[1]} />
+ <span className="text-muted-foreground">
+ {" -> "}
+ {edge[1].length == 1 ? edge[1] : edge[1].join(", ")}
+ {" -> "}
+ </span>
+ <CellLinkError cellId={edge[2]} />
</li>
))}
</ul>
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 4af5cb9ae1..3ad69b5963 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -26,7 +26,7 @@ export type MarimoError =
raising_cell?: CellId;
}
| { type: "ancestor-stopped"; msg: string; raising_cell: CellId }
- | { type: "cycle"; edges: Array<[CellId, CellId]> }
+ | { type: "cycle"; edges_with_vars: Array<[CellId, string[], CellId]> }
| { type: "multiple-defs"; name: string; cells: CellId[] }
| { type: "delete-nonlocal"; name: string; cells: CellId[] }
| { type: "unknown"; msg?: string };
diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.py
index 05ebf7759c..fd5bb3200f 100644
--- a/marimo/_messaging/errors.py
+++ b/marimo/_messaging/errors.py
@@ -5,12 +5,12 @@ from dataclasses import dataclass
from typing import Optional, Union
from marimo._ast.cell import CellId_t
-from marimo._runtime.dataflow import Edge
+from marimo._runtime.dataflow import EdgeWithVar
@dataclass
class CycleError:
- edges: tuple[Edge, ...]
+ edges_with_vars: tuple[EdgeWithVar, ...]
type: str = "cycle"
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 15441a07c7..1ca0f60b01 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import threading
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Optional, Tuple
+from typing import TYPE_CHECKING, Any, List, Optional, Tuple
from marimo import _loggers
from marimo._ast.cell import (
@@ -19,6 +19,12 @@ if TYPE_CHECKING:
from collections.abc import Collection
Edge = Tuple[CellId_t, CellId_t]
+# EdgeWithVar uses a list rather than a set for the variables linking the cells
+# as sets are not JSON-serializable (required by static_notebook_template()).
+# The first entry is the source node; the second entry is a list of defs from
+# the source read by the destination; and the third entry is the destination
+# node.
+EdgeWithVar = Tuple[CellId_t, List[str], CellId_t]
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_runtime/validate_graph.py b/marimo/_runtime/validate_graph.py
index da0ba599e3..cdbe7deeb2 100644
--- a/marimo/_runtime/validate_graph.py
+++ b/marimo/_runtime/validate_graph.py
@@ -57,8 +57,19 @@ def check_for_cycles(graph: DirectedGraph) -> dict[CellId_t, list[CycleError]]:
errors = defaultdict(list)
for cycle in graph.cycles:
nodes_in_cycle: set[CellId_t] = set(sum(cycle, ()))
+ # before reporting the cells in the cycle to the user,
+ # we first annotate the cycle with the variable names
+ # that link its cells
+ cycle_with_vars = tuple(
+ (
+ edge[0],
+ sorted(graph.cells[edge[0]].defs & graph.cells[edge[1]].refs),
+ edge[1],
+ )
+ for edge in cycle
+ )
for cid in nodes_in_cycle:
- errors[cid].append(CycleError(edges=cycle))
+ errors[cid].append(CycleError(edges_with_vars=cycle_with_vars))
return errors
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index c5ec3a6297..723a458a10 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -15,7 +15,7 @@ from marimo._messaging.errors import (
)
from marimo._messaging.types import NoopStream
from marimo._plugins.ui._core.ids import IDProvider
-from marimo._runtime.dataflow import Edge
+from marimo._runtime.dataflow import EdgeWithVar
from marimo._runtime.requests import (
AppMetadata,
CreationRequest,
@@ -32,11 +32,11 @@ if TYPE_CHECKING:
from types import ModuleType
-def _check_edges(error: Error, expected_edges: Sequence[Edge]) -> None:
+def _check_edges(error: Error, expected_edges: Sequence[EdgeWithVar]) -> None:
assert isinstance(error, CycleError)
- assert len(error.edges) == len(expected_edges)
+ assert len(error.edges_with_vars) == len(expected_edges)
for edge in expected_edges:
- assert edge in error.edges or (edge[1], edge[0]) in error.edges
+ assert edge in error.edges_with_vars
# Test Basic Reactivity
@@ -335,8 +335,8 @@ async def test_cycle_error(k: Kernel) -> None:
assert set(k.errors.keys()) == {"0", "1"}
assert len(k.errors["0"]) == 1
assert len(k.errors["1"]) == 1
- _check_edges(k.errors["0"][0], [("0", "1"), ("1", "0")])
- _check_edges(k.errors["1"][0], [("0", "1"), ("1", "0")])
+ _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
+ _check_edges(k.errors["1"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
# break cycle by modifying cell
await k.run([ExecutionRequest(cell_id="1", code="y=1")])
@@ -358,7 +358,7 @@ async def test_break_cycle_error_with_delete(k: Kernel) -> None:
assert set(k.errors.keys()) == {"0", "1"}
assert len(k.errors["0"]) == 1
assert len(k.errors["1"]) == 1
- _check_edges(k.errors["0"][0], [("0", "1"), ("1", "0")])
+ _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
# break cycle by deleting cell
await k.delete(DeleteRequest(cell_id="1"))
diff --git a/tests/_runtime/test_validate_graph.py b/tests/_runtime/test_validate_graph.py
index e73a10bd2e..e065b33b27 100644
--- a/tests/_runtime/test_validate_graph.py
+++ b/tests/_runtime/test_validate_graph.py
@@ -83,8 +83,8 @@ def test_two_node_cycle() -> None:
graph.register_cell("1", parse_cell("y = x"))
errors = check_for_errors(graph)
assert set(errors.keys()) == set(["0", "1"])
- assert errors["0"] == (CycleError(edges=(("0", "1"), ("1", "0"))),)
- assert errors["1"] == (CycleError(edges=(("0", "1"), ("1", "0"))),)
+ assert errors["0"] == (CycleError(edges_with_vars=(("0", ["x"], "1"), ("1", ["y"], "0"))),)
+ assert errors["1"] == (CycleError(edges_with_vars=(("0", ["x"], "1"), ("1", ["y"], "0"))),)
def test_three_node_cycle() -> None:
@@ -97,11 +97,11 @@ def test_three_node_cycle() -> None:
for _, t in errors.items():
assert len(t) == 1
assert isinstance(t[0], CycleError)
- edges = t[0].edges
- assert len(edges) == 3
- assert ("0", "1") in edges or ("1", "0") in edges
- assert ("1", "2") in edges or ("2", "1") in edges
- assert ("0", "2") in edges or ("2", "0") in edges
+ edges_with_vars = t[0].edges_with_vars
+ assert len(edges_with_vars) == 3
+ assert ("0", ["x"], "2") in edges_with_vars
+ assert ("1", ["y"], "0") in edges_with_vars
+ assert ("2", ["z"], "1") in edges_with_vars
def test_cycle_and_multiple_def() -> None:
@@ -119,10 +119,10 @@ def test_cycle_and_multiple_def() -> None:
cycle_error = cast(
CycleError, t[0] if isinstance(t[0], CycleError) else t[1]
)
- edges = cycle_error.edges
- assert len(edges) == 2
- assert ("0", "1") in edges
- assert ("1", "0") in edges
+ edges_with_vars = cycle_error.edges_with_vars
+ assert len(edges_with_vars) == 2
+ assert ("0", ["x"], "1") in edges_with_vars
+ assert ("1", ["y"], "0") in edges_with_vars
multiple_definition_error = cast(
MultipleDefinitionError,