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(risk): read dependency edges only, so a co-change partner is not an import (#1462)
Raghav Chamadiyae292bc7b20e0
diff --git a/packages/core/src/repowise/core/analysis/pr_blast.py b/packages/core/src/repowise/core/analysis/pr_blast.pyindex 05977804c..2031d3217 100644--- a/packages/core/src/repowise/core/analysis/pr_blast.py+++ b/packages/core/src/repowise/core/analysis/pr_blast.py@@ -23,6 +23,7 @@ from typing import Anyfrom sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.ingestion.models import NON_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.models import GitMetadata, GraphNode@@ -137,10 +138,21 @@ class PRBlastRadiusAnalyzer:"""BFS over reverse graph edges (source_node_id -> target_node_id direction).We want files that *import* the changed files (i.e. are affected when a- changed file changes). In graph_edges, an edge means+ changed file changes). In graph_edges, a dependency edge means``source imports target``, so we look for rows where``target_node_id IN (frontier)`` and collect the ``source_node_id``values — those are the files that depend on our changed set.++ Not every row is a dependency edge, though, which is what the sentence+ above used to assume. ``co_changes`` rows live in the same table, so an+ unfiltered BFS treated "these two files tend to change together" as+ "this file imports that one" and walked through it, then walked+ through *that* file's co-change partners at the next depth. On this+ repository a PR touching ``core/__init__.py`` reached five co-change+ rows and two real importers at depth 1, and since ``will_break`` is+ capped at five and sorted by depth, the noise crowded out the answer.+ Those partners are already reported, correctly labelled, by+ :meth:`_cochange_warnings`."""visited: dict[str, int] = {} # path -> depth at which it was first reachedfrontier = list(set(changed_files))@@ -150,13 +162,16 @@ class PRBlastRadiusAnalyzer:break# SQLite / SQLAlchemy compatible IN query via text()placeholders = ",".join(f":p{i}" for i in range(len(frontier)))+ excluded = ",".join(f":e{i}" for i in range(len(NON_DEPENDENCY_EDGE_TYPES)))params: dict[str, Any] = {"repo_id": self._repo_id}params.update({f"p{i}": v for i, v in enumerate(frontier)})+ params.update({f"e{i}": v for i, v in enumerate(sorted(NON_DEPENDENCY_EDGE_TYPES))})rows = await self._session.execute(text(f"SELECT DISTINCT source_node_id FROM graph_edges "f"WHERE repository_id = :repo_id "- f"AND target_node_id IN ({placeholders})"+ f"AND target_node_id IN ({placeholders}) "+ f"AND edge_type NOT IN ({excluded})"),params,)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 5a1596d5f..dddc7777b 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -272,6 +272,20 @@ EdgeType = Literal["type_use",]+# Edge types that are *not* code dependencies, and so must be excluded by any+# consumer answering "what depends on this?".+#+# ``defines`` (file → symbol) and ``has_method`` / ``has_property``+# (class symbol → member symbol) are containment: a file "depends on" the+# symbols it declares only in a sense nobody asks about.+# ``co_changes`` is temporal: evidence that two files move together in history,+# not evidence that one references the other. It is also the one that bites,+# because a co-change edge fed back in as a dependency makes every co-change+# partner look like an import of its own subject.+NON_DEPENDENCY_EDGE_TYPES: frozenset[str] = frozenset(+ {"defines", "has_method", "has_property", "co_changes"}+)+@dataclassclass TypeReference:diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 8bf7500e4..ab2c3fe01 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -6,6 +6,7 @@ import asynciofrom sqlalchemy import select+from repowise.core.ingestion.models import NON_DEPENDENCY_EDGE_TYPESfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (GitMetadata,@@ -77,10 +78,16 @@ async def get_risk(repository = await _get_repo(session)repo_id = repository.id- # Pre-load edges+ # Pre-load edges. Dependency edges only: everything below reads these as+ # "X depends on Y", and the graph also carries containment and co-change+ # edges. Leaving co_changes in made the relation circular: a co-change+ # partner was fed back in as an import link, so every partner that+ # cleared the count floor was annotated ``(imports)``, including the+ # markdown and JSON files that are graph nodes but import nothing.res = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id,+ GraphEdge.edge_type.notin_(NON_DEPENDENCY_EDGE_TYPES),))all_edges = res.scalars().all()diff --git a/tests/unit/server/mcp/test_risk_dependency_edges.py b/tests/unit/server/mcp/test_risk_dependency_edges.pynew file mode 100644index 000000000..439a3929e--- /dev/null+++ b/tests/unit/server/mcp/test_risk_dependency_edges.py@@ -0,0 +1,112 @@+"""``get_risk`` must read dependency edges only.++The graph carries more than code dependencies: file-to-symbol containment+(``defines`` / ``has_method``) and the temporal ``co_changes`` relation live in+the same table. ``get_risk`` pre-loaded every edge for the repository and fed+all of them into ``dep_counts`` / ``import_links`` / ``reverse_deps``.++Feeding ``co_changes`` back in made the relation circular. A co-change partner+that cleared the count floor became its own subject's "import link", so the CLI+annotated it ``(imports)``, including markdown and JSON files, which are graph+nodes but import nothing. Containment edges inflated ``dependents_count`` by one+per symbol the file declares.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime++import pytest+from sqlalchemy import select++from repowise.core.persistence.models import GitMetadata, GraphEdge++_TARGET = "src/auth/service.py"+_DOC = "docs/auth-flow.md"+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)+++async def _add_doc_co_change(factory, repo_id: str) -> None:+ """A doc that moves with the target but imports nothing, wired the way the+ pipeline wires it: a partner entry plus a ``co_changes`` graph edge."""+ async with factory() as s:+ meta = (+ await s.execute(select(GitMetadata).where(GitMetadata.file_path == _TARGET))+ ).scalar_one()+ partners = json.loads(meta.co_change_partners_json)+ partners.append({"file_path": _DOC, "count": 9})+ meta.co_change_partners_json = json.dumps(partners)+ s.add(+ GraphEdge(+ id="ge-cochange",+ repository_id=repo_id,+ source_node_id=_TARGET,+ target_node_id=_DOC,+ imported_names_json="[]",+ edge_type="co_changes",+ created_at=_NOW,+ )+ )+ await s.commit()+++async def test_co_change_partner_is_not_an_import_link(setup_mcp, factory):+ from repowise.server.mcp_server import get_risk++ await _add_doc_co_change(factory, setup_mcp)++ result = await get_risk([_TARGET])+ partners = {p["file_path"]: p for p in result["targets"][_TARGET]["co_change_partners"]}++ assert partners[_DOC]["has_import_link"] is False+ # The real importer still reads as one, so the filter has not blanked the+ # annotation altogether.+ assert partners["src/auth/middleware.py"]["has_import_link"] is True+++async def test_co_change_partner_is_not_blast_radius(setup_mcp, factory):+ """PR mode walks the same table with its own raw-SQL BFS.++ ``_transitive_affected`` collects the sources of every edge pointing at a+ changed file and calls them "affected". A co_changes row made a file that+ merely tends to change alongside the diff look like an importer of it, and+ the next BFS depth then walked through *that* file's partners. will_break+ is capped and depth-sorted, so the noise crowds out the real importers.+ """+ from repowise.server.mcp_server import get_risk++ await _add_doc_co_change(factory, setup_mcp)++ result = await get_risk([_TARGET], changed_files=[_DOC])+ affected = {+ e.get("path") for e in (result.get("pr_blast_radius") or {}).get("transitive_affected", [])+ }++ # service.py co-changes with the doc; it does not import it.+ assert _TARGET not in affected+++async def test_containment_edges_are_not_dependents(setup_mcp, factory):+ from repowise.server.mcp_server import get_risk++ async with factory() as s:+ s.add(+ GraphEdge(+ id="ge-defines",+ repository_id=setup_mcp,+ source_node_id=_TARGET,+ target_node_id=f"{_TARGET}::AuthService",+ imported_names_json="[]",+ edge_type="defines",+ created_at=_NOW,+ )+ )+ await s.commit()++ before = await get_risk([f"{_TARGET}::AuthService"])+ # A symbol a file declares is not a file that depends on that symbol.+ assert before["targets"][f"{_TARGET}::AuthService"]["dependents_count"] == 0