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
"""Graph rehydration equivalence: ``GraphBuilder.from_persisted``.
Proves that a builder rehydrated from persisted node/edge/metric rows is
metric- and traversal-equivalent to the originally-built graph — without
running any resolution pass or recomputing centrality. This is the property
the incremental ``repowise update --full`` upgrade relies on.
"""
from __future__ import annotations
from datetime import datetime
from repowise.core.ingestion.graph import GraphBuilder
from repowise.core.ingestion.graph._rehydrate import _NODE_ATTR_KEYS
from repowise.core.ingestion.models import FileInfo, Import, ParsedFile, Symbol
def _fi(path: str) -> FileInfo:
return FileInfo(
path=path,
abs_path=f"/repo/{path}",
language="python",
size_bytes=100,
git_hash="",
last_modified=datetime.now(),
is_test=False,
is_config=False,
is_api_contract=False,
is_entry_point=False,
)
def _imp(module_path: str) -> Import:
return Import(
raw_statement=f"import {module_path}",
module_path=module_path,
imported_names=[],
is_relative=False,
resolved_file=None,
)
def _parsed(path: str, imports: list[Import] | None = None) -> ParsedFile:
return ParsedFile(
file_info=_fi(path),
symbols=[],
imports=imports or [],
exports=[],
docstring=None,
parse_errors=[],
content_hash="",
)
def _build_sample() -> GraphBuilder:
"""a imports b and c; b imports c — a small connected file graph."""
b = GraphBuilder()
b.add_file(_parsed("a.py", [_imp("b"), _imp("c")]))
b.add_file(_parsed("b.py", [_imp("c")]))
b.add_file(_parsed("c.py"))
b.build()
return b
def _serialize(builder: GraphBuilder) -> tuple[list[dict], list[dict]]:
"""Serialize the live graph to the dict shape the SQL readers return.
Mirrors ``persistence.crud.get_all_graph_nodes`` / ``get_all_graph_edges``
so the test exercises the real round-trip contract (note ``parent_name`` is
persisted under the ``parent_symbol_id`` key).
"""
graph = builder.graph()
nodes: list[dict] = []
for node_id, data in graph.nodes(data=True):
row = {"node_id": node_id}
for key in _NODE_ATTR_KEYS:
if key == "parent_symbol_id":
row[key] = data.get("parent_name")
else:
row[key] = data.get(key)
nodes.append(row)
edges: list[dict] = []
for u, v, data in graph.edges(data=True):
edges.append(
{
"source_node_id": u,
"target_node_id": v,
"edge_type": data.get("edge_type", "imports"),
"confidence": data.get("confidence", 1.0),
"imported_names": data.get("imported_names", []),
"hint_source": data.get("hint_source"),
"resolution_origin": data.get("resolution_origin"),
"call_lines": data.get("call_lines", []),
"type_only": bool(data.get("type_only", False)),
}
)
return nodes, edges
def test_rehydrated_metrics_match_original():
original = _build_sample()
nodes, edges = _serialize(original)
metrics = original.file_metrics_snapshot()
hydrated = GraphBuilder.from_persisted(nodes, edges, metrics)
# Finalized, with caches pre-filled — no implicit rebuild on read.
assert hydrated._built is True
assert hydrated._pagerank_cache is not None
assert hydrated.pagerank() == original.pagerank()
assert hydrated.betweenness_centrality() == original.betweenness_centrality()
assert hydrated.community_detection() == original.community_detection()
assert hydrated.in_degree() == original.in_degree()
assert hydrated.out_degree() == original.out_degree()
def test_rehydrated_graph_is_traversal_equivalent():
original = _build_sample()
nodes, edges = _serialize(original)
hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
og = original.graph()
hg = hydrated.graph()
assert og.number_of_nodes() == hg.number_of_nodes()
assert og.number_of_edges() == hg.number_of_edges()
for node in og.nodes:
assert set(og.successors(node)) == set(hg.successors(node))
assert set(og.predecessors(node)) == set(hg.predecessors(node))
# Edge types survive the round-trip.
for succ in og.successors(node):
assert og[node][succ].get("edge_type") == hg[node][succ].get("edge_type")
def test_resolution_origin_survives_rehydration():
"""An edge's origin must outlive the process that resolved it.
The graph is rebuilt from rows on every incremental update, so an origin
that only exists in memory would be present on the indexing run and gone
on every read after it. A row without one stays without one — that is what
lets an index built before the vocabulary keep working unchanged.
"""
original = _build_sample()
nodes, edges = _serialize(original)
edges[0] = {**edges[0], "edge_type": "calls", "resolution_origin": "same_file"}
hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
graph = hydrated.graph()
stamped = graph[edges[0]["source_node_id"]][edges[0]["target_node_id"]]
assert stamped["resolution_origin"] == "same_file"
for e in edges[1:]:
assert "resolution_origin" not in graph[e["source_node_id"]][e["target_node_id"]]
def test_call_lines_survive_rehydration():
original = _build_sample()
nodes, edges = _serialize(original)
edges[0] = {**edges[0], "edge_type": "calls", "call_lines": [7, 11]}
hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
stamped = hydrated.graph()[edges[0]["source_node_id"]][edges[0]["target_node_id"]]
assert stamped["call_lines"] == [7, 11]
def test_rehydrate_without_metrics_falls_back_to_recompute():
"""No snapshot supplied → caches stay empty and metrics recompute on read."""
original = _build_sample()
nodes, edges = _serialize(original)
hydrated = GraphBuilder.from_persisted(nodes, edges, metrics=None)
assert hydrated._pagerank_cache is None # nothing pre-loaded
# Recompute on the rehydrated structure still equals the original.
assert hydrated.pagerank() == original.pagerank()
assert hydrated.in_degree()["c.py"] == 2
def test_supplied_props_survives_rehydration():
"""An edge's supplied_props must outlive the process that resolved it."""
original = _build_sample()
nodes, edges = _serialize(original)
edges[0] = {**edges[0], "edge_type": "calls", "supplied_props": ["showBanner", "isLoaded"]}
hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
graph = hydrated.graph()
stamped = graph[edges[0]["source_node_id"]][edges[0]["target_node_id"]]
assert stamped["supplied_props"] == frozenset(["showBanner", "isLoaded"])
for e in edges[1:]:
assert "supplied_props" not in graph[e["source_node_id"]][e["target_node_id"]]
def test_reachability_root_survives_rehydration():
original = _build_sample()
original.graph().nodes["c.py"]["is_reachability_root"] = True
nodes, edges = _serialize(original)
hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
assert hydrated.graph().nodes["c.py"]["is_reachability_root"] is True
assert not hydrated.graph().nodes["a.py"].get("is_reachability_root")
def test_parse_only_symbol_attrs_come_back_from_the_reparse():
sym = Symbol(
id="a.py::A::f",
name="f",
qualified_name="a.A.f",
kind="method",
signature="f()",
start_line=1,
end_line=2,
docstring=None,
decorators=["@override"],
parent_name="A",
modifiers=("override",),
)
parsed = _parsed("a.py")
parsed.symbols.append(sym)
original = GraphBuilder()
original.add_file(parsed)
original.build()
nodes, edges = _serialize(original)
hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
assert "modifiers" not in hydrated.graph().nodes[sym.id]
hydrated.restore_parse_only_attrs([parsed])
node = hydrated.graph().nodes[sym.id]
assert node["modifiers"] == ("override",)
assert node["decorators"] == ["@override"]
def test_type_only_edges_survive_rehydration_and_suppress_cycles():
builder = GraphBuilder()
builder.add_file(_parsed("a.py", [_imp("b")]))
builder.add_file(_parsed("b.py", [_imp("a")]))
builder.build()
builder.graph()["a.py"]["b.py"]["type_only"] = True
builder.graph()["b.py"]["a.py"]["type_only"] = True
nodes, edges = _serialize(builder)
assert any(e.get("type_only") for e in edges)
hydrated = GraphBuilder.from_persisted(nodes, edges, builder.file_metrics_snapshot())
assert hydrated.graph()["a.py"]["b.py"]["type_only"] is True
assert hydrated.graph()["b.py"]["a.py"]["type_only"] is True
assert hydrated.cycle_subgraph().number_of_edges() == 0