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(graph): no file self-loops in the graph or in PageRank (#2677)
Swati Ahuja84a99c4fe6fc
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.pyindex 0d346e945..9a1bef8ed 100644--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py@@ -133,7 +133,9 @@ class EdgesMixin:def add_dynamic_edges(self, edges: list) -> None:"""Add dynamic-hint edges to the graph. Each edge is a DynamicEdge."""for e in edges:- if e.source not in self._graph:+ # A hint naming its own file (a package.json exporting+ # "./package.json") is not a dependency.+ if e.source not in self._graph or e.source == e.target:continueif e.target not in self._graph:if self._exclude.patterns and self._exclude.match_file(e.target):@@ -161,9 +163,9 @@ class EdgesMixin:# every `src/lib.rs` with an inline `mod tests` was marked a test# file wholesale and dropped from dead-code analysis, the knowledge# graph and key-concept selection (#1103). The marker means "contains- # tests", not "is a test": it stays recorded on this edge's- # ``hint_source``, where it says that and nothing more. Health- # computes the file-level version itself, from the source, as+ # tests", not "is a test", and as a file → same-file hint it is now+ # dropped by the self-loop guard above. Health computes the+ # file-level version itself, from the source, as# ``FileContext.has_inline_tests``.if edges:self._invalidate_subgraph_caches()diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.pyindex c45c0a1f5..f41b4ec0f 100644--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py@@ -113,10 +113,12 @@ class MetricsMixin:if d.get("node_type", "file") in ("file", "external")]sub = g.subgraph(file_nodes).copy()+ # A file never depends on itself; a self-loop only feeds PageRank+ # the node's own rank back to it.edges_to_remove = [(u, v)for u, v, d in sub.edges(data=True)- if d.get("edge_type") in TEMPORAL_EDGE_TYPES+ if u == v or d.get("edge_type") in TEMPORAL_EDGE_TYPES]sub.remove_edges_from(edges_to_remove)self._file_subgraph_cache = subdiff --git a/tests/fixtures/node_pkg_self_export/package.json b/tests/fixtures/node_pkg_self_export/package.jsonnew file mode 100644index 000000000..cd28be828--- /dev/null+++ b/tests/fixtures/node_pkg_self_export/package.json@@ -0,0 +1,9 @@+{+ "name": "self-export",+ "version": "1.0.0",+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js",+ "./package.json": "./package.json"+ }+}diff --git a/tests/fixtures/node_pkg_self_export/src/helper.js b/tests/fixtures/node_pkg_self_export/src/helper.jsnew file mode 100644index 000000000..9222eadae--- /dev/null+++ b/tests/fixtures/node_pkg_self_export/src/helper.js@@ -0,0 +1,5 @@+function helper() {+ return 1;+}++module.exports = { helper };diff --git a/tests/fixtures/node_pkg_self_export/src/index.js b/tests/fixtures/node_pkg_self_export/src/index.jsnew file mode 100644index 000000000..567b77221--- /dev/null+++ b/tests/fixtures/node_pkg_self_export/src/index.js@@ -0,0 +1,3 @@+const { helper } = require("./helper");++module.exports = { run: () => helper() };diff --git a/tests/unit/ingestion/test_file_self_loops.py b/tests/unit/ingestion/test_file_self_loops.pynew file mode 100644index 000000000..0c16b3ade--- /dev/null+++ b/tests/unit/ingestion/test_file_self_loops.py@@ -0,0 +1,63 @@+"""A file never depends on itself: no file-node self-loop survives a build.++A package.json that exports itself (``"./package.json": "./package.json"``,+common so tools can read the manifest) used to become a package.json →+package.json edge, and PageRank fed the node its own rank.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.dynamic_hints import HintRegistry+from repowise.core.ingestion.dynamic_hints.node import NodeDynamicHints++FIXTURES = Path(__file__).parent.parent.parent / "fixtures"+++def _build(repo: Path) -> GraphBuilder:+ builder = GraphBuilder(repo_path=repo)+ parser = ASTParser()+ paths = []+ for fi in FileTraverser(repo).traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ paths.append(fi.path)+ builder.build()+ builder.add_dynamic_edges(+ HintRegistry().extract_all(repo, dotnet_index=builder.dotnet_index, file_paths=paths)+ )+ return builder+++def _file_self_loops(g) -> list[str]:+ return [+ u+ for u, v in g.edges()+ if u == v and g.nodes[u].get("node_type", "file") in ("file", "external")+ ]+++def test_self_export_adds_no_self_loop_and_no_pagerank_lift() -> None:+ repo = FIXTURES / "node_pkg_self_export"+ hinted = {(e.source, e.target) for e in NodeDynamicHints().extract(repo)}+ # The fixture really does produce the self-export hint the builder must drop.+ assert ("package.json", "package.json") in hinted+ builder = _build(repo)+ assert builder.graph().has_edge("package.json", "src/index.js")+ assert _file_self_loops(builder.graph()) == []+ assert _file_self_loops(builder.file_subgraph()) == []+ pr = builder.pagerank()+ # The manifest only points out; with no inbound edge it must not outrank+ # the entry file it points at.+ assert pr["package.json"] < pr["src/index.js"]++[email protected]("fixture", ["sample_repo", "ts_sample", "go_sample"])+def test_no_file_self_loops_after_build(fixture: str) -> None:+ builder = _build(FIXTURES / fixture)+ assert builder.graph().number_of_nodes() > 0+ assert _file_self_loops(builder.graph()) == []+ assert _file_self_loops(builder.file_subgraph()) == []diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.pyindex bed80d342..d8f3a93e0 100644--- a/tests/unit/ingestion/test_graph.py+++ b/tests/unit/ingestion/test_graph.py@@ -962,8 +962,10 @@ class TestInlineTestHintDoesNotMarkFileAsTest:gb.add_dynamic_edges([self._test_edge("src/lib.rs")])assert gb._graph.nodes["src/lib.rs"]["is_test"] is False- def test_the_hint_is_still_recorded_on_the_edge(self):+ def test_the_hint_adds_no_file_self_loop(self):+ # The marker names the file itself, so it is not a dependency: a+ # self-loop would only feed the file's own PageRank back to it.gb = GraphBuilder("/tmp/fake")gb._graph.add_node("src/lib.rs", is_test=False)gb.add_dynamic_edges([self._test_edge("src/lib.rs")])- assert gb._graph.edges["src/lib.rs", "src/lib.rs"]["hint_source"] == "rust:test"+ assert not gb._graph.has_edge("src/lib.rs", "src/lib.rs")