Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix: start reported dependency cycles at the smallest node id (#4513)
Muhamad Raza Haiderbde0ca3aa1e1
diff --git a/packages/core/src/repowise/core/workspace/cycles.py b/packages/core/src/repowise/core/workspace/cycles.pyindex 815ed3213..57ec80879 100644--- a/packages/core/src/repowise/core/workspace/cycles.py+++ b/packages/core/src/repowise/core/workspace/cycles.py@@ -119,14 +119,31 @@ def _cycle(return DependencyCycle(nodes=list(nodes), edge_ids=edge_ids, leg_kinds=leg_kinds)+def _canonical_rotation(nodes: list[str]) -> list[str]:+ """Rotate the cycle so the lexicographically smallest service id starts it.++ NetworkX's ``simple_cycles`` begins each cycle at whatever node its own+ iteration order lands on, which follows set iteration order and therefore+ varies with PYTHONHASHSEED. A cycle is the same loop regardless of where+ the rotation starts, so normalising the start node makes the reported+ ``nodes``, ``edge_ids`` and ``leg_kinds`` identical on every run.+ """+ if not nodes:+ return nodes+ start = nodes.index(min(nodes))+ return nodes[start:] + nodes[:start]++def detect_cycles(graph: SystemGraph) -> tuple[list[DependencyCycle], int]:"""Return the structural dependency cycles in *graph*, and how many exist.Cycles are ordered shortest-first (the tightest loops are the most- actionable), then lexicographically for stability. The returned list is- capped at :data:`MAX_CYCLES`; the second element is the true count before- that cap, so a caller reporting "N cycles" cannot accidentally report the- cap instead. Returns ``([], 0)`` when the structural subgraph is acyclic or+ actionable), then lexicographically for stability. Every cycle is rotated+ to start at its smallest node id, so the same graph always produces the+ same cycles regardless of hash seed. The returned list is capped at+ :data:`MAX_CYCLES`; the second element is the true count before that cap,+ so a caller reporting "N cycles" cannot accidentally report the cap+ instead. Returns ``([], 0)`` when the structural subgraph is acyclic orNetworkX is unavailable."""adjacency = graph.adjacency()@@ -146,7 +163,7 @@ def detect_cycles(graph: SystemGraph) -> tuple[list[DependencyCycle], int]:cycles: list[DependencyCycle] = []try:for raw in nx.simple_cycles(digraph):- cycle = _cycle(raw, adjacency)+ cycle = _cycle(_canonical_rotation(raw), adjacency)if cycle.edge_ids:cycles.append(cycle)except Exception: # pragma: no cover - defensivediff --git a/tests/unit/workspace/test_conformance.py b/tests/unit/workspace/test_conformance.pyindex 726b134e8..044a60468 100644--- a/tests/unit/workspace/test_conformance.py+++ b/tests/unit/workspace/test_conformance.py@@ -197,6 +197,27 @@ def test_longer_cycle():assert cycles[0].length == 3+def test_cycles_start_at_smallest_node_id():+ # Regression test for #4507: nx.simple_cycles begins each cycle at whatever+ # node its iteration order lands on (varies with PYTHONHASHSEED). Every+ # rotation of the same loop must canonicalize to the same cycle, so the+ # loop printed by `repowise workspace check` and the `cycles` in+ # conformance.json never change between runs on the same graph.+ import networkx as nx++ g = _graph(+ [_node("b"), _node("c"), _node("a")],+ [_edge("a", "b"), _edge("b", "c"), _edge("c", "a")],+ )+ for rotation in (["a", "b", "c"], ["b", "c", "a"], ["c", "a", "b"]):+ with patch.object(nx, "simple_cycles", return_value=[rotation]):+ (cycle,), total = detect_cycles(g)+ assert cycle.nodes == ["a", "b", "c"]+ assert cycle.edge_ids == ["a->b:http", "b->c:http", "c->a:http"]+ assert cycle.leg_kinds == [["http"], ["http"], ["http"]]+ assert total == 1++def test_acyclic_graph_has_no_cycles():g = _graph([_node("a"), _node("b"), _node("c")],