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): prune deleted files, and stop a degraded run stranding its range (#1377)
Raghav Chamadiyaf83a03a6b334
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex ad2c9b0a7..afa05f46e 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -730,6 +730,39 @@ def run_update(emitter.error(message)raise click.ClickException(message)+ # Re-cover a range a previous update failed to fully persist. The pointer+ # advanced past it anyway (so every other reader stays current), and the+ # marker is what stops that from stranding the range's data forever. An+ # explicit --since is the user naming their own base and wins outright.+ #+ # Index-only only, because that is the pointer the marker is written+ # against. In docs mode ``base_ref`` is ``last_docs_commit``, which+ # normally trails ``last_sync_commit``, so the marker would read as a+ # *descendant* of the base and be given up on as "no longer part of this+ # branch's history" — dropping a valid repair and saying something untrue+ # about why. Left alone here, it is repaired by the next index-only run.+ if since is None and resolved_index_only:+ from .persistence import resolve_repair_base++ repaired_ref, give_up = resolve_repair_base(repo_path, state, base_ref, head)+ if give_up is not None:+ console.print(+ f"[yellow]Dropping the pending repair of an earlier update: {give_up}. "+ "Run [bold]repowise init --force[/bold] to rebuild the index.[/yellow]"+ )+ # Dropped in memory only. Writing it here would persist state on a+ # --dry-run, and would do it before the single-flight lock below,+ # where a concurrent update is exactly what the lock exists to+ # stop. Every save_state past the lock carries the cleared marker+ # because they all build on this dict.+ state.pop("pending_repair", None)+ elif repaired_ref != base_ref:+ console.print(+ f"[dim]Re-covering commits an earlier update did not finish "+ f"persisting (from {repaired_ref[:8]}).[/dim]"+ )+ base_ref = repaired_ref+# A config.yaml / health-rules.json change warrants a full health re-score# even when git is unchanged. A missing prior fingerprint is backfilled, not# treated as a change. ``config_changed`` gates every "nothing to do" path.@@ -1002,6 +1035,15 @@ def run_update("config_fingerprint": curr_config_fp,"renderer_fingerprint": curr_renderer_fp,}+ # base_ref has already been widened to any unrepaired range by this+ # point, so no changed files means the range holds nothing left to+ # re-cover. Clearing here is also what stops a marker whose range is+ # permanently empty from being carried, and re-announced, forever.+ # Gated exactly as the widening above is: with --since or in docs mode+ # this base is a different range that says nothing about the marker's,+ # and clearing on it would drop a repair that never happened.+ if since is None and resolved_index_only:+ persisted.pop("pending_repair", None)if not resolved_index_only and head:persisted["last_docs_commit"] = headsave_state(repo_path, persisted)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex bedbd3cb0..58d3a65e7 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -237,6 +237,112 @@ def heal_commit_offsets(repo_path: Any) -> None:run_async(_run())+# A repair window that has grown past this many commits stopped being a repair+# and became a re-index: the diff it forces every update to walk is no longer+# change-sized. Bounding it is what stops a step that fails on every run from+# pinning the window open forever.+_REPAIR_MAX_COMMITS = 500+++def record_repair_marker(new_state: dict, prior_state: dict, failed_steps: list[str]) -> None:+ """Record, or clear, the commit range this update failed to fully persist.++ ``last_sync_commit`` advances whether or not the persist steps succeeded, so+ a failed step used to take its commit range with it: nothing ever revisited+ those commits, and their git metadata, health rows, symbols or edges were+ skipped permanently and announced exactly once in the completion panel. The+ marker keeps the *old* pointer so the next update diffs from there and+ re-covers the range, while the pointer itself stays current for every other+ reader of the state file.++ Carrying the oldest unrepaired commit forward rather than the newest is the+ part that makes it hold: three failed runs in a row still have to re-cover+ all three ranges, not just the last one.++ Only range-scoped failures land here (see ``persist_incremental_index``),+ so a repo-wide step that fails on every single run cannot keep the marker+ alive: it heals itself on the next update instead.+ """+ if not failed_steps:+ new_state.pop("pending_repair", None)+ return+ prior = prior_state.get("pending_repair")+ if not isinstance(prior, dict): # a hand-edited or truncated state file+ prior = {}+ from_commit = prior.get("from_commit") or prior_state.get("last_sync_commit")+ if not from_commit:+ # Nothing to diff back to (a first index, or a state file with no+ # pointer). Widening from an unknown base is not something we can do+ # safely, so leave no marker rather than a broken one.+ new_state.pop("pending_repair", None)+ return+ # Union, not replace: the marker names one range, so it has to name+ # everything still unrepaired in it. Run 1 failing the git persist and run 2+ # failing only the health persist leaves both unrepaired over the same span.+ prior_steps = prior.get("steps")+ prior_steps = prior_steps if isinstance(prior_steps, list) else []+ new_state["pending_repair"] = {+ "from_commit": from_commit,+ "steps": sorted({*prior_steps, *failed_steps}),+ }+++def resolve_repair_base(+ repo_path: Any, state: dict, base_ref: str, head: str | None+) -> tuple[str, str | None]:+ """Widen *base_ref* back to an unrepaired range, or report giving up on it.++ Returns ``(base_ref, give_up_reason)``. The reason is non-None exactly when+ the marker should be dropped without being honoured, and it is written for+ the user rather than the log.++ Three things have to hold before the marker is honoured, and each one closes+ a way this could go wrong:++ * the recorded commit still resolves and is an *ancestor* of the current+ base, so honouring it can only ever move the diff backwards. Without the+ ancestry check a rebase, a branch switch or a docs-mode base that is+ already older would let the marker move the base *forward* and skip the+ very commits it exists to re-cover;+ * the range is still bounded (see ``_REPAIR_MAX_COMMITS``);+ * it differs from the base we already have, so a marker that has effectively+ caught up costs nothing.+ """+ import subprocess++ marker = state.get("pending_repair")+ from_commit = marker.get("from_commit") if isinstance(marker, dict) else None+ if not from_commit or from_commit == base_ref:+ return base_ref, None++ def _git(*args: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ ["git", "-C", str(repo_path), *args], capture_output=True, timeout=30, text=True+ )++ try:+ if _git("merge-base", "--is-ancestor", from_commit, base_ref).returncode != 0:+ # Non-zero covers both "not an ancestor" (rebased, force-pushed,+ # branch switched) and "cannot resolve that object" (gc'd, or a+ # shallow clone that never fetched it), and git does not+ # distinguish them by exit code. Say both rather than assert one.+ return base_ref, (+ f"the recorded commit {from_commit[:8]} is not an ancestor of this "+ "branch's history, or is not present in this clone"+ )+ counted = _git("rev-list", "--count", f"{from_commit}..{head or 'HEAD'}")+ if counted.returncode == 0 and int(counted.stdout.strip() or 0) > _REPAIR_MAX_COMMITS:+ return base_ref, (+ f"the range has grown past {_REPAIR_MAX_COMMITS} commits, which is "+ "a re-index rather than a repair"+ )+ except Exception:+ # git being unavailable is not a reason to widen blindly.+ return base_ref, None++ return from_commit, None++def _persist_index_only_update(repo_path: Any,graph_builder: Any,@@ -273,6 +379,10 @@ def _persist_index_only_update(from repowise.core.pipeline.incremental import persist_incremental_indexdegraded = degraded if degraded is not None else []+ # Failures whose input was this commit range, kept apart from ``degraded``+ # (which also collects repo-wide and non-DB failures) because only these+ # strand data the advancing sync pointer would otherwise skip forever.+ failed_steps: list[str] = []run_async(persist_incremental_index(repo_path,@@ -287,6 +397,7 @@ def _persist_index_only_update(git_decay_map=git_decay_map,log=console.print,degraded=degraded,+ failed_steps=failed_steps,))from repowise.cli.helpers import config_fingerprint@@ -325,6 +436,15 @@ def _persist_index_only_update(# here is exactly the cost the mode exists to avoid."renderer_fingerprint": _current_renderer_fingerprint(repo_path),}+ # Before save_state, and reading ``state`` (the pre-update dict) for the old+ # pointer: this is what keeps a degraded run recoverable now that the+ # pointer below advances to head regardless.+ record_repair_marker(new_state, state, failed_steps)+ if failed_steps:+ console.print(+ "[yellow]Some data for this commit range was not persisted; "+ "the next update will re-cover it.[/yellow]"+ )if "last_docs_commit" not in state and "last_sync_commit" in state:new_state["last_docs_commit"] = state["last_sync_commit"]if knowledge_graph_result is not None:diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex b8f564fe8..c8eaeeca5 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -926,6 +926,7 @@ async def persist_incremental_index(git_decay_map: dict | None = None,log: LogFn | None = None,degraded: list[str] | None = None,+ failed_steps: list[str] | None = None,) -> None:"""Persist an incremental index refresh (graph + symbols + git + dead-code + health).@@ -936,6 +937,22 @@ async def persist_incremental_index(``degraded`` (when supplied) collects a one-line entry for everybest-effort step that failed, so the caller can render an honestcompletion report instead of silently claiming success.++ ``failed_steps`` (when supplied) collects the names of the failed steps+ whose input was *this commit range* rather than the whole repo. Those are+ the only failures a later run cannot heal on its own: their data is scoped+ to a range the sync pointer is about to move past, so the caller records+ them as a repair marker and re-covers the range next update.++ The test for membership is "would widening the next run's diff base repair+ this, and would nothing else". Steps that re-derive the whole repo every+ run are deliberately absent (graph nodes, the sweeps, the page tree,+ related pages, the knowledge graph, the deleted-file prune): they heal+ themselves on the next update, and marking them would let a permanently+ broken one pin the repair window open. So is the commit capture, which+ looks range-scoped and is not: it bounds its walk by the newest+ ``committed_at`` already in the table, so a run it skipped is re-walked by+ the next one whatever the diff base says."""from repowise.core.persistence import (create_engine,@@ -948,10 +965,12 @@ async def persist_incremental_index(log = log or _noop_log- def _skip(step: str, exc: Exception) -> None:+ def _skip(step: str, exc: Exception, *, range_scoped: bool = False) -> None:log(f"[yellow]{step} skipped: {exc}[/yellow]")if degraded is not None:degraded.append(f"{step}: {exc}")+ if range_scoped and failed_steps is not None:+ failed_steps.append(step)url = resolve_db_url(repo_path)engine = create_engine(url)@@ -968,13 +987,6 @@ async def persist_incremental_index(repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))repo_id = repo.id- if current_graph_file_paths:- try:- from repowise.core.pipeline.persist import _prune_stale_file_rows-- await _prune_stale_file_rows(session, repo_id, current_graph_file_paths, set())- except Exception as exc:- _skip("Stale row prune", exc)# Delete rows of pages retired since this index was built. This# path never regenerates a repo-wide page, so nothing else here@@ -1012,7 +1024,7 @@ async def persist_incremental_index(session, repo_id, tombstone_candidates(file_diffs))except Exception as exc:- _skip("Tombstone marking", exc)+ _skip("Tombstone marking", exc, range_scoped=True)# Placement depends on the whole page set, which on an incremental# run lives in the store rather than in the pages just generated.@@ -1040,7 +1052,7 @@ async def persist_incremental_index()await recompute_git_percentiles(session, repo_id)except Exception as exc:- _skip("Git persist", exc)+ _skip("Git persist", exc, range_scoped=True)try:await persist_incremental_commits(session, repo_id, repo_path)@@ -1057,13 +1069,13 @@ async def persist_incremental_index(session, repo_id, dead_code_report.findings, file_paths=changed_paths)except Exception as exc:- _skip("Dead-code persist", exc)+ _skip("Dead-code persist", exc, range_scoped=True)if partial_health_report is not None:try:await persist_partial_health(session, repo_id, partial_health_report)except Exception as exc:- _skip("Health persist", exc)+ _skip("Health persist", exc, range_scoped=True)# Re-persist graph_nodes so symbol-level PageRank /# betweenness / community ids stay in sync with the@@ -1088,7 +1100,7 @@ async def persist_incremental_index(await persist_incremental_symbols(session, repo_id, parsed_files, changed_paths)except Exception as exc:- _skip("Symbol persist", exc)+ _skip("Symbol persist", exc, range_scoped=True)# Refresh graph_edges for the changed files. The full-init path was# historically the only writer of edges, so adjacency froze at the@@ -1102,7 +1114,7 @@ async def persist_incremental_index(session, repo_id, graph_builder, parsed_files, changed_paths)except Exception as exc:- _skip("Graph edges persist", exc)+ _skip("Graph edges persist", exc, range_scoped=True)# Refresh related-pages metadata across the whole wiki. LLM-free,# so even index-only updates heal pages generated before the@@ -1138,7 +1150,7 @@ async def persist_incremental_index(try:await refresh_external_systems(session, repo_id, repo_path, file_diffs, log=log)except Exception as exc:- _skip("External systems refresh", exc)+ _skip("External systems refresh", exc, range_scoped=True)# One-shot drain of proposals from the removed code_comment# harvest (#751). Runs on the index-only path too, because the@@ -1153,6 +1165,61 @@ async def persist_incremental_index(except Exception as exc:_skip("Decision purge", exc)+ # Drop file-scoped rows for files that have actually been deleted.+ # Without this an incremental update tombstones the deleted file's+ # page and leaves everything else: graph nodes, edges, metrics,+ # symbols, health rows and git metadata all keep serving a file+ # that is gone. The liveness question is asked of the filesystem+ # and git, never of this run's parse, so a transient read failure+ # cannot masquerade as a deletion (see prune_deleted_file_rows).+ #+ # Last in the session on purpose. Everything above upserts rather+ # than deleting, and the git step in particular indexes the changed+ # *paths*, which includes the deleted ones: pruning first left a+ # fresh git_metadata row for every file this run watched disappear.+ # Running last means the prune has the final say on what the store+ # claims exists.+ try:+ from repowise.core.pipeline.persist import prune_deleted_file_rows++ live_hint = set(+ current_graph_file_paths+ if current_graph_file_paths is not None+ else {pf.file_info.path for pf in parsed_files or []}+ )+ # Plus every file node the rebuilt graph still holds, which is+ # the only reliable way to know a node names no file at all.+ # Framework and resolver passes mint file-shaped nodes for+ # things that were never on disk: `external:` imports,+ # `framework:` anchors, and Spring's `META-INF/services/<iface>`+ # SPI source, which carries no prefix to recognise it by. All+ # of them fail every liveness test there is, so a prune that+ # asked only about disk and git would delete them and take+ # their edges with them, and only *changed* files' edges are+ # rebuilt afterwards. A node this run's graph build still+ # contains is live by construction, whatever it names.+ #+ # Deliberately not guarded: a graph this run cannot read is a+ # run that has no business deciding what was deleted, and the+ # outer handler skips the prune entirely.+ graph = graph_builder.graph()+ live_hint |= {+ node+ for node, data in graph.nodes(data=True)+ if data.get("node_type", "file") == "file"+ }+ pruned, refusals = await prune_deleted_file_rows(+ session, repo_id, repo_path, live_hint=live_hint+ )+ if pruned:+ log(f"Pruned rows for [cyan]{pruned}[/cyan] deleted file(s)")+ for refusal in refusals:+ log(f"[yellow]{refusal}[/yellow]")+ if degraded is not None:+ degraded.append(refusal)+ except Exception as exc:+ _skip("Deleted-file prune", exc)+# After the session closes: on SQLite the full-text index shares the# database file, so writing to it while the session holds a write lock# raises "database is locked".@@ -1175,7 +1242,13 @@ async def persist_incremental_index(if swept_page_ids:await fts.delete_many(swept_page_ids)except Exception as exc:- _skip("Tombstone full-text removal", exc)+ # Range-scoped for the tombstone half: mark_tombstone_pages+ # re-marks and re-returns pages that are already tombstones, so+ # a widened re-run regenerates these ids and retries the delete.+ # The swept half is not repairable this way, because the sweeps+ # deleted those rows and a later run finds nothing to sweep.+ # Tagging still recovers strictly more than not tagging.+ _skip("Tombstone full-text removal", exc, range_scoped=True)# Ceiling: the swept pages' *vector* embeddings survive this path.# There is no store here to delete them from, and building one woulddiff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 100f4a7d4..523f26a5f 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -586,7 +586,13 @@ async def _prune_stale_file_rows(*current_graph_file_paths* (from ``parsed_files``) governs graph/analysistables; *current_git_file_paths* (from ``git_metadata_list``) governs``git_metadata`` only. Each set independently no-ops when empty to avoid- wiping rows on a broken run. FULL persistence only — not incremental paths.+ wiping rows on a broken run.++ Full runs only. The authority here is "absent from this run's output",+ which is only safe because a full run rebuilds every table it prunes from+ in the same transaction. Incremental runs use+ :func:`prune_deleted_file_rows`, whose authority is the filesystem and git+ rather than the parse — see its docstring for why the two differ."""from sqlalchemy import delete, or_, select@@ -676,6 +682,240 @@ async def _prune_stale_file_rows(await _delete_stale_by_paths(GitMetadata, GitMetadata.file_path, current_git_file_paths)+# A prune that would take more than this share of a table is read as a broken+# run rather than a large commit, and refused. The asymmetry is the whole+# argument: refusing leaves stale rows, which are visible in the UI and cleared+# by a reindex, where proceeding deletes live ones, which are invisible until+# someone notices the symbol is missing.+_PRUNE_MAX_FRACTION = 0.5+# ...but a small repo can legitimately lose half its files in one commit, so the+# fraction only applies once the *deletion* is big enough for the ratio to mean+# something. Measured on the deletion rather than the table so that a 25-row+# store losing 20 rows still prunes: at that size "most of it went" is an+# ordinary commit, not evidence of a broken run.+_PRUNE_FLOOR_MIN_ROWS = 20+++def _git_tracked_paths(root: Path) -> frozenset[str]:+ """Every path git tracks at HEAD, POSIX-relative, or an empty set on failure.++ Empty is indistinguishable from "git failed" on purpose: both mean this+ witness has nothing to say, and the caller treats silence as "no opinion"+ rather than as "nothing is tracked".+ """+ import subprocess++ try:+ out = subprocess.run(+ ["git", "-C", str(root), "ls-files", "-z"],+ capture_output=True,+ timeout=60,+ check=True,+ ).stdout+ except Exception:+ return frozenset()+ return frozenset(p for p in out.decode("utf-8", "replace").split("\0") if p)+++class _FileLiveness:+ """Is this path still a real file, judged without consulting this run's parser.++ Two witnesses, neither of which is the parse: the file is present on disk,+ or git still tracks it. A path has to fail both to count as deleted.++ That split is the point. Deriving deletions from ``parsed_files`` alone+ makes every transient read or parse failure look like a deletion, and on+ Windows a file lock or an antivirus scan produces exactly that: the file is+ there, the run could not read it, and the naive prune deletes its rows.+ The disk check answers for that case; git covers the narrower one where the+ stat itself fails (``Path.exists()`` reports False on a permission error).++ The deliberate cost of taking the union: a file that a config change has+ newly *excluded* still exists and is still tracked, so its rows survive an+ incremental update. That matches the behaviour before this guard existed+ (which pruned nothing at all on this path), and a full reindex still clears+ it, so nothing regresses.++ ``git ls-files`` is spawned lazily, on the first path that is not on disk,+ so an update with no deletions never pays for it.+ """++ def __init__(self, repo_path: Any) -> None:+ self._root = Path(repo_path)+ self._tracked: frozenset[str] | None = None+ # The same path is asked about once per table it has rows in, and a+ # stat under an antivirus scanner is not free.+ self._memo: dict[str, bool] = {}++ def is_live(self, path: str) -> bool:+ answer = self._memo.get(path)+ if answer is None:+ answer = self._is_live(path)+ self._memo[path] = answer+ return answer++ def _is_live(self, path: str) -> bool:+ if (self._root / path).exists():+ return True+ if self._tracked is None:+ self._tracked = _git_tracked_paths(self._root)+ return path in self._tracked+++async def prune_deleted_file_rows(+ session: Any,+ repo_id: str,+ repo_path: Any,+ *,+ live_hint: set[str] | None = None,+) -> tuple[int, list[str]]:+ """Delete file-scoped rows for files that are gone, on an incremental update.++ The incremental path never pruned anything: deleting a file tombstoned its+ wiki page and left its graph nodes, edges, metrics, symbols, health rows and+ git metadata behind, so MCP, search and every health aggregate kept counting+ a file that no longer exists until someone ran a full reindex.++ The authority is deliberately *not* the one :func:`_prune_stale_file_rows`+ uses. A full run rebuilds every table it prunes from, so "absent from this+ run's output" is a safe question there. An incremental run rebuilds nothing:+ a row deleted here is not rewritten, so the question has to be "is the file+ gone", answered by :class:`_FileLiveness` from the filesystem and git rather+ than from the parse. They differ exactly in the transient-failure case, and+ that case is the one that loses data.++ *live_hint* is what this run already knows to be live: the paths that+ parsed, plus every file node the rebuilt graph holds. The first half is+ purely an optimisation, since anything in it would pass the liveness test+ anyway and the stat is skipped. The second half is load-bearing: a node+ like ``external:...`` or Spring's ``META-INF/services/<iface>`` names no+ file, so it fails every liveness test there is, and only the fact that the+ graph build just re-minted it says it is not a deletion.++ Returns ``(deleted_path_count, refusals)``, where a refusal is a one-line+ explanation of a floor guard that fired, for the caller's degraded report.+ """+ from sqlalchemy import delete, or_, select++ # Not every ``node_type == "file"`` row names a file. ``external:`` and+ # ``framework:`` nodes are minted for third-party imports and for+ # convention-based loading, they are stored as file nodes, and they answer+ # "no" to every liveness question there is because no such file was ever+ # meant to exist. Without this they read as a mass deletion: 223 of hugo's+ # 2,356 file nodes, 590 of react's 3,353, and 70% of spring-petclinic's,+ # which is past the floor guard and would have been reported as a refusal+ # rather than as the bug it is.+ #+ # Imported rather than re-listed: a prefix added to one copy and not the+ # other is exactly the bug above. Costs nothing on this path, where the+ # partial dead-code analysis has already loaded the module (13.7 ms when+ # it has not, measured cold after the CLI modules are up).+ from repowise.core.analysis.dead_code.analyzer import _is_synthetic_node+ from repowise.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ GraphEdge,+ GraphMetric,+ GraphNode,+ HealthFileMetric,+ HealthFinding,+ SecurityFinding,+ WikiSymbol,+ )++ hint = live_hint or set()+ liveness = _FileLiveness(repo_path)+ refusals: list[str] = []+ deleted: set[str] = set()++ def _dead(persisted: set[str], label: str) -> list[str]:+ """Paths in *persisted* that no longer exist, or [] if the floor fired."""+ persisted = {p for p in persisted if not _is_synthetic_node(p)}+ dead = [p for p in persisted if p not in hint and not liveness.is_live(p)]+ if (+ len(dead) > _PRUNE_FLOOR_MIN_ROWS+ and persisted+ and len(dead) > _PRUNE_MAX_FRACTION * len(persisted)+ ):+ refusals.append(+ f"Deleted-file prune refused for {label}: {len(dead)} of "+ f"{len(persisted)} paths looked deleted, which reads as a broken "+ "run rather than a commit. Run a full reindex to clear them."+ )+ return []+ deleted.update(dead)+ return dead++ async def _prune_table(model: Any, column: Any, label: str) -> None:+ persisted = set(+ (await session.execute(select(column).where(model.repository_id == repo_id).distinct()))+ .scalars()+ .all()+ )+ persisted.discard(None)+ dead = _dead(persisted, label)+ for i in range(0, len(dead), _PRUNE_CHUNK):+ await session.execute(+ delete(model).where(+ model.repository_id == repo_id,+ column.in_(dead[i : i + _PRUNE_CHUNK]),+ )+ )++ # ---- Graph nodes + edges -------------------------------------------------+ # File nodes key on node_id, symbol nodes on file_path, and edges have no FK+ # cascade from either, so edges go first.+ node_rows = (+ await session.execute(+ select(GraphNode.node_id, GraphNode.node_type, GraphNode.file_path).where(+ GraphNode.repository_id == repo_id+ )+ )+ ).all()+ node_paths = {+ (node_id if node_type == "file" else file_path)+ for node_id, node_type, file_path in node_rows+ if node_type == "file" or file_path+ }+ dead_paths = set(_dead(node_paths, "graph_nodes"))+ if dead_paths:+ stale_node_ids = [+ node_id+ for node_id, node_type, file_path in node_rows+ if (node_id if node_type == "file" else file_path) in dead_paths+ ]+ for i in range(0, len(stale_node_ids), _PRUNE_CHUNK):+ batch = stale_node_ids[i : i + _PRUNE_CHUNK]+ await session.execute(+ delete(GraphEdge).where(+ GraphEdge.repository_id == repo_id,+ or_(+ GraphEdge.source_node_id.in_(batch),+ GraphEdge.target_node_id.in_(batch),+ ),+ )+ )+ await session.execute(+ delete(GraphNode).where(+ GraphNode.repository_id == repo_id,+ GraphNode.node_id.in_(batch),+ )+ )++ await _prune_table(GraphMetric, GraphMetric.node_id, "graph_metrics")+ await _prune_table(WikiSymbol, WikiSymbol.file_path, "wiki_symbols")+ await _prune_table(SecurityFinding, SecurityFinding.file_path, "security_findings")+ await _prune_table(DeadCodeFinding, DeadCodeFinding.file_path, "dead_code_findings")+ await _prune_table(HealthFileMetric, HealthFileMetric.file_path, "health_file_metrics")+ await _prune_table(HealthFinding, HealthFinding.file_path, "health_findings")+ # git_metadata is keyed off the git indexer on a full run, but an+ # incremental run only indexes the changed files, so the same liveness+ # question is the only authority available here too.+ await _prune_table(GitMetadata, GitMetadata.file_path, "git_metadata")++ return len(deleted), refusals++# Generated page types keyed on run-scoped structure: module/scc pages on# clustering ordinals, layer pages on display names. Those keys shift between# runs, so re-runs mint fresh page ids and the previous rows linger asdiff --git a/tests/unit/cli/test_update_repair_marker.py b/tests/unit/cli/test_update_repair_marker.pynew file mode 100644index 000000000..8dd6db98e--- /dev/null+++ b/tests/unit/cli/test_update_repair_marker.py@@ -0,0 +1,151 @@+"""Tests for the repair marker that keeps a degraded update recoverable.++``last_sync_commit`` advances whether or not the persist steps succeeded, so a+failed step used to take its commit range with it: nothing revisited those+commits and their data was skipped permanently. The marker holds the old+pointer so the next update re-covers the range.+"""++from __future__ import annotations++import subprocess+from pathlib import Path++import pytest++from repowise.cli.commands.update_cmd.persistence import (+ _REPAIR_MAX_COMMITS,+ record_repair_marker,+ resolve_repair_base,+)+++def _git(repo: Path, *args: str) -> str:+ return subprocess.run(+ ["git", "-C", str(repo), *args], check=True, capture_output=True, text=True+ ).stdout.strip()+++def linear_repo(tmp_path: Path) -> tuple[Path, list[str]]:+ """A repo with three linear commits; returns (repo, [sha0, sha1, sha2])."""+ repo = tmp_path / "repo"+ repo.mkdir()+ _git(repo, "init", "-q")+ _git(repo, "config", "user.name", "Seed")+ _git(repo, "config", "user.email", "[email protected]")+ shas = []+ for i in range(3):+ (repo / f"f{i}.txt").write_text(f"{i}\n", encoding="utf-8")+ _git(repo, "add", "-A")+ _git(repo, "commit", "-q", "-m", f"c{i}")+ shas.append(_git(repo, "rev-parse", "HEAD"))+ return repo, shas+++# --- record_repair_marker -------------------------------------------------+++def test_failure_records_the_pointer_the_run_started_from():+ new_state: dict = {"last_sync_commit": "head-sha"}+ record_repair_marker(new_state, {"last_sync_commit": "base-sha"}, ["Git persist"])+ assert new_state["pending_repair"] == {"from_commit": "base-sha", "steps": ["Git persist"]}+++def test_consecutive_failures_keep_the_oldest_unrepaired_commit():+ """Three failed runs in a row must still re-cover all three ranges.++ And the marker names one range, so its step list has to name everything+ still unrepaired over that range, not just the latest run's casualties.+ """+ prior = {+ "last_sync_commit": "c1",+ "pending_repair": {"from_commit": "c0", "steps": ["Git persist"]},+ }+ new_state: dict = {"last_sync_commit": "c2"}+ record_repair_marker(new_state, prior, ["Health persist"])+ assert new_state["pending_repair"]["from_commit"] == "c0"+ assert new_state["pending_repair"]["steps"] == ["Git persist", "Health persist"]+++def test_a_junk_marker_does_not_crash_the_update():+ """A hand-edited or truncated state file must not take the run down with it."""+ new_state: dict = {"last_sync_commit": "c2"}+ record_repair_marker(new_state, {"last_sync_commit": "c1", "pending_repair": "garbage"}, ["X"])+ assert new_state["pending_repair"] == {"from_commit": "c1", "steps": ["X"]}+++def test_clean_run_clears_the_marker():+ new_state: dict = {"pending_repair": {"from_commit": "c0", "steps": ["Git persist"]}}+ record_repair_marker(new_state, {"last_sync_commit": "c1"}, [])+ assert "pending_repair" not in new_state+++def test_no_marker_without_a_pointer_to_diff_back_to():+ """A first index has no old pointer, so there is no range to name."""+ new_state: dict = {}+ record_repair_marker(new_state, {}, ["Git persist"])+ assert "pending_repair" not in new_state+++# --- resolve_repair_base --------------------------------------------------+++def test_marker_widens_the_base_back_to_the_unrepaired_range(linear_repo):+ repo, shas = linear_repo+ state = {"pending_repair": {"from_commit": shas[0], "steps": ["Git persist"]}}+ base, give_up = resolve_repair_base(repo, state, shas[1], shas[2])+ assert (base, give_up) == (shas[0], None)+++def test_no_marker_leaves_the_base_alone(linear_repo):+ repo, shas = linear_repo+ base, give_up = resolve_repair_base(repo, {}, shas[1], shas[2])+ assert (base, give_up) == (shas[1], None)+++def test_a_junk_marker_is_ignored_rather_than_raising(linear_repo):+ repo, shas = linear_repo+ base, give_up = resolve_repair_base(repo, {"pending_repair": "garbage"}, shas[1], shas[2])+ assert (base, give_up) == (shas[1], None)+++def test_marker_that_caught_up_is_a_no_op(linear_repo):+ repo, shas = linear_repo+ state = {"pending_repair": {"from_commit": shas[1], "steps": ["Git persist"]}}+ base, give_up = resolve_repair_base(repo, state, shas[1], shas[2])+ assert (base, give_up) == (shas[1], None)+++def test_commit_that_left_the_history_is_given_up_on(linear_repo):+ """A rebased or gc'd marker must never move the base forward, so it is dropped."""+ repo, shas = linear_repo+ state = {"pending_repair": {"from_commit": "0" * 40, "steps": ["Git persist"]}}+ base, give_up = resolve_repair_base(repo, state, shas[1], shas[2])+ assert base == shas[1]+ assert give_up is not None and "not present in this clone" in give_up+++def test_non_ancestor_marker_is_given_up_on(linear_repo):+ """A base older than the marker (docs mode, a branch switch) must win."""+ repo, shas = linear_repo+ state = {"pending_repair": {"from_commit": shas[2], "steps": ["Git persist"]}}+ base, give_up = resolve_repair_base(repo, state, shas[0], shas[2])+ assert base == shas[0]+ assert give_up is not None+++def test_window_past_the_cap_is_given_up_on(linear_repo, monkeypatch):+ """The bound is what stops a step that fails every run from pinning the window open."""+ repo, shas = linear_repo+ monkeypatch.setattr(+ "repowise.cli.commands.update_cmd.persistence._REPAIR_MAX_COMMITS", 1+ )+ state = {"pending_repair": {"from_commit": shas[0], "steps": ["Git persist"]}}+ base, give_up = resolve_repair_base(repo, state, shas[1], shas[2])+ assert base == shas[1]+ assert give_up is not None and "re-index rather than a repair" in give_up+++def test_cap_is_a_real_bound():+ assert _REPAIR_MAX_COMMITS > 0diff --git a/tests/unit/persistence/test_prune_deleted_files.py b/tests/unit/persistence/test_prune_deleted_files.pynew file mode 100644index 000000000..5572a6708--- /dev/null+++ b/tests/unit/persistence/test_prune_deleted_files.py@@ -0,0 +1,246 @@+"""Tests for the incremental deleted-file prune and its floor guard.++The incremental update path used to prune nothing: deleting a file tombstoned+its wiki page and left its graph nodes, edges, metrics, symbols, health rows+and git metadata serving a file that no longer existed. These cover both+halves of the fix — that a real deletion is cleaned out of every file-scoped+table, and that a run whose parser fell over cannot be mistaken for one.+"""++from __future__ import annotations++import subprocess+from pathlib import Path++import pytest+from sqlalchemy import select++from repowise.core.persistence.models import (+ DeadCodeFinding,+ GitMetadata,+ GraphEdge,+ GraphMetric,+ GraphNode,+ HealthFileMetric,+ HealthFinding,+ SecurityFinding,+ WikiSymbol,+)+from repowise.core.pipeline.persist import prune_deleted_file_rows+from tests.unit.persistence.helpers import insert_repo+from tests.unit.persistence.test_persist_prune import KEPT, STALE, _paths, _seed++# Every file-scoped table the audit found surviving a delete, with the column+# that carries the path. Kept in one list so a new table cannot be covered by+# the "deleted" assertion and forgotten by the "transient failure" one.+FILE_SCOPED = [+ (GraphMetric, GraphMetric.node_id),+ (WikiSymbol, WikiSymbol.file_path),+ (SecurityFinding, SecurityFinding.file_path),+ (DeadCodeFinding, DeadCodeFinding.file_path),+ (HealthFileMetric, HealthFileMetric.file_path),+ (HealthFinding, HealthFinding.file_path),+ (GitMetadata, GitMetadata.file_path),+]+++def _git(repo: Path, *args: str) -> None:+ subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)+++def repo_with_kept_file(tmp_path: Path) -> Path:+ """A git repo where KEPT exists and is tracked, and STALE does not exist."""+ repo = tmp_path / "repo"+ (repo / Path(KEPT).parent).mkdir(parents=True)+ (repo / KEPT).write_text("export const main = () => {};\n", encoding="utf-8")+ _git(repo, "init", "-q")+ _git(repo, "config", "user.name", "Seed")+ _git(repo, "config", "user.email", "[email protected]")+ _git(repo, "add", KEPT)+ _git(repo, "commit", "-q", "-m", "seed")+ return repo+++async def test_deleted_file_is_pruned_from_every_table(async_session, repo_with_kept_file):+ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id)++ pruned, refusals = await prune_deleted_file_rows(+ async_session, repo.id, repo_with_kept_file, live_hint={KEPT}+ )+ await async_session.commit()++ assert refusals == []+ assert pruned == 1++ # The deleted file's graph node and its symbol node are both gone.+ assert await _paths(async_session, GraphNode, GraphNode.node_id, repo.id) == {+ KEPT,+ f"{KEPT}::main",+ }+ # ...along with the edge that pointed at it.+ edges = (+ (await async_session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo.id)))+ .scalars()+ .all()+ )+ assert [(e.source_node_id, e.target_node_id) for e in edges] == [(KEPT, f"{KEPT}::main")]++ for model, column in FILE_SCOPED:+ assert await _paths(async_session, model, column, repo.id) == {KEPT}, model.__name__+++async def test_transient_parse_failure_prunes_nothing(async_session, repo_with_kept_file):+ """A run where nothing parsed must not read as a run where everything was deleted.++ This is the failure mode the parse-derived authority has and the liveness+ one does not: on Windows a file lock or an antivirus scan drops a live file+ out of ``parsed_files``, and that must never delete its rows.+ """+ # Both files exist on disk this time, so the only thing saying they are+ # gone is the empty parse result.+ (repo_with_kept_file / Path(STALE).parent).mkdir(parents=True, exist_ok=True)+ (repo_with_kept_file / STALE).write_text("// locked\n", encoding="utf-8")++ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id)++ pruned, refusals = await prune_deleted_file_rows(+ async_session, repo.id, repo_with_kept_file, live_hint=set()+ )+ await async_session.commit()++ assert (pruned, refusals) == (0, [])+ assert await _paths(async_session, GraphNode, GraphNode.node_id, repo.id) == {+ KEPT,+ STALE,+ f"{KEPT}::main",+ f"{STALE}::main",+ }+ for model, column in FILE_SCOPED:+ assert await _paths(async_session, model, column, repo.id) == {KEPT, STALE}, model.__name__+++async def test_git_tracked_file_missing_from_disk_survives(async_session, repo_with_kept_file):+ """The second witness: a stat that fails must not count as a deletion.++ ``Path.exists()`` answers False for a file it cannot stat, which is the+ same answer it gives for a file that is really gone. git tracking is what+ separates the two.+ """+ (repo_with_kept_file / KEPT).unlink() # tracked, but unreadable/absent now++ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id)++ pruned, _ = await prune_deleted_file_rows(+ async_session, repo.id, repo_with_kept_file, live_hint=set()+ )+ await async_session.commit()++ # STALE is neither on disk nor tracked, so it goes; KEPT is still tracked.+ assert pruned == 1+ assert await _paths(async_session, GitMetadata, GitMetadata.file_path, repo.id) == {KEPT}+++async def test_synthetic_nodes_are_not_deleted_files(async_session, repo_with_kept_file):+ """``external:``/``framework:`` nodes are stored as file nodes and name no file.++ They answer "not live" to every witness there is, because no such file was+ ever meant to exist. Counting them as deletions drops their graph rows and+ every edge that reaches them, and on this path only the *changed* files'+ edges are rebuilt afterwards, so the edges do not come back. It also+ dominates the floor guard: on a Spring sample app they are 70% of the file+ nodes, so the whole prune would be refused rather than corrected.+ """+ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id)+ for node_id in ("external:github.com/spf13/cobra", "framework:conftest"):+ async_session.add(GraphNode(repository_id=repo.id, node_id=node_id, node_type="file"))+ async_session.add(GraphMetric(repository_id=repo.id, node_id=node_id))+ async_session.add(+ GraphEdge(+ repository_id=repo.id,+ source_node_id=KEPT,+ target_node_id="external:github.com/spf13/cobra",+ edge_type="imports",+ )+ )+ await async_session.flush()++ pruned, refusals = await prune_deleted_file_rows(+ async_session, repo.id, repo_with_kept_file, live_hint={KEPT}+ )+ await async_session.commit()++ assert (pruned, refusals) == (1, [])+ node_ids = await _paths(async_session, GraphNode, GraphNode.node_id, repo.id)+ assert "external:github.com/spf13/cobra" in node_ids+ assert "framework:conftest" in node_ids+ assert await _paths(async_session, GraphMetric, GraphMetric.node_id, repo.id) == {+ KEPT,+ "external:github.com/spf13/cobra",+ "framework:conftest",+ }+ # The edge into the external node survives with it.+ edges = (+ (await async_session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo.id)))+ .scalars()+ .all()+ )+ assert ("external:github.com/spf13/cobra") in {e.target_node_id for e in edges}+++async def test_mass_deletion_is_refused_not_applied(async_session, repo_with_kept_file):+ """A prune that would take most of a table reads as a broken run, and is refused."""+ repo = await insert_repo(async_session)+ for i in range(40):+ async_session.add(+ GitMetadata(repository_id=repo.id, file_path=f"src/module_{i}.js")+ )+ await async_session.flush()++ pruned, refusals = await prune_deleted_file_rows(+ async_session, repo.id, repo_with_kept_file, live_hint=set()+ )+ await async_session.commit()++ assert pruned == 0+ assert len(refusals) == 1+ assert "git_metadata" in refusals[0]+ assert len(await _paths(async_session, GitMetadata, GitMetadata.file_path, repo.id)) == 40+++async def test_small_repo_can_still_lose_most_of_its_files(async_session, repo_with_kept_file):+ """The fraction only bites above a row floor, so a 3-file repo still prunes."""+ repo = await insert_repo(async_session)+ for name in ("a.js", "b.js", "c.js"):+ async_session.add(GitMetadata(repository_id=repo.id, file_path=f"src/{name}"))+ await async_session.flush()++ pruned, refusals = await prune_deleted_file_rows(+ async_session, repo.id, repo_with_kept_file, live_hint=set()+ )+ await async_session.commit()++ assert refusals == []+ assert pruned == 3+ assert await _paths(async_session, GitMetadata, GitMetadata.file_path, repo.id) == set()+++async def test_prune_is_scoped_to_one_repo(async_session, repo_with_kept_file):+ repo_a = await insert_repo(async_session, local_path="/tmp/repo-a", name="a")+ repo_b = await insert_repo(async_session, local_path="/tmp/repo-b", name="b")+ await _seed(async_session, repo_a.id)+ await _seed(async_session, repo_b.id)++ await prune_deleted_file_rows(+ async_session, repo_a.id, repo_with_kept_file, live_hint={KEPT}+ )+ await async_session.commit()++ assert await _paths(async_session, GitMetadata, GitMetadata.file_path, repo_b.id) == {+ STALE,+ KEPT,+ }diff --git a/tests/unit/pipeline/test_incremental_failure_isolation.py b/tests/unit/pipeline/test_incremental_failure_isolation.pynew file mode 100644index 000000000..1e6e6b87d--- /dev/null+++ b/tests/unit/pipeline/test_incremental_failure_isolation.py@@ -0,0 +1,164 @@+"""A degraded persist step must be recorded precisely enough to be repaired.++``persist_incremental_index`` degrades every step it can, and the caller then+advances ``last_sync_commit`` regardless. Which failures are worth a repair+marker is therefore not a detail: a step whose input was this commit range+strands data when the pointer moves past it, and a step that re-derives the+whole repo every run does not. Marking the second kind would let one+permanently broken step pin the repair window open forever.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.pipeline.incremental import persist_incremental_index+++def repo(tmp_path: Path) -> Path:+ (tmp_path / ".repowise").mkdir()+ return tmp_path+++async def test_range_scoped_failure_is_marked_and_repo_wide_failure_is_not(repo, monkeypatch):+ from repowise.core.persistence import crud++ def _boom(*args, **kwargs):+ raise RuntimeError("disk full")++ monkeypatch.setattr(crud, "upsert_git_metadata_bulk", _boom)++ degraded: list[str] = []+ failed_steps: list[str] = []+ await persist_incremental_index(+ repo,+ # No graph builder worth the name: the repo-wide steps that consume it+ # fail on their own, which is exactly the contrast under test.+ object(),+ {"src/a.py": {"file_path": "src/a.py"}},+ None,+ None,+ ["src/a.py"],+ log=lambda _msg: None,+ degraded=degraded,+ failed_steps=failed_steps,+ )++ # The forced failure was scoped to this run's changed files, so it strands+ # data the pointer is about to skip: it has to be repairable.+ assert "Git persist" in failed_steps+ assert any(entry.startswith("Git persist:") for entry in degraded)++ # The graph node persist failed too (no real builder), and it is repo-wide:+ # the next update rebuilds it from scratch, so it is reported and not+ # marked for repair.+ assert any(entry.startswith("Graph nodes persist:") for entry in degraded)+ assert "Graph nodes persist" not in failed_steps+++async def test_prune_spares_every_file_node_the_rebuilt_graph_still_holds(repo, monkeypatch):+ """Nodes that name no file survive, including the ones with no prefix to spot.++ ``external:`` and ``framework:`` nodes are recognisable, but Spring's SPI+ source is minted as the bare path ``META-INF/services/<iface>`` with+ ``node_type="file"`` (ingestion/framework_edges/spring.py). It is on no+ disk and in no git index, so a prune that asked only those two witnesses+ would delete it and every framework edge hanging off it, and only+ *changed* files' edges are rebuilt afterwards.++ The invariant that covers all three without a list to keep in sync: a node+ this run's graph build still contains is live, whatever it names.+ """+ import networkx as nx++ from repowise.core.pipeline import persist as persist_mod++ graph = nx.DiGraph()+ graph.add_node("META-INF/services/com.example.Spi", node_type="file")+ graph.add_node("external:github.com/spf13/cobra", node_type="file")+ graph.add_node("src/kept.py", node_type="file")+ graph.add_node("src/kept.py::main", node_type="symbol", file_path="src/kept.py")+ # "src/gone.py" is deliberately absent: a deleted file drops out of the+ # rebuilt graph, which is what leaves it a prune candidate.++ class FakeBuilder:+ def graph(self):+ return graph++ seen: dict = {}++ async def spy(session, repo_id, repo_path, *, live_hint=None):+ seen["hint"] = live_hint+ return 0, []++ monkeypatch.setattr(persist_mod, "prune_deleted_file_rows", spy)++ await persist_incremental_index(+ repo,+ FakeBuilder(),+ {},+ None,+ None,+ [],+ log=lambda _msg: None,+ parsed_files=[],+ )++ assert "META-INF/services/com.example.Spi" in seen["hint"]+ assert "external:github.com/spf13/cobra" in seen["hint"]+ assert "src/kept.py" in seen["hint"]+ assert "src/gone.py" not in seen["hint"]+ # Symbol nodes are not file paths and must not widen the hint.+ assert "src/kept.py::main" not in seen["hint"]+++def test_the_range_scoped_set_is_exactly_these_steps():+ """Which steps are repairable is a judgement, so it is pinned rather than assumed.++ Getting it wrong is silent in both directions: a range-scoped step left+ untagged strands its data forever (the bug), and a repo-wide step tagged by+ mistake keeps the repair window open on every run until the commit bound+ gives up on it. Neither shows up in any other test.++ ``Commit capture`` is the one that reads range-scoped and is not: it bounds+ its walk by the newest ``committed_at`` already persisted, so the next run+ re-walks whatever it skipped. ``External systems refresh`` is the reverse,+ since it only runs when a dependency manifest is in *this* diff.+ """+ import re+ from pathlib import Path++ import repowise.core.pipeline.incremental as mod++ source = Path(mod.__file__).read_text(encoding="utf-8")+ tagged = set(re.findall(r'_skip\(\s*"([^"]+)",\s*exc,\s*range_scoped=True', source))+ assert tagged == {+ "Tombstone marking",+ "Git persist",+ "Dead-code persist",+ "Health persist",+ "Symbol persist",+ "Graph edges persist",+ "External systems refresh",+ "Tombstone full-text removal",+ }+++async def test_clean_run_marks_nothing(repo):+ """No failures means no repair marker, whatever else degraded."""+ failed_steps: list[str] = []+ await persist_incremental_index(+ repo,+ object(),+ {},+ None,+ None,+ [],+ log=lambda _msg: None,+ degraded=[],+ failed_steps=failed_steps,+ )+ assert failed_steps == []