Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(graph): read dependency edges, not every edge row, on the graph surfaces (#1531)

Swati Ahuja45f284beace1
diff --git a/packages/core/src/repowise/core/analysis/health/signals.py b/packages/core/src/repowise/core/analysis/health/signals.py
index 4c8484b94..cb966c71a 100644
--- a/packages/core/src/repowise/core/analysis/health/signals.py
+++ b/packages/core/src/repowise/core/analysis/health/signals.py
@@ -154,6 +154,14 @@ def file_signals(
``get_node_degree_counts`` (or ``None`` when the file is not a graph node).
No DB access and no recompute — this is the single join the drawer, the
file page, and MCP all reuse.
+
+ **Pass degrees scoped to** ``FILE_DEPENDENCY_EDGE_TYPES``. The UI states
+ these two fields as "N files depend on this" and "depends on N files", so
+ an unscoped count is a false claim: it adds one per symbol the file
+ declares, plus its co-change partners. Four call sites build this value
+ (the file page, the health drawer, ``get_context`` and ``get_health``), and
+ they render into one panel, so a producer that scopes differently from the
+ others is a visible contradiction rather than a private choice.
"""
g = git_meta
return FileSignals(
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index 36a3cf6fa..de339985a 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -791,24 +791,31 @@ async def get_node_degree_counts(
session: AsyncSession,
repository_id: str,
node_id: str,
+ *,
+ edge_types: list[str] | None = None,
) -> dict[str, int]:
- """Return in-degree and out-degree for a node from edge counts."""
- in_result = await session.execute(
- select(func.count())
- .select_from(GraphEdge)
- .where(
- GraphEdge.repository_id == repository_id,
- GraphEdge.target_node_id == node_id,
- )
+ """Return in-degree and out-degree for a node from edge counts.
+
+ ``edge_types`` narrows the count the same way it narrows
+ :func:`get_graph_edges_for_node`. A caller that presents degree beside a
+ list of neighbours should pass the view it used for that list, or the
+ count and the list describe different graphs — a file's unfiltered
+ in-degree is rendered as "Dependents (N)" above a dependents list, and
+ the two disagreed by the file's own symbol count.
+ """
+ in_q = select(func.count()).select_from(GraphEdge).where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.target_node_id == node_id,
)
- out_result = await session.execute(
- select(func.count())
- .select_from(GraphEdge)
- .where(
- GraphEdge.repository_id == repository_id,
- GraphEdge.source_node_id == node_id,
- )
+ out_q = select(func.count()).select_from(GraphEdge).where(
+ GraphEdge.repository_id == repository_id,
+ GraphEdge.source_node_id == node_id,
)
+ if edge_types:
+ in_q = in_q.where(GraphEdge.edge_type.in_(edge_types))
+ out_q = out_q.where(GraphEdge.edge_type.in_(edge_types))
+ in_result = await session.execute(in_q)
+ out_result = await session.execute(out_q)
return {
"in_degree": in_result.scalar() or 0,
"out_degree": out_result.scalar() or 0,
@@ -819,6 +826,8 @@ async def get_node_degree_counts_bulk(
session: AsyncSession,
repository_id: str,
node_ids: list[str],
+ *,
+ edge_types: list[str] | None = None,
) -> dict[str, dict[str, int]]:
"""Return ``node_id -> {in_degree, out_degree}`` for many nodes at once.
@@ -826,6 +835,10 @@ async def get_node_degree_counts_bulk(
count per direction). Callers that need degrees for a set of files were
otherwise forced into an N+1.
+ ``edge_types`` narrows the count exactly as it does in
+ :func:`get_node_degree_counts`. The two must stay in step: they are the
+ single and bulk halves of one question, and both feed ``file_signals``.
+
A node absent from the graph is absent from the result, mirroring
``get_graph_node`` returning ``None``: consumers distinguish "not a graph
node" (no entry) from "a node with no edges" (``{0, 0}``), and collapsing
@@ -855,14 +868,13 @@ async def get_node_degree_counts_bulk(
(GraphEdge.source_node_id, "out_degree"),
):
for i in range(0, len(present), _BATCH_SIZE):
- rows = await session.execute(
- select(column, func.count())
- .where(
- GraphEdge.repository_id == repository_id,
- column.in_(present[i : i + _BATCH_SIZE]),
- )
- .group_by(column)
+ q = select(column, func.count()).where(
+ GraphEdge.repository_id == repository_id,
+ column.in_(present[i : i + _BATCH_SIZE]),
)
+ if edge_types:
+ q = q.where(GraphEdge.edge_type.in_(edge_types))
+ rows = await session.execute(q.group_by(column))
for node_id, count in rows.all():
counts[node_id][key] = count or 0
return counts
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 7ddc43645..7ca642442 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -16,7 +16,10 @@ from sqlalchemy import distinct, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import file_signals
-from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES
+from repowise.core.ingestion.models import (
+ FILE_DEPENDENCY_EDGE_TYPES,
+ SYMBOL_USE_EDGE_TYPES,
+)
from repowise.core.persistence.crud import (
get_all_file_metrics,
get_community_members,
@@ -56,6 +59,11 @@ _MIN_CALL_CONFIDENCE = 0.7
# still right: hand-trimming a member here is how the private sets started.
_CALL_EDGE_TYPES = sorted(SYMBOL_USE_EDGE_TYPES)
+# Degree reported for a FILE. `file_signals` states it as "N files depend on
+# this", so it is counted over file dependencies rather than every adjacent
+# row, which would add one per symbol the file declares.
+_FILE_DEPENDENCY_EDGE_TYPES = sorted(FILE_DEPENDENCY_EDGE_TYPES)
+
def _unique_by_symbol(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Collapse entries sharing a ``symbol_id``, keeping the first.
@@ -332,7 +340,18 @@ async def _resolve_metrics(
except (json.JSONDecodeError, TypeError):
meta = {}
- degrees = await get_node_degree_counts(session, repo_id, node.node_id)
+ # Scoped by layer, because "degree" means a different edge set on each: a
+ # file's neighbours are files, a symbol's are symbols. Unscoped, a symbol's
+ # in-degree always counted the containment edge from its own declaring file
+ # or class, and a file's out-degree counted one edge per symbol it declares.
+ degrees = await get_node_degree_counts(
+ session,
+ repo_id,
+ node.node_id,
+ edge_types=(
+ _CALL_EDGE_TYPES if node.node_type == "symbol" else _FILE_DEPENDENCY_EDGE_TYPES
+ ),
+ )
# Percentile computation against same-type peers
all_nodes = await get_all_file_metrics(session, repo_id)
@@ -517,7 +536,11 @@ async def _resolve_health(
git_meta = await get_git_metadata(session, repo_id, file_path)
node = await get_graph_node(session, repo_id, file_path)
degrees = (
- await get_node_degree_counts(session, repo_id, file_path) if node is not None else None
+ await get_node_degree_counts(
+ session, repo_id, file_path, edge_types=_FILE_DEPENDENCY_EDGE_TYPES
+ )
+ if node is not None
+ else None
)
signals = {k: v for k, v in asdict(file_signals(git_meta, degrees)).items() if v is not None}
if signals:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
index 0adbcd98e..749abd64b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py
@@ -101,7 +101,7 @@ async def get_dependency_path(source: str, target: str, repo: str | None = None)
graph.add_edge(
e.source_node_id,
e.target_node_id,
- edge_type=getattr(e, "edge_type", None) or "imports",
+ edge_type=e.edge_type,
)
if source not in graph:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 447c9c981..33f6ffcca 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -20,6 +20,7 @@ from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_f
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
from repowise.core.analysis.health.trends import diff_snapshots, file_trend, recent_kpis
+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence.crud import (
get_all_git_metadata,
get_coverage_summary,
@@ -1229,7 +1230,10 @@ async def get_health(
session, repository.id, list(effective_targets)
)
degrees_by_path = await get_node_degree_counts_bulk(
- session, repository.id, list(effective_targets)
+ session,
+ repository.id,
+ list(effective_targets),
+ edge_types=sorted(FILE_DEPENDENCY_EDGE_TYPES),
)
for path in effective_targets:
signals_by_path[path] = asdict(
diff --git a/packages/server/src/repowise/server/routers/code_health/loaders.py b/packages/server/src/repowise/server/routers/code_health/loaders.py
index ea89958cc..effc165a2 100644
--- a/packages/server/src/repowise/server/routers/code_health/loaders.py
+++ b/packages/server/src/repowise/server/routers/code_health/loaders.py
@@ -6,6 +6,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import FileSignals, file_signals
+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence import crud
from repowise.core.persistence.models import WikiSymbol
@@ -20,7 +21,11 @@ async def _load_file_signals(session: AsyncSession, repo_id: str, file_path: str
git_meta = await crud.get_git_metadata(session, repo_id, file_path)
node = await crud.get_graph_node(session, repo_id, file_path)
degrees = (
- await crud.get_node_degree_counts(session, repo_id, file_path) if node is not None else None
+ await crud.get_node_degree_counts(
+ session, repo_id, file_path, edge_types=sorted(FILE_DEPENDENCY_EDGE_TYPES)
+ )
+ if node is not None
+ else None
)
return file_signals(git_meta, degrees)
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index af6f1cc6c..8fcd9e210 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -21,6 +21,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.trends import file_trend
from repowise.core.ids import is_external
+from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence import crud
from repowise.core.persistence.decision_graph import get_governing_decisions
from repowise.core.persistence.models import DeadCodeFinding, Page, WikiSymbol
@@ -197,9 +198,16 @@ async def file_detail(
metrics = await crud.get_health_metrics(session, repo_id, file_paths=[file_path])
metric = metrics[0] if metrics else None
# Degree is read once (graph node only) and shared by the health-signals
- # block below and the graph-context block further down.
+ # block below and the graph-context block further down. Scoped to file
+ # dependencies because both places state it as one: the signals panel
+ # renders it as "N files depend on this", and the graph panel as
+ # "Dependents (N)" above the dependents list.
degrees = (
- await crud.get_node_degree_counts(session, repo_id, file_path) if node is not None else None
+ await crud.get_node_degree_counts(
+ session, repo_id, file_path, edge_types=sorted(FILE_DEPENDENCY_EDGE_TYPES)
+ )
+ if node is not None
+ else None
)
if node is None and git_meta is None and metric is None:
@@ -282,8 +290,18 @@ async def file_detail(
all_files = await crud.get_all_file_metrics(session, repo_id)
assert degrees is not None # node is not None here, so degrees was loaded
meta = parse_community_meta(node)
+ # Dependencies only. Unfiltered, this served the file's own `defines`
+ # edges as "dependencies", so a file depended on its own functions —
+ # and since the limit is per direction and the query has no ORDER BY,
+ # a file with more symbols than the limit could return containment
+ # rows and none of its real imports.
edges = await crud.get_graph_edges_for_node(
- session, repo_id, file_path, direction="both", limit=40
+ session,
+ repo_id,
+ file_path,
+ direction="both",
+ edge_types=sorted(FILE_DEPENDENCY_EDGE_TYPES),
+ limit=40,
)
neighbor_ids = {
e.source_node_id if e.source_node_id != file_path else e.target_node_id for e in edges
diff --git a/packages/server/src/repowise/server/routers/graph/intelligence.py b/packages/server/src/repowise/server/routers/graph/intelligence.py
index 9892664d2..7925a134f 100644
--- a/packages/server/src/repowise/server/routers/graph/intelligence.py
+++ b/packages/server/src/repowise/server/routers/graph/intelligence.py
@@ -6,6 +6,10 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.ingestion.models import (
+ FILE_DEPENDENCY_EDGE_TYPES,
+ SYMBOL_USE_EDGE_TYPES,
+)
from repowise.core.persistence import crud
from repowise.core.persistence.models import GraphNode
from repowise.server.deps import get_db_session
@@ -48,7 +52,20 @@ async def get_graph_metrics(
all_pr = [n.pagerank or 0.0 for n in all_files]
all_bw = [n.betweenness or 0.0 for n in all_files]
- degrees = await crud.get_node_degree_counts(session, repo_id, node_id)
+ # Scoped by layer. This endpoint feeds the same symbol component as
+ # /api/symbols/detail (the drawer, where that page is the drill-down), so
+ # an unscoped count here made one symbol report two different degrees
+ # depending on which of the two the user opened.
+ degrees = await crud.get_node_degree_counts(
+ session,
+ repo_id,
+ node_id,
+ edge_types=(
+ sorted(SYMBOL_USE_EDGE_TYPES)
+ if node.node_type == "symbol"
+ else sorted(FILE_DEPENDENCY_EDGE_TYPES)
+ ),
+ )
meta = parse_community_meta(node)
return GraphMetricsResponse(
@@ -149,7 +166,7 @@ async def get_callers_callees(
if other
else (other_id.split("::")[0] if "::" in other_id else other_id),
start_line=other.start_line if other else None,
- edge_type=e.edge_type or "calls",
+ edge_type=e.edge_type,
confidence=round(e.confidence or 0.0, 3),
)
diff --git a/packages/server/src/repowise/server/routers/graph/neighborhoods.py b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
index 52c3ebc19..b7a07ecd1 100644
--- a/packages/server/src/repowise/server/routers/graph/neighborhoods.py
+++ b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
from repowise.core.persistence.models import (
DeadCodeFinding,
GitMetadata,
@@ -49,7 +50,16 @@ async def ego_graph(
except ImportError:
raise HTTPException(status_code=501, detail="networkx not available") from None
- edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
+ # Temporal edges are excluded from the traversal for the reason
+ # `get_dependency_path` gives: a co-change edge is history, not a
+ # reference, so it makes an unrelated file a 1-hop neighbour. Containment
+ # stays — it is the only bridge from the file layer to the symbol layer.
+ edge_result = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.edge_type.notin_(TEMPORAL_EDGE_TYPES),
+ )
+ )
edges = edge_result.scalars().all()
graph: nx.DiGraph = nx.DiGraph()
@@ -67,6 +77,10 @@ async def ego_graph(
raise HTTPException(status_code=404, detail=f"Node '{node_id}' not found")
graph.add_node(node_id)
+ # Counted on the graph this endpoint returns rather than from the edge
+ # rows, so a temporal edge cannot inflate it. Not identical to the length
+ # of `links`: nx.DiGraph collapses a pair joined by two edge types (an
+ # `imports` and a `type_use` to the same file) into one arc.
inbound_count = graph.in_degree(node_id)
outbound_count = graph.out_degree(node_id)
@@ -122,7 +136,15 @@ async def entry_points_graph(
except ImportError:
raise HTTPException(status_code=501, detail="networkx not available") from None
- edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
+ # Same exclusion as /ego, and it matters more here: this walks three hops
+ # from every entry point, so one co-change edge pulls its whole
+ # neighbourhood into "reachable from an entry point".
+ edge_result = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.edge_type.notin_(TEMPORAL_EDGE_TYPES),
+ )
+ )
edges = edge_result.scalars().all()
graph: nx.DiGraph = nx.DiGraph()
diff --git a/packages/server/src/repowise/server/routers/graph/path.py b/packages/server/src/repowise/server/routers/graph/path.py
index dec462628..4c197afc8 100644
--- a/packages/server/src/repowise/server/routers/graph/path.py
+++ b/packages/server/src/repowise/server/routers/graph/path.py
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
from repowise.core.persistence.models import GraphEdge, GraphNode
from repowise.server.deps import get_db_session
from repowise.server.routers.graph._common import with_repo
@@ -26,7 +27,24 @@ async def dependency_path(
When no direct path exists, returns visual context with nearest common
ancestors, shared neighbors, and bridge suggestions.
"""
- edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
+ # Drop the temporal relation only — the same rule the MCP twin
+ # (`get_dependency_path`) applies, for the same reasons. A ``co_changes``
+ # edge records that two files move together in history, so leaving it in
+ # makes it a free hop and this endpoint reports a "dependency path" no
+ # code creates.
+ #
+ # Containment stays, unlike in the consumers that answer "what depends on
+ # this file". ``defines`` is the only bridge from the file layer to the
+ # symbol layer, and no edge points back the other way, so excluding it
+ # cannot suppress a false file-to-file path — there is none to suppress —
+ # while it does delete the real ones: a --defines--> a::foo --calls-->
+ # b::bar is how a caller asks which file reaches a function.
+ edge_result = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.edge_type.notin_(TEMPORAL_EDGE_TYPES),
+ )
+ )
edges = edge_result.scalars().all()
node_result = await session.execute(select(GraphNode).where(GraphNode.repository_id == repo_id))
@@ -40,6 +58,10 @@ async def dependency_path(
) from None
graph: nx.DiGraph = nx.DiGraph()
+ # Seed every indexed node, not just the endpoints of surviving edges. A
+ # file whose only edges were temporal is still indexed, so building from
+ # edges alone made the 404 below untrue for it.
+ graph.add_nodes_from(n.node_id for n in nodes)
for e in edges:
graph.add_edge(e.source_node_id, e.target_node_id)
diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.py
index 094508677..4412ab792 100644
--- a/packages/server/src/repowise/server/routers/symbols.py
+++ b/packages/server/src/repowise/server/routers/symbols.py
@@ -10,6 +10,7 @@ from sqlalchemy import func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.signals import iso_utc
+from repowise.core.ingestion.models import SYMBOL_USE_EDGE_TYPES
from repowise.core.persistence import crud
from repowise.core.persistence.decision_graph import get_governing_decisions
from repowise.core.persistence.models import (
@@ -391,13 +392,21 @@ async def symbol_detail(
)
[symbol] = await _attach_blame(session, repo_id, [symbol])
- # Callers/callees from the symbol graph (call + heritage edges).
+ # Callers/callees from the symbol graph. The filter is what makes the
+ # comment true: unfiltered, a symbol's inbound containment edge — from its
+ # own declaring file or class, which 34,570 of 34,808 symbols on this repo
+ # have — was served as a caller.
callers: list[dict] = []
callees: list[dict] = []
node = await crud.get_graph_node(session, repo_id, symbol_id)
if node is not None:
edges = await crud.get_graph_edges_for_node(
- session, repo_id, symbol_id, direction="both", limit=40
+ session,
+ repo_id,
+ symbol_id,
+ direction="both",
+ edge_types=sorted(SYMBOL_USE_EDGE_TYPES),
+ limit=40,
)
other_ids = {
e.source_node_id if e.source_node_id != symbol_id else e.target_node_id for e in edges
@@ -417,15 +426,20 @@ async def symbol_detail(
if other and other.file_path
else (other_id.split("::")[0] if "::" in other_id else other_id),
"start_line": other.start_line if other else None,
- "edge_type": e.edge_type or "calls",
+ "edge_type": e.edge_type,
"confidence": round(e.confidence or 0.0, 3),
}
(callers if inbound else callees).append(entry)
callers.sort(key=lambda x: (-x["confidence"], x["name"]))
callees.sort(key=lambda x: (-x["confidence"], x["name"]))
+ # Scoped to the same edges as `callers`/`callees`, which sit beside these
+ # two in one `graph` object. Unscoped, every symbol's in-degree carried the
+ # containment edge from its own declaring file or class.
degrees = (
- await crud.get_node_degree_counts(session, repo_id, symbol_id)
+ await crud.get_node_degree_counts(
+ session, repo_id, symbol_id, edge_types=sorted(SYMBOL_USE_EDGE_TYPES)
+ )
if node is not None
else {"in_degree": 0, "out_degree": 0}
)
diff --git a/packages/server/src/repowise/server/services/c4_builder/architecture.py b/packages/server/src/repowise/server/services/c4_builder/architecture.py
index 8c788e1b3..4b37454ec 100644
--- a/packages/server/src/repowise/server/services/c4_builder/architecture.py
+++ b/packages/server/src/repowise/server/services/c4_builder/architecture.py
@@ -450,9 +450,22 @@ async def build_architecture_view(
edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
all_edges: list[GraphEdge] = list(edge_result.scalars())
+ # The edges this view actually returns. Degree is counted from the same
+ # list the arrows are drawn from: counting every row instead made one
+ # response disagree with itself, because a file's out-degree included the
+ # `defines` edge to each symbol it declares and none of those are shown
+ # when symbols are excluded.
+ view_edges = [
+ e
+ for e in all_edges
+ if (include_symbols or e.edge_type not in _SYMBOL_EDGE_TYPES)
+ and e.source_node_id in node_id_set
+ and e.target_node_id in node_id_set
+ ]
+
in_degree: dict[str, int] = defaultdict(int)
out_degree: dict[str, int] = defaultdict(int)
- for e in all_edges:
+ for e in view_edges:
out_degree[e.source_node_id] += 1
in_degree[e.target_node_id] += 1
@@ -588,16 +601,12 @@ async def build_architecture_view(
# -- Build ArchEdges --
arch_edges: list[ArchEdge] = []
- for e in all_edges:
- if not include_symbols and e.edge_type in _SYMBOL_EDGE_TYPES:
- continue
- if e.source_node_id not in node_id_set or e.target_node_id not in node_id_set:
- continue
+ for e in view_edges:
arch_edges.append(
ArchEdge(
source=e.source_node_id,
target=e.target_node_id,
- edge_type=e.edge_type or "imports",
+ edge_type=e.edge_type,
direction="forward",
weight=e.confidence,
confidence=e.confidence,
diff --git a/packages/server/src/repowise/server/services/c4_builder/relations.py b/packages/server/src/repowise/server/services/c4_builder/relations.py
index e07cbe66d..778629fc5 100644
--- a/packages/server/src/repowise/server/services/c4_builder/relations.py
+++ b/packages/server/src/repowise/server/services/c4_builder/relations.py
@@ -32,7 +32,7 @@ from .models import Relation
async def load_edges(
session: AsyncSession, repository_id: str
-) -> list[tuple[str, str, str | None]]:
+) -> list[tuple[str, str, str]]:
"""Read every graph edge once, as ``(source, target, type)`` rows.
Split out so a caller rolling the same edges up several ways — by
@@ -53,7 +53,7 @@ async def aggregate_relations(
file_to_box: dict[str, str],
*,
file_to_external: dict[str, str] | None = None,
- edges: list[tuple[str, str, str | None]] | None = None,
+ edges: list[tuple[str, str, str]] | None = None,
) -> list[Relation]:
"""Roll file→file edges up to box→box edges.
@@ -72,6 +72,14 @@ async def aggregate_relations(
if edges is None:
edges = await load_edges(session, repository_id)
+ # No edge-type filter here, and that is deliberate rather than an
+ # oversight. ``file_to_box`` is keyed on file paths only, so a containment
+ # edge cannot survive the two lookups below: ``defines`` is file → symbol
+ # and loses its target, ``has_method`` is symbol → symbol and loses its
+ # source. Measured across the 41 indexed corpus repos, excluding
+ # containment changes no relation, no count and no coupling band on any of
+ # them. Temporal edges do survive, and a "co-changes" arrow is a labeled
+ # relation this view means to draw (see ``_EDGE_VERB``), not leakage.
counts: dict[tuple[str, str], int] = defaultdict(int)
types: dict[tuple[str, str], set[str]] = defaultdict(set)
@@ -89,7 +97,7 @@ async def aggregate_relations(
continue
key = (src_box, tgt_box)
counts[key] += 1
- types[key].add(etype or "imports")
+ types[key].add(etype)
relations: list[Relation] = []
for (src_box, tgt_box), count in counts.items():
diff --git a/packages/server/src/repowise/server/services/zoom_builder/relations.py b/packages/server/src/repowise/server/services/zoom_builder/relations.py
index 5ccbd3399..5e6440d88 100644
--- a/packages/server/src/repowise/server/services/zoom_builder/relations.py
+++ b/packages/server/src/repowise/server/services/zoom_builder/relations.py
@@ -79,7 +79,7 @@ def aggregate_relations(
continue
key = (parent, child_a, child_b)
counts[key] += 1
- types[key].add(etype or "imports")
+ types[key].add(etype)
relations: list[ZoomRelation] = []
for (parent, child_a, child_b), count in counts.items():
diff --git a/tests/unit/server/test_graph_edge_filtering.py b/tests/unit/server/test_graph_edge_filtering.py
new file mode 100644
index 000000000..1817e177a
--- /dev/null
+++ b/tests/unit/server/test_graph_edge_filtering.py
@@ -0,0 +1,274 @@
+"""The graph-reading REST surfaces must read dependency edges, not every row.
+
+Four endpoints loaded ``graph_edges`` with no filter and presented the result
+as dependencies. The table also carries containment (``defines`` is file →
+symbol, ``has_method`` is class → member) and the temporal ``co_changes``
+relation, so:
+
+* a file's "dependencies" list contained the file's own functions;
+* a symbol's "callers" list contained the file that declares it;
+* ``/path`` reported a dependency path across a co-change hop, the same defect
+ ``get_dependency_path`` was fixed for in #1470 — its nine-line comment did
+ not travel to the REST twin;
+* ``/ego`` made a co-change partner a one-hop neighbour.
+
+The degree numbers are covered too, because each is rendered beside the list it
+disagreed with: the file page prints ``in_degree`` as "Dependents (N)" directly
+above the dependents list.
+"""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GraphEdge, GraphNode, WikiSymbol
+from tests.unit.server.conftest import create_test_repo
+
+_FILE = "src/app/service.py"
+_OTHER = "src/app/repo.py"
+_PARTNER = "docs/changelog.md"
+_SYMBOL = "src/app/service.py::Service"
+_METHOD = "src/app/service.py::Service.run"
+_CALLER = "src/app/repo.py::load"
+
+
+async def _seed(session_factory, repo_id: str) -> None:
+ """One file with a symbol, one real import, one co-change partner.
+
+ Deliberately minimal: every edge below is one of the three kinds under
+ test, so a failure names the kind rather than a fixture.
+ """
+ async with get_session(session_factory) as session:
+ for node_id, node_type in (
+ (_FILE, "file"),
+ (_OTHER, "file"),
+ (_PARTNER, "file"),
+ (_SYMBOL, "symbol"),
+ (_METHOD, "symbol"),
+ (_CALLER, "symbol"),
+ ):
+ session.add(
+ GraphNode(
+ repository_id=repo_id,
+ node_id=node_id,
+ node_type=node_type,
+ language="python",
+ pagerank=0.1,
+ file_path=node_id.split("::")[0] if node_type == "symbol" else None,
+ name=node_id.split("::")[-1] if node_type == "symbol" else None,
+ )
+ )
+ # /api/symbols/detail resolves the symbol row first, so the graph node
+ # alone is not enough to reach the callers block under test.
+ for symbol_id, name, kind in (
+ (_SYMBOL, "Service", "class"),
+ (_METHOD, "run", "method"),
+ ):
+ session.add(
+ WikiSymbol(
+ repository_id=repo_id,
+ file_path=_FILE,
+ symbol_id=symbol_id,
+ name=name,
+ qualified_name=name,
+ kind=kind,
+ language="python",
+ )
+ )
+ for src, tgt, etype in (
+ (_FILE, _OTHER, "imports"), # the one real dependency
+ (_FILE, _SYMBOL, "defines"), # containment, file -> symbol
+ (_FILE, _PARTNER, "co_changes"), # temporal
+ (_CALLER, _SYMBOL, "calls"), # the one real caller
+ (_SYMBOL, _METHOD, "has_method"), # containment, class -> member
+ (_CALLER, _METHOD, "calls"), # the method's one real caller
+ ):
+ session.add(
+ GraphEdge(
+ repository_id=repo_id,
+ source_node_id=src,
+ target_node_id=tgt,
+ imported_names_json="[]",
+ edge_type=etype,
+ )
+ )
+
+
+async def test_a_file_does_not_depend_on_its_own_symbols(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/files/{_FILE}")
+ assert resp.status_code == 200
+ graph = resp.json()["graph"]
+
+ deps = [d["node_id"] for d in graph["dependencies"]]
+ assert _SYMBOL not in deps, f"file depends on its own symbol: {deps}"
+ assert _PARTNER not in deps, f"co-change partner served as a dependency: {deps}"
+ assert deps == [_OTHER]
+
+
+async def test_the_file_dependent_count_matches_the_dependent_list(
+ client: AsyncClient, app
+) -> None:
+ """The UI prints this count as "Dependents (N)" above that list."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/files/{_FILE}")
+ graph = resp.json()["graph"]
+
+ assert graph["out_degree"] == len(graph["dependencies"])
+ assert graph["in_degree"] == len(graph["dependents"])
+
+
+async def test_the_two_degree_blocks_on_the_file_response_agree(
+ client: AsyncClient, app
+) -> None:
+ """One response carries this number twice, under two different keys.
+
+ ``health.signals`` renders as "N files depend on this" and ``graph`` as
+ "Dependents (N)". They are built by different helpers, so scoping one and
+ not the other makes a single page contradict itself.
+ """
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/files/{_FILE}")
+ body = resp.json()
+
+ assert body["health"]["signals"]["out_degree"] == body["graph"]["out_degree"]
+ assert body["health"]["signals"]["in_degree"] == body["graph"]["in_degree"]
+ # And the shared value is the dependency one, not every adjacent row.
+ assert body["graph"]["out_degree"] == 1
+
+
+async def test_symbol_degree_agrees_between_the_page_and_the_drawer(
+ client: AsyncClient, app
+) -> None:
+ """``/graph/{repo}/metrics`` feeds the drawer, ``/symbols/detail`` the page.
+
+ Both render through one component, so one symbol must not report two
+ different degrees depending on which the user opened.
+ """
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ page = await client.get(
+ "/api/symbols/detail", params={"repo_id": repo["id"], "symbol_id": _SYMBOL}
+ )
+ drawer = await client.get(
+ f"/api/graph/{repo['id']}/metrics", params={"node_id": _SYMBOL}
+ )
+ assert page.status_code == 200
+ assert drawer.status_code == 200
+
+ assert drawer.json()["in_degree"] == page.json()["graph"]["in_degree"]
+ assert drawer.json()["out_degree"] == page.json()["graph"]["out_degree"]
+ assert drawer.json()["in_degree"] == 1 # the caller, not the declaring file
+
+
+async def test_a_symbols_declaring_file_is_not_a_caller(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(
+ "/api/symbols/detail", params={"repo_id": repo["id"], "symbol_id": _SYMBOL}
+ )
+ assert resp.status_code == 200
+ graph = resp.json()["graph"]
+
+ callers = [c["symbol_id"] for c in graph["callers"]]
+ assert _FILE not in callers, f"declaring file served as a caller: {callers}"
+ assert callers == [_CALLER]
+ assert graph["in_degree"] == len(callers)
+
+
+async def test_a_methods_declaring_class_is_not_a_caller(
+ client: AsyncClient, app
+) -> None:
+ """The ``has_method`` half of containment, class -> member."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(
+ "/api/symbols/detail", params={"repo_id": repo["id"], "symbol_id": _METHOD}
+ )
+ assert resp.status_code == 200
+ graph = resp.json()["graph"]
+
+ callers = [c["symbol_id"] for c in graph["callers"]]
+ assert _SYMBOL not in callers, f"declaring class served as a caller: {callers}"
+ assert callers == [_CALLER]
+
+
+async def test_rest_path_does_not_walk_a_co_change_hop(
+ client: AsyncClient, app
+) -> None:
+ """The REST twin of the MCP tool fixed in #1470."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(
+ f"/api/graph/{repo['id']}/path", params={"from": _FILE, "to": _PARTNER}
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+
+ assert body["path"] == [], f"co_changes walked as a dependency: {body['path']}"
+ # Shortest-path must be what rejected the hop. If the node had instead
+ # fallen out of the graph the endpoint would 404, which would pass a
+ # naive "no path" assertion for entirely the wrong reason.
+ assert "not found in graph" not in (body.get("explanation") or "")
+
+
+async def test_path_still_resolves_through_the_symbol_layer(
+ client: AsyncClient, app
+) -> None:
+ """``defines`` is the only bridge from a file to its symbols.
+
+ Nothing points from a symbol back to a file, so excluding containment
+ cannot suppress a false file-to-file path — it only deletes the real
+ file -> symbol answer.
+ """
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(
+ f"/api/graph/{repo['id']}/path", params={"from": _FILE, "to": _SYMBOL}
+ )
+ assert resp.status_code == 200
+ assert resp.json()["path"] == [_FILE, _SYMBOL]
+
+
+async def test_ego_graph_excludes_a_co_change_partner(
+ client: AsyncClient, app
+) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(
+ f"/api/graph/{repo['id']}/ego", params={"node_id": _FILE, "hops": 1}
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+
+ node_ids = {n["node_id"] for n in body["nodes"]}
+ assert _PARTNER not in node_ids, "co-change partner is not a graph neighbour"
+ assert _OTHER in node_ids
+ assert body["outbound_count"] == 2 # imports + defines, not the co-change