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(update): persist graph_edges on incremental update (#806)
Raghav Chamadiya51ba39bd293e
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 61953d60a..9e3e1be92 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -549,6 +549,19 @@ async def _persist_full_update_async(except Exception as exc:_skip("Symbol persist", exc)+ # Refresh graph_edges for the changed files (delete-then-insert of+ # each file's outgoing edges). Without this, adjacency fossilizes at+ # the last full index and Phase E flow-path answers decay on every+ # incremental update.+ try:+ from repowise.core.pipeline.persist import persist_incremental_edges++ await persist_incremental_edges(+ session, repo_id, graph_builder, parsed_files, [fd.path for fd in file_diffs]+ )+ except Exception as exc:+ _skip("Graph edges persist", exc)+# Record a GenerationJob so the web UI "last synced" timestamp updates.try:from datetime import UTC as _UTCdiff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.pyindex 79e4c47cb..cf1d9e5b9 100644--- a/packages/core/src/repowise/core/persistence/crud/graph.py+++ b/packages/core/src/repowise/core/persistence/crud/graph.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport json-from sqlalchemy import func, select+from sqlalchemy import and_, delete, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom ..models import (@@ -122,6 +122,100 @@ async def batch_upsert_graph_edges()+# Chunk size for the scoped edge delete/existence work — stays under SQLite's+# host-parameter limit when a wide catch-up update touches many files.+_EDGE_RECONCILE_CHUNK = 400+++async def reconcile_edges_for_files(+ session: AsyncSession,+ repository_id: str,+ source_file_paths: list[str],+ edges: list[dict], # fresh edges whose source belongs to those files+) -> int:+ """Make ``graph_edges`` outgoing from *source_file_paths* match a fresh parse.++ Sibling of :func:`reconcile_symbols_for_files` for the edge table. The+ incremental update path rebuilds the in-memory graph, but only the full-init+ path ever persisted edges, so ``graph_edges`` froze at the last full index:+ new imports/calls stayed invisible and edges a changed file dropped lingered+ as false BFS paths (the Phase E flow-path traversal reads adjacency straight+ from this table). This deletes every edge whose source node belongs to one+ of *source_file_paths* — both the file node and its symbol nodes, including+ symbols the change deleted whose node rows the incremental path never prunes+ — then inserts the fresh set. Edges *into* a changed file from an unchanged+ one are owned by that other file and left untouched, the same file-scoping+ the symbol reconciler uses; a full reindex reconciles those.++ Returns the number of deleted rows.+ """+ scoped = [p for p in dict.fromkeys(source_file_paths) if p]+ if not scoped:+ return 0++ # Every graph node owned by a changed file. Pulled from graph_nodes (not+ # just the fresh edge list) so outgoing edges of a symbol the change deleted+ # — whose node row the incremental path leaves behind — are cleared too. A+ # file node keys on node_id == path; a symbol node carries file_path.+ source_ids: set[str] = set()+ for i in range(0, len(scoped), _EDGE_RECONCILE_CHUNK):+ chunk = scoped[i : i + _EDGE_RECONCILE_CHUNK]+ rows = (+ (+ await session.execute(+ select(GraphNode.node_id).where(+ GraphNode.repository_id == repository_id,+ or_(+ and_(+ GraphNode.node_type == "file",+ GraphNode.node_id.in_(chunk),+ ),+ GraphNode.file_path.in_(chunk),+ ),+ )+ )+ )+ .scalars()+ .all()+ )+ source_ids.update(rows)+ # Union in the fresh edges' own sources so a brand-new node's edges are still+ # rewritten cleanly even if the node-row read above raced its insert.+ source_ids.update(e.get("source_node_id", "") for e in edges)+ source_ids.discard("")+ if not source_ids:+ return 0++ id_list = list(source_ids)+ deleted = 0+ for i in range(0, len(id_list), _EDGE_RECONCILE_CHUNK):+ batch = id_list[i : i + _EDGE_RECONCILE_CHUNK]+ res = await session.execute(+ delete(GraphEdge).where(+ GraphEdge.repository_id == repository_id,+ GraphEdge.source_node_id.in_(batch),+ )+ )+ deleted += res.rowcount or 0++ # Every fresh edge's source was just cleared, so these are all plain inserts+ # — no need for the repo-wide upsert (which reloads every edge row).+ for e in edges:+ session.add(+ GraphEdge(+ id=_new_uuid(),+ repository_id=repository_id,+ source_node_id=e.get("source_node_id", ""),+ target_node_id=e.get("target_node_id", ""),+ imported_names_json=e.get("imported_names_json", "[]"),+ edge_type=e.get("edge_type", "imports"),+ confidence=e.get("confidence", 1.0),+ )+ )+ await session.flush()+ return deleted++async def batch_upsert_graph_metrics(session: AsyncSession,repository_id: str,diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 531b4dadc..06093f1d5 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -660,6 +660,20 @@ async def persist_incremental_index(except Exception as exc:_skip("Symbol persist", exc)+ # Refresh graph_edges for the changed files. The full-init path was+ # historically the only writer of edges, so adjacency froze at the+ # last full index: new imports/calls stayed invisible and dropped+ # ones lingered as false paths. Phase E flow-path traversal reads+ # adjacency straight from this table, so it decayed on every update.+ try:+ from repowise.core.pipeline.persist import persist_incremental_edges++ await persist_incremental_edges(+ session, repo_id, graph_builder, parsed_files, changed_paths+ )+ except Exception as exc:+ _skip("Graph edges persist", exc)+if knowledge_graph_result is not None:try:from repowise.core.pipeline.persist import persist_kgdiff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 6f0d42a05..e72299a58 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -302,6 +302,76 @@ async def persist_incremental_symbols(await reconcile_symbols_for_files(session, repo_id, reconcile_paths, symbols)+def _changed_file_edges(+ graph_builder: Any,+ parsed_files: list[Any] | None,+ changed_paths: list[str],+) -> tuple[list[str], list[dict]]:+ """``(reconcile_paths, edges)`` for edges emanating from changed+parsed files.++ An edge is attributed to the file that owns its *source* node: a file node+ is the path itself; a symbol node carries ``file_path``. Restricting to+ files that both changed and parsed this run mirrors ``_changed_file_symbols``+ — a changed file that failed to parse keeps its existing edges rather than+ having them wrongly wiped on a transient failure.+ """+ changed = set(changed_paths or [])+ parsed = {pf.file_info.path for pf in parsed_files or []}+ reconcile = changed & parsed+ if not reconcile:+ return [], []++ graph = graph_builder.graph()+ owner: dict[str, str | None] = {}+ for node_id in graph.nodes:+ data = graph.nodes[node_id]+ owner[node_id] = (+ node_id if data.get("node_type", "file") == "file" else data.get("file_path")+ )++ edges: list[dict] = []+ for u, v, data in graph.edges(data=True):+ if owner.get(u) not in reconcile:+ continue+ edges.append(+ {+ "source_node_id": u,+ "target_node_id": v,+ "imported_names_json": json.dumps(data.get("imported_names", [])),+ "edge_type": data.get("edge_type", "imports"),+ "confidence": data.get("confidence", 1.0),+ }+ )+ return sorted(reconcile), edges+++async def persist_incremental_edges(+ session: Any,+ repo_id: str,+ graph_builder: Any,+ parsed_files: list[Any] | None,+ changed_paths: list[str],+) -> None:+ """Refresh ``graph_edges`` for changed files on an incremental update.++ Sibling of :func:`persist_incremental_symbols`. The full-init path was the+ only one that ever wrote ``graph_edges``; ``repowise update`` rebuilt the+ graph but never repersisted edges, so adjacency froze at the last full+ index. Phase E flow-path answers and any graph expansion read adjacency+ straight from this table, so they decayed on every incremental update. This+ delete-then-inserts the changed files' outgoing edges (dropping edges those+ files no longer have). Scoped to the changed set for cost.+ """+ if graph_builder is None or not parsed_files:+ return+ from repowise.core.persistence.crud import reconcile_edges_for_files++ reconcile_paths, edges = _changed_file_edges(graph_builder, parsed_files, changed_paths)+ if not reconcile_paths:+ return+ await reconcile_edges_for_files(session, repo_id, reconcile_paths, edges)++# Chunk size for IN (...) deletes — stays under SQLite's host-parameter limit._PRUNE_CHUNK = 500diff --git a/tests/unit/persistence/test_incremental_edge_persist.py b/tests/unit/persistence/test_incremental_edge_persist.pynew file mode 100644index 000000000..31b16178d--- /dev/null+++ b/tests/unit/persistence/test_incremental_edge_persist.py@@ -0,0 +1,130 @@+"""Incremental updates must refresh ``graph_edges`` for changed files.++The incremental update path rebuilds the in-memory graph but historically only+the full-init path persisted edges, so ``graph_edges`` froze at the last full+index: a new import stayed invisible and an import a file dropped lingered as a+false adjacency (the Phase E flow-path traversal reads adjacency straight from+this table). These tests drive the real parser + graph builder over a file whose+imports change and assert the persisted edges follow — the added edge appears,+the dropped edge is pruned, and edges owned by unchanged files are left alone.+"""++from __future__ import annotations++import json+from pathlib import Path++from sqlalchemy import select++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.persistence import batch_upsert_graph_edges+from repowise.core.persistence.models import GraphEdge+from repowise.core.pipeline.persist import persist_graph_nodes, persist_incremental_edges+from tests.unit.persistence.helpers import insert_repo+++def _build_graph(repo_dir: Path) -> tuple[GraphBuilder, list]:+ """Parse every file under *repo_dir* and build the ingestion graph."""+ traverser = FileTraverser(repo_dir)+ parser = ASTParser()+ gb = GraphBuilder(repo_dir)+ parsed = []+ for fi in traverser.traverse():+ pf = parser.parse_file(fi, Path(fi.abs_path).read_bytes())+ parsed.append(pf)+ gb.add_file(pf)+ gb.build()+ return gb, parsed+++def _graph_edges(gb: GraphBuilder) -> list[dict]:+ return [+ {+ "source_node_id": u,+ "target_node_id": v,+ "imported_names_json": json.dumps(d.get("imported_names", [])),+ "edge_type": d.get("edge_type", "imports"),+ "confidence": d.get("confidence", 1.0),+ }+ for u, v, d in gb.graph().edges(data=True)+ ]+++async def _db_edge_set(session, repo_id: str) -> set[tuple[str, str, str]]:+ rows = (+ (await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id)))+ .scalars()+ .all()+ )+ return {(r.source_node_id, r.target_node_id, r.edge_type) for r in rows}+++async def _seed_full(session, repo_id: str, gb: GraphBuilder) -> None:+ """Mirror the full-init persist: nodes first, then the whole edge set."""+ await persist_graph_nodes(session, repo_id, gb)+ await batch_upsert_graph_edges(session, repo_id, _graph_edges(gb))+++async def test_incremental_update_reconciles_changed_file_edges(async_session, tmp_path):+ repo = await insert_repo(async_session)++ # v1: b.py imports a.py; d.py imports b.py. c.py stands ready as b's next+ # import target.+ (tmp_path / "a.py").write_text("x = 1\n")+ (tmp_path / "c.py").write_text("y = 2\n")+ (tmp_path / "b.py").write_text("from a import x\n")+ (tmp_path / "d.py").write_text("import b\n")++ gb1, _ = _build_graph(tmp_path)+ await _seed_full(async_session, repo.id, gb1)+ await async_session.commit()++ before = await _db_edge_set(async_session, repo.id)+ # Sanity: the fixture really produced the edges the test reasons about.+ assert ("b.py", "a.py", "imports") in before+ assert ("d.py", "b.py", "imports") in before++ # v2: b.py drops its import of a.py and imports c.py instead.+ (tmp_path / "b.py").write_text("from c import y\n")+ gb2, parsed2 = _build_graph(tmp_path)++ # Nodes are refreshed before edges on the real path; the reconcile reads+ # graph_nodes to scope the delete, so do the same here.+ await persist_graph_nodes(async_session, repo.id, gb2)+ await persist_incremental_edges(async_session, repo.id, gb2, parsed2, ["b.py"])+ await async_session.commit()++ after = await _db_edge_set(async_session, repo.id)+ # The dropped import is gone; the new import is persisted.+ assert ("b.py", "a.py", "imports") not in after+ assert ("b.py", "c.py", "imports") in after+ # An edge owned by an unchanged file (d.py -> b.py) is left untouched.+ assert ("d.py", "b.py", "imports") in after+++async def test_incremental_edge_persist_leaves_unchanged_files_untouched(async_session, tmp_path):+ """Only edges owned by the changed set are rewritten; others keep their rows."""+ repo = await insert_repo(async_session)++ (tmp_path / "a.py").write_text("x = 1\n")+ (tmp_path / "b.py").write_text("from a import x\n")+ (tmp_path / "c.py").write_text("from a import x\n")++ gb1, _ = _build_graph(tmp_path)+ await _seed_full(async_session, repo.id, gb1)+ await async_session.commit()+ before = await _db_edge_set(async_session, repo.id)+ assert ("b.py", "a.py", "imports") in before+ assert ("c.py", "a.py", "imports") in before++ # b.py changes but keeps importing a.py; c.py is not in the changed set.+ (tmp_path / "b.py").write_text("from a import x\ny = x + 1\n")+ gb2, parsed2 = _build_graph(tmp_path)+ await persist_graph_nodes(async_session, repo.id, gb2)+ await persist_incremental_edges(async_session, repo.id, gb2, parsed2, ["b.py"])+ await async_session.commit()++ after = await _db_edge_set(async_session, repo.id)+ # Both survive: b.py re-inserted its (unchanged) edge, c.py was never touched.+ assert ("b.py", "a.py", "imports") in after+ assert ("c.py", "a.py", "imports") in after