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(init): prune graph edges and nodes absent from a full re-index (#4406) (#4510)

Aman4b884f393bdc
diff --git a/packages/core/src/repowise/core/pipeline/persist/__init__.py b/packages/core/src/repowise/core/pipeline/persist/__init__.py
index 772422fa1..d62aa41b9 100644
--- a/packages/core/src/repowise/core/pipeline/persist/__init__.py
+++ b/packages/core/src/repowise/core/pipeline/persist/__init__.py
@@ -51,6 +51,7 @@ from .graph import (
persist_incremental_edges,
persist_incremental_symbols,
persist_symbol_analysis,
+ prune_absent_graph_rows,
stamp_edges_parser_fingerprint,
)
from .health import (
diff --git a/packages/core/src/repowise/core/pipeline/persist/graph.py b/packages/core/src/repowise/core/pipeline/persist/graph.py
index 864159b95..1f09a36ed 100644
--- a/packages/core/src/repowise/core/pipeline/persist/graph.py
+++ b/packages/core/src/repowise/core/pipeline/persist/graph.py
@@ -363,6 +363,90 @@ def _edge_row(source: str, target: str, data: dict) -> dict:
}
+async def prune_absent_graph_rows(
+ session: Any,
+ repo_id: str,
+ node_ids: set[str],
+ edge_rows: list[dict],
+) -> tuple[int, int]:
+ """Delete this repo's ``graph_edges`` / ``graph_nodes`` the fresh graph lacks.
+
+ :func:`persist_graph_nodes` and :func:`batch_upsert_graph_edges` only
+ upsert, so a full re-index over an existing store kept every row an earlier
+ run wrote: an import removed from source stayed visible to MCP callers /
+ dependents, flow paths and change health, and a superseded
+ ``external:...`` target sat beside its resolved edge. Full runs only: the
+ authority is "absent from this run's complete graph", the same rule as
+ :func:`_prune_stale_file_rows`. Incremental updates use the file-scoped
+ reconcilers instead and never call this.
+
+ Runs in the caller's session, so the prune commits or rolls back together
+ with the upsert it follows. Edges go before nodes (no FK cascade between
+ the tables). An empty graph is treated as a broken run and prunes nothing,
+ matching the rest of the full-run pruning.
+
+ Returns ``(edges_deleted, nodes_deleted)``.
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.persistence.models import GraphEdge, GraphNode
+
+ if not node_ids:
+ return 0, 0
+
+ fresh_edges = {
+ (r["source_node_id"], r["target_node_id"], r.get("edge_type", "imports")) for r in edge_rows
+ }
+
+ # Diff in Python so each IN (...) is bounded by the stale set, not the whole
+ # repo (SQLite host-parameter limit) — same approach as _prune_stale_file_rows.
+ edge_rows_db = (
+ await session.execute(
+ select(
+ GraphEdge.id,
+ GraphEdge.source_node_id,
+ GraphEdge.target_node_id,
+ GraphEdge.edge_type,
+ ).where(GraphEdge.repository_id == repo_id)
+ )
+ ).all()
+ stale_edge_ids = [
+ edge_id
+ for edge_id, source, target, edge_type in edge_rows_db
+ if (source, target, edge_type) not in fresh_edges
+ ]
+ for i in range(0, len(stale_edge_ids), _PRUNE_CHUNK):
+ await session.execute(
+ delete(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.id.in_(stale_edge_ids[i : i + _PRUNE_CHUNK]),
+ )
+ )
+
+ node_rows_db = (
+ await session.execute(
+ select(GraphNode.id, GraphNode.node_id).where(GraphNode.repository_id == repo_id)
+ )
+ ).all()
+ stale_node_ids = [row_id for row_id, node_id in node_rows_db if node_id not in node_ids]
+ for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):
+ await session.execute(
+ delete(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.id.in_(stale_node_ids[i : i + _PRUNE_CHUNK]),
+ )
+ )
+
+ if stale_edge_ids or stale_node_ids:
+ logger.info(
+ "graph_rows_full_prune",
+ repo_id=repo_id,
+ edges=len(stale_edge_ids),
+ nodes=len(stale_node_ids),
+ )
+ return len(stale_edge_ids), len(stale_node_ids)
+
+
async def _edges_predate_cohesion(session: Any, repo_id: str, graph_builder: Any) -> bool:
"""True when ``graph_edges`` was written before edge cohesion was recorded.
@@ -442,15 +526,9 @@ async def stamp_edges_parser_fingerprint(session: Any, repo_id: str, fingerprint
"""Record the parser build that just wrote this repo's ``graph_edges``.
Written by :func:`persist_incremental_edges` after a widen, and by the full
- :func:`persist_ingestion` path only when the store held no edges before it.
- That path upserts edges (:func:`batch_upsert_graph_edges`) and prunes only
- the nodes of files that vanished, so a re-index over an existing store adds
- the new build's edges without removing the old build's surplus ones.
- Stamping such a store would mark it parser-current and permanently suppress
- the delete-then-insert reconcile that is the only thing which clears them;
- it stays unstamped, and the first update widens. A fresh store has no
- surplus, so it is stamped: unstamped, the next parser change could not be
- told apart from "already up to date" on a quiet checkout.
+ :func:`persist_ingestion` path after it has pruned the store down to the
+ fresh graph (:func:`prune_absent_graph_rows`). Either way the table holds
+ exactly the running build's edges, so it is parser-current.
"""
from sqlalchemy import update
@@ -562,7 +640,9 @@ async def _prune_vanished_symbol_nodes(
)
)
await session.execute(
- delete(GraphNode).where(GraphNode.repository_id == repo_id, GraphNode.node_id.in_(batch))
+ delete(GraphNode).where(
+ GraphNode.repository_id == repo_id, GraphNode.node_id.in_(batch)
+ )
)
if stale:
logger.info("graph_nodes_parser_prune", repo_id=repo_id, nodes=len(stale))
diff --git a/packages/core/src/repowise/core/pipeline/persist/ingestion.py b/packages/core/src/repowise/core/pipeline/persist/ingestion.py
index 8eb6c879c..b9fce2389 100644
--- a/packages/core/src/repowise/core/pipeline/persist/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/persist/ingestion.py
@@ -10,7 +10,7 @@ import structlog
# ``repowise.core.pipeline.persist`` reaches this module too.
from repowise.core.pipeline import persist as _persist
-from .graph import _edge_row, has_graph_edges, stamp_edges_parser_fingerprint
+from .graph import _edge_row, prune_absent_graph_rows, stamp_edges_parser_fingerprint
logger = structlog.get_logger("repowise.core.pipeline.persist")
@@ -21,6 +21,8 @@ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
Every write here is an idempotent UPSERT keyed by ``(repo_id, …)``, so
this is safe to call incrementally (per phase) and to re-run on resume.
+ Graph nodes and edges are then pruned to the fresh graph, which is always
+ the complete graph here (the incremental update path does not call this).
Returns the number of symbols written (for the summary log). Mutates
``sym.file_path`` on symbols that lack one — callers should treat the
@@ -54,13 +56,17 @@ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
# ---- Graph edges ---------------------------------------------------------
graph = result.graph_builder.graph()
edges = [_edge_row(u, v, data) for u, v, data in graph.edges(data=True)]
- fresh_store = not await has_graph_edges(session, repo_id)
if edges:
await batch_upsert_graph_edges(session, repo_id, edges)
- if fresh_store:
- from repowise.core.ingestion.parse_cache import parser_fingerprint
-
- await stamp_edges_parser_fingerprint(session, repo_id, parser_fingerprint())
+ # The upserts above never delete, so drop this repo's rows the fresh graph no
+ # longer has (a removed import, a re-resolved ``external:`` target, a renamed
+ # symbol). Same session, so it lands in the same transaction as the upsert.
+ await prune_absent_graph_rows(session, repo_id, set(graph.nodes), edges)
+ # The store now holds exactly this build's graph, whatever it held before, so
+ # it is parser-current and can be stamped.
+ from repowise.core.ingestion.parse_cache import parser_fingerprint
+
+ await stamp_edges_parser_fingerprint(session, repo_id, parser_fingerprint())
# ---- External systems (C4 L1) -------------------------------------------
# Persist before symbols so the FK linkage step below sees the IDs.
diff --git a/tests/unit/persistence/test_incremental_edge_persist.py b/tests/unit/persistence/test_incremental_edge_persist.py
index ce1dbd64f..73ba98362 100644
--- a/tests/unit/persistence/test_incremental_edge_persist.py
+++ b/tests/unit/persistence/test_incremental_edge_persist.py
@@ -20,7 +20,7 @@ from sqlalchemy import select
from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
from repowise.core.ingestion.parse_cache import parser_fingerprint
from repowise.core.persistence import batch_upsert_graph_edges
-from repowise.core.persistence.models import GraphEdge, Repository
+from repowise.core.persistence.models import GraphEdge, GraphNode, Repository
from repowise.core.pipeline.persist import (
persist_graph_nodes,
persist_incremental_edges,
@@ -301,13 +301,12 @@ async def test_index_into_a_fresh_store_stamps_the_parser(async_session, tmp_pat
assert await _stored_fingerprint(async_session, repo.id) == parser_fingerprint()
-async def test_full_reindex_does_not_suppress_the_widen(async_session, tmp_path):
- """A re-index must not mark a store parser-current — it cannot clear surplus edges.
+async def test_full_reindex_prunes_surplus_edges_and_stamps(async_session, tmp_path):
+ """A full re-index leaves exactly the fresh graph behind, so it can stamp.
- ``persist_ingestion`` upserts edges and prunes only vanished files' nodes,
- so re-indexing an old store adds the new build's edges while leaving the old
- build's wrong ones behind. If it stamped the fingerprint, the widen — the
- only path that deletes those — would never run again for that store.
+ ``persist_ingestion`` used to upsert only, so re-indexing an old store kept
+ the old build's wrong edges. It now prunes them in the same transaction, and
+ because nothing surplus remains the store is parser-current.
"""
repo = await insert_repo(async_session)
(tmp_path / "a.py").write_text("x = 1\n")
@@ -333,7 +332,6 @@ async def test_full_reindex_does_not_suppress_the_widen(async_session, tmp_path)
await async_session.commit()
assert ("c.py", "a.py", "imports") in await _db_edge_set(async_session, repo.id)
- # A full re-index on the new build: every edge rewritten, none deleted.
await persist_ingestion(
SimpleNamespace(
parsed_files=parsed,
@@ -346,14 +344,73 @@ async def test_full_reindex_does_not_suppress_the_widen(async_session, tmp_path)
repo.id,
)
await async_session.commit()
- # The surplus edge survived the re-index, and the store is still unstamped.
+
+ assert ("c.py", "a.py", "imports") not in await _db_edge_set(async_session, repo.id)
+ assert await _db_edge_set(async_session, repo.id) == {
+ (u, v, d.get("edge_type", "imports")) for u, v, d in gb.graph().edges(data=True)
+ }
+ assert await _stored_fingerprint(async_session, repo.id) == parser_fingerprint()
+
+
+async def test_full_reindex_deletes_removed_edge_and_node(async_session, tmp_path):
+ """Issue #4406: re-persisting a graph minus one edge and one node drops both 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")
+
+ def _view(gb, parsed):
+ return SimpleNamespace(
+ parsed_files=parsed,
+ graph_builder=gb,
+ external_systems=[],
+ execution_flow_report=None,
+ source_map={},
+ )
+
+ gb1, parsed1 = _build_graph(tmp_path)
+ await persist_ingestion(_view(gb1, parsed1), async_session, repo.id)
+ await async_session.commit()
+ assert ("b.py", "a.py", "imports") in await _db_edge_set(async_session, repo.id)
assert ("c.py", "a.py", "imports") in await _db_edge_set(async_session, repo.id)
- assert await _stored_fingerprint(async_session, repo.id) == "older-parser-build"
- # So the next update still widens, and that is what clears it.
- await persist_incremental_edges(async_session, repo.id, gb, parsed, ["b.py"])
+ # b.py drops its import; c.py disappears from the graph entirely.
+ (tmp_path / "b.py").write_text("y = 2\n")
+ (tmp_path / "c.py").unlink()
+ gb2, parsed2 = _build_graph(tmp_path)
+ await persist_ingestion(_view(gb2, parsed2), async_session, repo.id)
await async_session.commit()
- assert ("c.py", "a.py", "imports") not in await _db_edge_set(async_session, repo.id)
+
+ edges = await _db_edge_set(async_session, repo.id)
+ assert ("b.py", "a.py", "imports") not in edges
+ assert ("c.py", "a.py", "imports") not in edges
+ node_ids = set(
+ (
+ await async_session.execute(
+ select(GraphNode.node_id).where(GraphNode.repository_id == repo.id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert "c.py" not in node_ids
+ assert node_ids == set(gb2.graph().nodes)
+
+
+async def test_full_reindex_with_empty_graph_prunes_nothing(async_session, tmp_path):
+ """An empty graph means a broken run; it must not wipe the stored graph."""
+ 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")
+ gb, _parsed = _build_graph(tmp_path)
+ await _seed_full(async_session, repo.id, gb)
+ await async_session.commit()
+ before = await _db_edge_set(async_session, repo.id)
+
+ from repowise.core.pipeline.persist import prune_absent_graph_rows
+
+ assert await prune_absent_graph_rows(async_session, repo.id, set(), []) == (0, 0)
+ assert await _db_edge_set(async_session, repo.id) == before
async def test_a_registration_edge_follows_the_decorated_file(async_session, tmp_path):
@@ -369,11 +426,13 @@ async def test_a_registration_edge_follows_the_decorated_file(async_session, tmp
edge = ("reg.py::rule", "b.py::_check", "references")
assert edge not in await _db_edge_set(async_session, repo.id)
- for text, expected in ((plain.replace("def _check", "@rule\ndef _check"), True), (plain, False)):
+ for text, expected in (
+ (plain.replace("def _check", "@rule\ndef _check"), True),
+ (plain, False),
+ ):
(tmp_path / "b.py").write_text(text)
gb, parsed = _build_graph(tmp_path)
await persist_graph_nodes(async_session, repo.id, gb)
await persist_incremental_edges(async_session, repo.id, gb, parsed, ["b.py"])
await async_session.commit()
assert (edge in await _db_edge_set(async_session, repo.id)) is expected
-