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: tie-break topological sort by top-down order (#3060)

Myles Scolnick5e76aa14dbf3
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 1acf41d200..cd74deddf7 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -489,18 +489,36 @@ def get_cycles(
def topological_sort(
graph: DirectedGraph, cell_ids: Collection[CellId_t]
) -> list[CellId_t]:
- """Sort `cell_ids` in a topological order."""
+ """Sort `cell_ids` in a topological order using a heap queue.
+
+ When multiple cells have the same parents (including no parents), the tie is broken by
+ registration order - cells registered earlier are processed first.
+ """
+ from heapq import heappop, heappush
+
parents, children = induced_subgraph(graph, cell_ids)
- roots = [cid for cid in cell_ids if not parents[cid]]
- sorted_cell_ids = []
- while roots:
- cid = roots.pop(0)
+ # Use registration order as tiebreaker
+ top_down_keys = {
+ key: index for index, key in enumerate(graph.cells.keys())
+ }
+
+ # Initialize heap with roots (nodes with no parents)
+ heap: list[tuple[int, CellId_t]] = []
+ for cid in cell_ids:
+ if not parents[cid]:
+ # Use tuple with registration order as first element for heap ordering
+ heappush(heap, (top_down_keys[cid], cid))
+
+ sorted_cell_ids: list[CellId_t] = []
+ while heap:
+ _, cid = heappop(heap)
sorted_cell_ids.append(cid)
+
for child in children[cid]:
parents[child].remove(cid)
if not parents[child]:
- roots.append(child)
- # TODO make sure parents for each id is empty, otherwise cycle
+ heappush(heap, (top_down_keys[child], child))
+
return sorted_cell_ids
diff --git a/tests/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.py
index 14a4666e7e..fe305b6200 100644
--- a/tests/_runtime/test_dataflow.py
+++ b/tests/_runtime/test_dataflow.py
@@ -227,6 +227,97 @@ def test_register_with_stale_ancestor() -> None:
assert graph.get_stale() == set(["0", "1"])
+def test_topological_sort_single_node() -> None:
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ cell = parse_cell(code)
+ graph.register_cell("0", cell)
+ sorted_cells = dataflow.topological_sort(graph, ["0"])
+ assert sorted_cells == ["0"]
+
+
+def test_topological_sort_linear_chain() -> None:
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "z = y"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ sorted_cells = dataflow.topological_sort(graph, ["0", "1", "2"])
+ assert sorted_cells == ["0", "1", "2"]
+
+
+def test_topological_sort_diamond_dependency() -> None:
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "z = x"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ code = "a = y + z"
+ fourth_cell = parse_cell(code)
+ graph.register_cell("3", fourth_cell)
+
+ sorted_cells = dataflow.topological_sort(graph, ["0", "1", "2", "3"])
+ assert sorted_cells == ["0", "1", "2", "3"]
+
+ sorted_cells = dataflow.topological_sort(graph, ["3", "2", "1", "0"])
+ assert sorted_cells == ["0", "1", "2", "3"]
+
+ # Subset of nodes
+ sorted_cells = dataflow.topological_sort(graph, ["0"])
+ assert sorted_cells == ["0"]
+
+
+def test_topological_sort_with_unrelated_nodes() -> None:
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "a = 0"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ sorted_cells = dataflow.topological_sort(graph, ["0", "1", "2"])
+ assert sorted_cells == ["0", "1", "2"]
+
+ sorted_cells = dataflow.topological_sort(graph, ["2", "1", "0"])
+ assert sorted_cells == ["0", "1", "2"]
+
+
+def test_topological_sort_with_cycle() -> None:
+ graph = dataflow.DirectedGraph()
+ code = "x = y"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ sorted_cells = dataflow.topological_sort(graph, ["0", "1"])
+ assert sorted_cells == []
+
+
@pytest.mark.skipif(not HAS_DUCKDB, reason="duckdb is required")
class TestSQL:
@pytest.mark.parametrize(