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.

feat(core): incremental fast->full index upgrade via `repowise update --full` (#224)

Raghav Chamadiya131ff315691d
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index e3e083b16..27e37ab82 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -104,9 +104,12 @@ Incrementally update wiki pages for files changed since the last sync.
| `--workspace` | Update all stale repos in the workspace + cross-repo analysis |
| `--no-workspace` | Force single-repo mode (handy when running from a workspace root) |
| `--repo` | Update a specific workspace repo by alias |
+| `--full` | Upgrade a fast (`--mode fast`) index to a full one — see below. Single-repo only. |
**First-time indexing:** as of v0.8, `update --workspace` now runs full first-time indexing for workspace entries that have no `.repowise/` dir yet (previously skipped with `"not_indexed"`). The pipeline runs index-only — no LLM cost — and writes a state.json marker so `repowise update --repo <alias> --docs` later picks up doc generation cleanly.
+**Upgrading a fast index to full (`--full`):** a repo first indexed with `repowise init --mode fast` has the full dependency graph + metrics persisted, but only the *essential* git tier (last commits, no per-file blame or co-change) and no LLM docs. `repowise update --full` upgrades it **incrementally**: it backfills the git tier to FULL (per-file blame + repo-wide co-change) using a resumable, checkpointed worker, then generates the docs that fast mode skipped. Crucially, it **reuses the persisted graph** — the dependency graph is rehydrated from SQL rather than re-parsed and re-resolved, so the expensive import/call/heritage resolution and centrality computation the fast index already did are not repeated. This is measurably cheaper than re-running a full `init`. The backfill is resumable: if it is interrupted, re-running `repowise update --full` picks it up. A provider is required (the fast index made no LLM calls), so pass `--provider`/`--model` or have one configured.
+
**Examples:**
```bash
@@ -117,6 +120,7 @@ repowise update --reasoning off # one-off supported-provider thinking-off
repowise update --workspace # all workspace repos (incl. first-time indexing)
repowise update --repo backend # specific workspace repo
repowise update --no-workspace # force single-repo mode in a workspace root
+repowise update --full --provider anthropic # upgrade a fast index to full
```
---
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 053511f27..702f9c05a 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -235,6 +235,17 @@ Much faster and cheaper than a full `init` — only regenerates pages for change
| `--reasoning` | Reasoning mode for supported providers: `auto`, `off`, or `minimal`. |
| `--cascade-budget` | Max pages to regenerate per run (default: 30). Prevents runaway regeneration. |
| `--dry-run` | Show what would be updated without regenerating. |
+| `--full` | Upgrade a fast (`--mode fast`) index to a full one (single-repo). See below. |
+
+**Upgrading a fast index to full (`--full`):**
+
+If you first indexed a large repo with `repowise init --mode fast` (graph + essential git only, no LLM docs), `repowise update --full` upgrades it to a full index **without redoing the structural work**:
+
+1. Backfills the git tier from *essential* to *full* — per-file blame and repo-wide co-change — via a resumable, checkpointed worker (re-run `--full` to resume if interrupted).
+2. Rehydrates the dependency graph straight from the database instead of re-parsing and re-resolving it, so imports/calls/heritage resolution and centrality are **not** recomputed.
+3. Generates the LLM documentation that fast mode skipped.
+
+This is cheaper than re-running a full `init`, which would rebuild the graph from scratch. A provider is required, so pass `--provider`/`--model` or have one configured.
**Examples:**
@@ -254,6 +265,9 @@ repowise update --cascade-budget 10
# Disable reasoning for a supported provider/model for this run
repowise update --reasoning off
+
+# Upgrade a fast index to a full one (backfill git + generate docs)
+repowise update --full --provider anthropic
```
---
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index a97cc62c5..06f88cfbb 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -268,6 +268,18 @@ def _workspace_update(
"(set during `repowise init`)."
),
)
+ "--full",
+ "full",
+ is_flag=True,
+ default=False,
+ help=(
+ "Upgrade a fast (`--mode fast`) index to a full one: backfill the git "
+ "tier ESSENTIAL -> FULL and generate the LLM docs that fast mode "
+ "skipped. Incremental — reuses the persisted graph instead of "
+ "re-parsing and re-resolving it. Single-repo only."
+ ),
+)
def update_command(
path: str | None,
provider_name: str | None,
@@ -281,6 +293,7 @@ def update_command(
repo_alias: str | None,
index_only: bool = False,
docs_flag: bool | None = None,
+ full: bool = False,
concurrency: int = 5,
) -> None:
"""Incrementally update wiki pages for files changed since last sync.
@@ -301,6 +314,11 @@ def update_command(
target.notice(console, command="update")
if target.is_workspace:
+ if full:
+ raise click.ClickException(
+ "--full is single-repo only. Run it inside a specific repo "
+ "(or pass --no-workspace / --repo <alias>)."
+ )
_workspace_update(target, dry_run=dry_run)
return
@@ -308,6 +326,22 @@ def update_command(
repo_path = target.repo_path
assert repo_path is not None # single mode always sets repo_path
ensure_repowise_dir(repo_path)
+
+ # --- Fast -> full upgrade (--full): a distinct path that reuses the
+ # persisted graph rather than diffing changed files. Dispatched before any
+ # incremental change-detection so the normal `repowise update` flow below
+ # is byte-for-byte unchanged. ---
+ if full:
+ from repowise.cli.commands.upgrade_flow import upgrade_to_full
+
+ upgrade_to_full(
+ repo_path,
+ provider_name=provider_name,
+ model=model,
+ reasoning=reasoning,
+ concurrency=concurrency,
+ )
+ return
# Truncate the hook-managed log if it has grown past the cap. The hook
# appends each run unconditionally — without this opportunistic rotation
# at the start of every CLI update, a busy repo's ``.update.log`` would
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
new file mode 100644
index 000000000..124ec2eee
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -0,0 +1,310 @@
+"""``repowise update --full`` — incremental fast→full index upgrade.
+
+A repo indexed with ``--mode fast`` has the full structural graph + metrics
+persisted, but only ESSENTIAL git signals and no LLM docs. Re-running
+``repowise init`` would upgrade it, but it re-parses *and* rebuilds the graph
+from scratch — redoing the expensive resolution/centrality work the fast index
+already did.
+
+This module upgrades incrementally instead:
+
+1. Create the repository row **first** (so the JobStore-backed backfill's
+ ``pipeline_jobs`` FK is satisfiable from the CLI).
+2. Backfill the git tier ESSENTIAL → FULL via the resumable
+ ``backfill_full_tier`` worker (per-file blame + repo-wide co-change).
+3. Rehydrate the dependency graph from SQL (``rehydrate_graph_builder``) —
+ no re-resolution, no centrality recompute.
+4. Re-parse files for ASTs + source bytes (the only unavoidable re-work) and
+ generate the docs the fast index skipped, against the rehydrated graph.
+5. Persist pages + git metadata and flip the persisted state to full.
+
+The normal incremental ``repowise update`` path is untouched; this runs only
+when ``--full`` is passed.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import time
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import (
+ console,
+ get_head_commit,
+ load_config,
+ load_state,
+ resolve_provider,
+ resolve_reasoning,
+ run_async,
+ save_state,
+)
+
+
+def _reparse(repo_path: Path, exclude_patterns: list[str]) -> tuple[list[Any], dict[str, bytes], Any]:
+ """Parse files for ASTs + source bytes WITHOUT building/resolving the graph.
+
+ The graph is rehydrated from SQL separately; here we only need the parsed
+ files and raw source the generator consumes. Skipping ``GraphBuilder.build``
+ is the whole point — that resolution pass is what the fast index already did.
+ """
+ from repowise.core.ingestion import ASTParser, FileTraverser
+
+ traverser = FileTraverser(repo_path, extra_exclude_patterns=exclude_patterns or None)
+ file_infos = list(traverser.traverse())
+ repo_structure = traverser.get_repo_structure()
+
+ parser = ASTParser()
+ parsed_files: list[Any] = []
+ source_map: dict[str, bytes] = {}
+ for fi in file_infos:
+ try:
+ source = Path(fi.abs_path).read_bytes()
+ parsed = parser.parse_file(fi, source)
+ parsed_files.append(parsed)
+ source_map[fi.path] = source
+ except Exception:
+ pass # unreadable / unparseable files are skipped, as in init
+ return parsed_files, source_map, repo_structure
+
+
+async def _backfill_git(
+ sf: Any,
+ repo_id: str,
+ repo_path: Path,
+ *,
+ commit_limit: int | None,
+ follow_renames: bool,
+) -> dict[str, dict]:
+ """Promote the git tier to FULL via the resumable backfill worker.
+
+ Returns the ``file_path → git-metadata`` map for the freshly-indexed FULL
+ signals, which is also persisted here so co-change/blame land in the DB.
+ """
+ from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+ from repowise.core.ingestion.git_indexer.backfill import (
+ BACKFILL_PHASE,
+ backfill_full_tier,
+ )
+ from repowise.core.persistence import get_session
+ from repowise.core.persistence.crud import (
+ recompute_git_percentiles,
+ upsert_git_metadata_bulk,
+ )
+ from repowise.core.persistence.stores.sql_job_store import SqlJobStore
+
+ indexer = GitIndexer(
+ repo_path,
+ commit_limit=commit_limit,
+ follow_renames=follow_renames,
+ tier=GitIndexTier.FULL,
+ )
+
+ async with get_session(sf) as session:
+ job_store = SqlJobStore(session)
+ resumable = await job_store.find_resumable(repository_id=repo_id)
+ if any(j.phase == BACKFILL_PHASE for j in resumable):
+ console.print(
+ "[dim]Found an interrupted git backfill — resuming (re-running FULL tier).[/dim]"
+ )
+ summary, git_results = await backfill_full_tier(
+ indexer, repo_id, job_store=job_store
+ )
+ if git_results:
+ await upsert_git_metadata_bulk(session, repo_id, git_results)
+ await recompute_git_percentiles(session, repo_id)
+
+ console.print(
+ f"Git tier upgraded to FULL: [cyan]{summary.files_indexed}[/cyan] files "
+ "(per-file blame + co-change)."
+ )
+ return {m["file_path"]: m for m in git_results if m.get("file_path")}
+
+
+async def _run_upgrade(
+ repo_path: Path,
+ provider: Any,
+ config: Any,
+ *,
+ exclude_patterns: list[str],
+ commit_limit: int | None,
+ follow_renames: bool,
+) -> list[Any]:
+ """Drive the full upgrade and return the generated pages."""
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.generation.cost_tracker import CostTracker
+ from repowise.core.persistence import (
+ FullTextSearch,
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_page_from_generated,
+ upsert_repository,
+ )
+ from repowise.core.pipeline import rehydrate_graph_builder, run_generation
+
+ url = get_db_url_for_repo(repo_path)
+ engine = create_engine(url)
+ await init_db(engine)
+ sf = create_session_factory(engine)
+
+ # 1. Repo row FIRST — this is the fix for the deferred CLI job_store
+ # wiring: pipeline_jobs.repository_id is an FK to repositories.id, so the
+ # row must exist before the backfill creates its checkpoint job.
+ async with get_session(sf) as session:
+ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))
+ repo_id = repo.id
+
+ # 2. Backfill the git tier ESSENTIAL -> FULL (resumable via JobStore).
+ git_meta_map = await _backfill_git(
+ sf,
+ repo_id,
+ repo_path,
+ commit_limit=commit_limit,
+ follow_renames=follow_renames,
+ )
+
+ # 3. Rehydrate the graph from SQL — no parse, no resolution, no recompute.
+ async with get_session(sf) as session:
+ graph_builder = await rehydrate_graph_builder(session, repo_id, repo_path)
+
+ # 4. Re-parse for ASTs + source (the only unavoidable re-work). The graph
+ # is NOT rebuilt — generation traverses the rehydrated SQL graph.
+ parsed_files, source_map, repo_structure = _reparse(repo_path, exclude_patterns)
+ console.print(
+ f"Re-parsed [cyan]{len(parsed_files)}[/cyan] files for doc generation "
+ "(graph reused from index — not re-resolved)."
+ )
+
+ # 5. Generate the docs the fast index skipped.
+ cost_tracker = CostTracker(session_factory=sf, repo_id=repo_id)
+ provider._cost_tracker = cost_tracker
+ generated_pages = await run_generation(
+ repo_path=repo_path,
+ parsed_files=parsed_files,
+ source_map=source_map,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ git_meta_map=git_meta_map,
+ llm_client=provider,
+ embedder=None,
+ vector_store=None,
+ concurrency=config.max_concurrency,
+ progress=None,
+ cost_tracker=cost_tracker,
+ generation_config=config,
+ )
+
+ # 6. Persist pages + a GenerationJob marker, then build the FTS index.
+ async with get_session(sf) as session:
+ for page in generated_pages:
+ await upsert_page_from_generated(session, page, repo_id)
+ try:
+ from datetime import UTC, datetime
+
+ from repowise.core.persistence.crud import upsert_generation_job
+
+ now = datetime.now(UTC)
+ job = await upsert_generation_job(
+ session,
+ repository_id=repo_id,
+ status="completed",
+ total_pages=len(generated_pages),
+ config={"mode": "upgrade", "source": "cli_update_full"},
+ )
+ job.completed_pages = len(generated_pages)
+ job.started_at = now
+ job.finished_at = now
+ except Exception:
+ pass # job recording is best-effort
+
+ try:
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ for page in generated_pages:
+ await fts.index(page.page_id, page.title, page.content)
+ except Exception:
+ pass # FTS indexing is best-effort
+
+ await engine.dispose()
+ return generated_pages
+
+
+def upgrade_to_full(
+ repo_path: Path,
+ *,
+ provider_name: str | None,
+ model: str | None,
+ reasoning: str | None,
+ concurrency: int,
+) -> None:
+ """Upgrade a fast (index-only / ESSENTIAL git) index to a full one.
+
+ Backfills the git tier and generates the LLM docs the fast index skipped,
+ reusing the persisted graph instead of rebuilding it.
+ """
+ from repowise.cli.ui import load_dotenv
+ from repowise.core.generation import GenerationConfig
+
+ load_dotenv(repo_path)
+ state = load_state(repo_path)
+ if not state:
+ raise click.ClickException(
+ f"No existing index found at {repo_path}. Run `repowise init` first."
+ )
+
+ cfg = load_config(repo_path)
+ head = get_head_commit(repo_path)
+ start = time.monotonic()
+
+ # Provider is required — the fast index made no LLM calls, so the repo may
+ # not have one configured yet. resolve_provider surfaces a clear error.
+ provider = resolve_provider(provider_name, model, repo_path=repo_path)
+
+ config = GenerationConfig(
+ max_concurrency=concurrency,
+ language=cfg.get("language", "en"),
+ reasoning=resolve_reasoning(reasoning, cfg),
+ enable_onboarding=bool(cfg.get("enable_onboarding", True)),
+ )
+ tier1_top_n = cfg.get("tier1_top_n")
+ if tier1_top_n is not None:
+ config = dataclasses.replace(config, tier1_top_n=tier1_top_n)
+
+ exclude_patterns = list(cfg.get("exclude_patterns") or [])
+ commit_limit = cfg.get("commit_limit")
+ follow_renames = bool(cfg.get("follow_renames", False))
+
+ console.print(f"[bold]repowise update --full[/bold] — upgrading {repo_path}")
+ console.print(
+ f"Provider: [cyan]{provider.provider_name}[/cyan] / "
+ f"[cyan]{provider.model_name}[/cyan]. This generates docs for the whole repo."
+ )
+
+ generated_pages = run_async(
+ _run_upgrade(
+ repo_path,
+ provider,
+ config,
+ exclude_patterns=exclude_patterns,
+ commit_limit=commit_limit,
+ follow_renames=follow_renames,
+ )
+ )
+
+ # Flip persisted state to full so subsequent `repowise update` runs the
+ # normal incremental LLM path (docs_enabled) rather than offering upgrade.
+ state["last_sync_commit"] = head
+ state["docs_enabled"] = True
+ state["git_tier"] = "full"
+ state["total_pages"] = len(generated_pages)
+ save_state(repo_path, state)
+
+ elapsed = time.monotonic() - start
+ console.print(
+ f"[bold green]Upgrade complete[/bold green] in {elapsed:.1f}s — "
+ f"{len(generated_pages)} pages generated, git tier now FULL."
+ )
diff --git a/packages/core/src/repowise/core/ingestion/graph/README.md b/packages/core/src/repowise/core/ingestion/graph/README.md
index 33147a499..0197d3374 100644
--- a/packages/core/src/repowise/core/ingestion/graph/README.md
+++ b/packages/core/src/repowise/core/ingestion/graph/README.md
@@ -47,6 +47,18 @@ This is gated by the pipeline knob `OrchestratorMode` / `sql_backed_metrics`
(default off in standard mode; on in fast mode). Standard generation keeps the
graph live because it traverses it for context assembly.
+### Rehydrating a builder from SQL
+
+`GraphBuilder.from_persisted(nodes, edges, metrics)` rebuilds a finalized
+builder directly from persisted rows (`persistence.get_all_graph_nodes` /
+`get_all_graph_edges` / `get_graph_metrics`) — **without re-parsing or
+re-resolving** imports/calls/heritage. It reconstructs the NetworkX graph and
+calls `load_metrics_from_sql`, so the result is metric- and
+traversal-equivalent to the originally-built graph. This is what powers the
+incremental `repowise update --full` fast→full upgrade: doc generation runs
+against the rehydrated graph, skipping the expensive resolution + centrality
+recompute that the fast index already did.
+
## Internal layout
- `builder.py` — `GraphBuilder` core: node/edge construction + `build()`.
@@ -54,6 +66,7 @@ graph live because it traverses it for context assembly.
- `_resolvers.py` — `ResolveMixin`: heritage / member-read / call passes.
- `_edges.py` — `EdgesMixin`: co-change / dynamic / framework edges.
- `_serialize.py` — `SerializeMixin`: node-link JSON + SQLite export.
+- `_rehydrate.py` — `RehydrateMixin`: `from_persisted` rebuild from SQL rows.
- `_stem.py` — import-stem priority + stem-map construction.
## Extension points
diff --git a/packages/core/src/repowise/core/ingestion/graph/__init__.py b/packages/core/src/repowise/core/ingestion/graph/__init__.py
index 0772cdfca..93bbfea1b 100644
--- a/packages/core/src/repowise/core/ingestion/graph/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/graph/__init__.py
@@ -29,6 +29,7 @@ Internal layout (kept under the 400-line ceiling):
_resolvers.py — heritage / member-read / call resolution passes
_edges.py — co-change / dynamic / framework edges
_serialize.py — node-link JSON + SQLite export
+ _rehydrate.py — rebuild a builder from persisted nodes/edges/metrics
_stem.py — import-stem resolution helpers
"""
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
new file mode 100644
index 000000000..fafdbe80b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -0,0 +1,119 @@
+"""Rehydrate a :class:`GraphBuilder` from persisted graph rows.
+
+After a ``--mode fast`` index the in-memory :class:`GraphBuilder` is gone, but
+the structural graph it produced is fully persisted (``graph_nodes`` /
+``graph_edges``) together with the materialized centrality snapshot
+(``graph_metrics``). When upgrading a fast index to full (``repowise update
+--full``) we need a builder to drive doc generation — but re-resolving imports,
+calls, and heritage would redo the most expensive part of ingestion for no
+benefit, since the answer is already on disk.
+
+:meth:`RehydrateMixin.from_persisted` reconstructs the NetworkX graph from those
+rows and loads the file-level metric snapshot via
+:meth:`MetricsMixin.load_metrics_from_sql`, so PageRank / betweenness /
+community / degree are served straight from SQL with **no NetworkX recompute**
+and **no resolution pass**. The result is metric- and traversal-equivalent to
+the originally-built graph (proven in ``tests/unit/ingestion``).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+log = structlog.get_logger(__name__)
+
+# Node-dict keys that map onto NetworkX node attributes. ``node_id`` is the key
+# itself (handled separately) and is excluded here. ``None`` values are dropped
+# so file nodes don't carry empty symbol columns.
+_NODE_ATTR_KEYS = (
+ "node_type",
+ "language",
+ "symbol_count",
+ "has_error",
+ "is_test",
+ "is_entry_point",
+ "kind",
+ "name",
+ "qualified_name",
+ "file_path",
+ "start_line",
+ "end_line",
+ "visibility",
+ "signature",
+ "parent_symbol_id",
+)
+
+
+class RehydrateMixin:
+ """Construct a :class:`GraphBuilder` from persisted rows instead of ASTs."""
+
+ @classmethod
+ def from_persisted(
+ cls,
+ nodes: Iterable[Mapping[str, Any]],
+ edges: Iterable[Mapping[str, Any]],
+ metrics: Mapping[str, Mapping[str, Any]] | None = None,
+ *,
+ repo_path: Path | str | None = None,
+ ) -> Any:
+ """Rebuild a finalized builder from persisted nodes/edges/metrics.
+
+ *nodes* and *edges* are sequences of plain dicts as returned by
+ ``persistence.get_all_graph_nodes`` / ``get_all_graph_edges``. *metrics*
+ is the ``graph_metrics`` snapshot (``node_id → metrics``); when supplied
+ it pre-fills the file-level metric caches so no centrality kernel runs.
+
+ The returned builder has ``_built = True`` — it is ready for traversal
+ and generation; calling :meth:`build` again is neither needed nor done.
+ """
+ builder = cls(repo_path=repo_path) # type: ignore[call-arg]
+ graph = builder._graph
+
+ node_count = 0
+ for node in nodes:
+ node_id = node.get("node_id")
+ if node_id is None:
+ continue
+ attrs = {
+ key: node[key]
+ for key in _NODE_ATTR_KEYS
+ if node.get(key) is not None
+ }
+ # ``parent_symbol_id`` is persisted under that name but the live
+ # graph uses ``parent_name`` (see GraphBuilder.add_file).
+ if "parent_symbol_id" in attrs:
+ attrs["parent_name"] = attrs.pop("parent_symbol_id")
+ graph.add_node(node_id, **attrs)
+ node_count += 1
+
+ edge_count = 0
+ for edge in edges:
+ source = edge.get("source_node_id")
+ target = edge.get("target_node_id")
+ if source is None or target is None:
+ continue
+ edge_attrs: dict[str, Any] = {
+ "edge_type": edge.get("edge_type", "imports"),
+ "confidence": edge.get("confidence", 1.0),
+ }
+ imported_names = edge.get("imported_names")
+ if imported_names:
+ edge_attrs["imported_names"] = list(imported_names)
+ graph.add_edge(source, target, **edge_attrs)
+ edge_count += 1
+
+ builder._built = True
+ if metrics:
+ builder.load_metrics_from_sql(dict(metrics))
+
+ log.info(
+ "graph.rehydrated_from_sql",
+ nodes=node_count,
+ edges=edge_count,
+ metrics=len(metrics) if metrics else 0,
+ )
+ return builder
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 14fc94246..653824144 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -20,6 +20,7 @@ from ..resolvers.go import read_go_module_path, read_go_modules
from ..type_ref_resolution import resolve_type_refs
from ._edges import EdgesMixin
from ._metrics import MetricsMixin
+from ._rehydrate import RehydrateMixin
from ._resolvers import ResolveMixin
from ._serialize import SerializeMixin
from ._stem import build_stem_map
@@ -27,7 +28,7 @@ from ._stem import build_stem_map
log = structlog.get_logger(__name__)
-class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin):
+class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, RehydrateMixin):
"""Build a dependency graph from a collection of ParsedFile objects.
Usage::
diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.py
index 5d974bf2c..d56d76f48 100644
--- a/packages/core/src/repowise/core/persistence/__init__.py
+++ b/packages/core/src/repowise/core/persistence/__init__.py
@@ -31,6 +31,8 @@ from .crud import (
delete_repository,
get_all_file_metrics,
get_all_git_metadata,
+ get_all_graph_edges,
+ get_all_graph_nodes,
get_community_members,
get_conversation,
get_cross_community_edges,
@@ -172,6 +174,8 @@ __all__ = [
"get_all_file_metrics",
# git metadata crud
"get_all_git_metadata",
+ "get_all_graph_edges",
+ "get_all_graph_nodes",
"get_community_members",
"get_configured_db_url",
"get_conversation",
diff --git a/packages/core/src/repowise/core/persistence/crud.py b/packages/core/src/repowise/core/persistence/crud.py
index a43213c07..abb74c3a9 100644
--- a/packages/core/src/repowise/core/persistence/crud.py
+++ b/packages/core/src/repowise/core/persistence/crud.py
@@ -617,6 +617,77 @@ async def get_graph_metrics(
}
+async def get_all_graph_nodes(
+ session: AsyncSession,
+ repository_id: str,
+) -> list[dict]:
+ """Read every persisted graph node as a list of plain dicts.
+
+ Used to rehydrate an in-memory :class:`GraphBuilder` from SQL without
+ re-parsing or re-resolving the graph (see
+ ``repowise.core.pipeline.upgrade.rehydrate_graph_builder``). Each dict
+ carries ``node_id`` plus the file/symbol attributes that the NetworkX node
+ needs for traversal and rendering.
+ """
+ result = await session.execute(
+ select(GraphNode).where(GraphNode.repository_id == repository_id)
+ )
+ return [
+ {
+ "node_id": row.node_id,
+ "node_type": row.node_type,
+ "language": row.language,
+ "symbol_count": row.symbol_count,
+ "has_error": row.has_error,
+ "is_test": row.is_test,
+ "is_entry_point": row.is_entry_point,
+ "kind": row.kind,
+ "name": row.name,
+ "qualified_name": row.qualified_name,
+ "file_path": row.file_path,
+ "start_line": row.start_line,
+ "end_line": row.end_line,
+ "visibility": row.visibility,
+ "signature": row.signature,
+ "parent_symbol_id": row.parent_symbol_id,
+ }
+ for row in result.scalars().all()
+ ]
+
+
+async def get_all_graph_edges(
+ session: AsyncSession,
+ repository_id: str,
+) -> list[dict]:
+ """Read every persisted graph edge as a list of plain dicts.
+
+ Companion to :func:`get_all_graph_nodes` for graph rehydration. The
+ ``imported_names_json`` column is decoded back into a list so the
+ rehydrated edge matches the in-memory shape produced during ingestion.
+ """
+ import json as _json
+
+ result = await session.execute(
+ select(GraphEdge).where(GraphEdge.repository_id == repository_id)
+ )
+ edges: list[dict] = []
+ for row in result.scalars().all():
+ try:
+ imported_names = _json.loads(row.imported_names_json or "[]")
+ except (ValueError, TypeError):
+ imported_names = []
+ edges.append(
+ {
+ "source_node_id": row.source_node_id,
+ "target_node_id": row.target_node_id,
+ "edge_type": row.edge_type,
+ "confidence": row.confidence,
+ "imported_names": imported_names,
+ }
+ )
+ return edges
+
+
# ---------------------------------------------------------------------------
# ExternalSystem CRUD
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/pipeline/__init__.py b/packages/core/src/repowise/core/pipeline/__init__.py
index ff2108814..2bb45b116 100644
--- a/packages/core/src/repowise/core/pipeline/__init__.py
+++ b/packages/core/src/repowise/core/pipeline/__init__.py
@@ -14,6 +14,7 @@ from .orchestrator import PipelineResult, run_generation, run_pipeline
from .persist import persist_pipeline_result
from .phase_timing import PhaseTimingRecorder
from .progress import LoggingProgressCallback, ProgressCallback
+from .upgrade import rehydrate_graph_builder
__all__ = [
"LoggingProgressCallback",
@@ -21,6 +22,7 @@ __all__ = [
"PipelineResult",
"ProgressCallback",
"persist_pipeline_result",
+ "rehydrate_graph_builder",
"run_generation",
"run_pipeline",
]
diff --git a/packages/core/src/repowise/core/pipeline/upgrade.py b/packages/core/src/repowise/core/pipeline/upgrade.py
new file mode 100644
index 000000000..63c43aaae
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/upgrade.py
@@ -0,0 +1,64 @@
+"""Incremental fast→full upgrade helpers.
+
+A ``--mode fast`` index persists the full structural graph + materialized
+metrics but skips FULL git signals and LLM doc generation. Upgrading it to a
+full index should *not* redo the structural work: the graph is already on disk.
+
+:func:`rehydrate_graph_builder` reconstructs a finalized :class:`GraphBuilder`
+from the persisted ``graph_nodes`` / ``graph_edges`` / ``graph_metrics`` rows so
+doc generation can run against it without re-parsing, re-resolving imports/
+calls/heritage, or recomputing centrality. The git-tier backfill is handled
+separately by ``ingestion.git_indexer.backfill.backfill_full_tier``; the CLI
+``repowise update --full`` flow stitches the two together (see
+``cli.commands.upgrade_flow``).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+log = structlog.get_logger(__name__)
+
+
+async def rehydrate_graph_builder(
+ session: Any,
+ repo_id: str,
+ repo_path: Path | str | None = None,
+) -> Any:
+ """Rebuild a :class:`GraphBuilder` from persisted rows for *repo_id*.
+
+ Reads every persisted node and edge plus the materialized metric snapshot
+ and hands them to ``GraphBuilder.from_persisted``. The returned builder is
+ already finalized (``_built = True``) with file-level metrics served from
+ SQL — no NetworkX centrality kernel runs and no resolution pass fires.
+
+ Raises ``ValueError`` if the repo has no persisted graph nodes, which means
+ it was never indexed (so there is nothing to upgrade).
+ """
+ from repowise.core.ingestion.graph import GraphBuilder
+ from repowise.core.persistence import (
+ get_all_graph_edges,
+ get_all_graph_nodes,
+ get_graph_metrics,
+ )
+
+ nodes = await get_all_graph_nodes(session, repo_id)
+ if not nodes:
+ raise ValueError(
+ f"No persisted graph nodes for repo {repo_id!r}; run `repowise init` first."
+ )
+ edges = await get_all_graph_edges(session, repo_id)
+ metrics = await get_graph_metrics(session, repo_id)
+
+ builder = GraphBuilder.from_persisted(nodes, edges, metrics, repo_path=repo_path)
+ log.info(
+ "upgrade.graph_rehydrated",
+ repo_id=repo_id,
+ nodes=len(nodes),
+ edges=len(edges),
+ has_metrics=bool(metrics),
+ )
+ return builder
diff --git a/scripts/benchmark_upgrade.py b/scripts/benchmark_upgrade.py
new file mode 100644
index 000000000..86d54f332
--- /dev/null
+++ b/scripts/benchmark_upgrade.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""Benchmark the incremental fast→full upgrade vs a full re-index.
+
+The ``repowise update --full`` upgrade reuses the persisted dependency graph
+instead of rebuilding it. The structural work a full ``init`` re-run repeats —
+and the upgrade skips — is the graph build (import/call/heritage resolution)
+plus the centrality snapshot. Re-parsing and the FULL git tier happen either
+way, so the *delta* between the two paths is precisely:
+
+ full re-index structural cost = GraphBuilder.build() + file_metrics_snapshot()
+ upgrade structural cost = rehydrate_graph_builder() (SQL read, no resolve)
+
+This script measures both on a synthetic repo and reports the ratio.
+
+Usage::
+
+ python scripts/benchmark_upgrade.py # 2000 files
+ python scripts/benchmark_upgrade.py --files 5000
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import sys
+import tempfile
+import time
+from datetime import UTC, datetime
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO_ROOT / "scripts"))
+
+from benchmark_large_repo import _git, generate_synthetic_repo # noqa: E402
+
+
+def _parse_and_build(repo: Path) -> tuple[object, list, dict[str, bytes], float]:
+ """Parse the repo and build+resolve the graph. Returns (builder, parsed, src, secs)."""
+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+ traverser = FileTraverser(repo)
+ file_infos = list(traverser.traverse())
+ parser = ASTParser()
+ parsed_files = []
+ source_map: dict[str, bytes] = {}
+ builder = GraphBuilder(repo)
+ for fi in file_infos:
+ try:
+ src = Path(fi.abs_path).read_bytes()
+ parsed = parser.parse_file(fi, src)
+ parsed_files.append(parsed)
+ source_map[fi.path] = src
+ builder.add_file(parsed)
+ except Exception:
+ pass
+
+ t0 = time.monotonic()
+ builder.build() # import/call/heritage resolution — the expensive pass
+ builder.file_metrics_snapshot() # pagerank + betweenness + community + degree
+ structural_secs = time.monotonic() - t0
+ return builder, parsed_files, source_map, structural_secs
+
+
+async def _persist_and_rehydrate(repo: Path, builder: object) -> float:
+ """Persist the graph then time a rehydrate from SQL (the upgrade path)."""
+ from repowise.core.persistence import (
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.database import create_engine
+ from repowise.core.pipeline import rehydrate_graph_builder
+ from repowise.core.pipeline.persist import persist_graph_nodes
+
+ db_path = repo / "bench.db"
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path}")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ rec = await upsert_repository(session, name=repo.name, local_path=str(repo))
+ repo_id = rec.id
+ await persist_graph_nodes(session, repo_id, builder)
+ # Edges (mirrors persist_pipeline_result).
+ import json as _json
+
+ from repowise.core.persistence import batch_upsert_graph_edges
+
+ graph = builder.graph()
+ edges = [
+ {
+ "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 graph.edges(data=True)
+ ]
+ if edges:
+ await batch_upsert_graph_edges(session, repo_id, edges)
+
+ async with get_session(sf) as session:
+ t0 = time.monotonic()
+ await rehydrate_graph_builder(session, repo_id, repo)
+ rehydrate_secs = time.monotonic() - t0
+
+ await engine.dispose()
+ return rehydrate_secs
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--files", type=int, default=2000, help="Number of source files.")
+ parser.add_argument("--commits", type=int, default=20, help="Number of git commits.")
+ args = parser.parse_args(argv)
+
+ tmp = Path(tempfile.mkdtemp(prefix="repowise-bench-upgrade-"))
+ repo = tmp / "repo"
+ n = generate_synthetic_repo(repo, args.files, args.commits)
+ print(f"Generated {n} files. Measuring structural cost ...")
+
+ builder, _parsed, _src, rebuild_secs = _parse_and_build(repo)
+ rehydrate_secs = asyncio.run(_persist_and_rehydrate(repo, builder))
+
+ speedup = (rebuild_secs / rehydrate_secs) if rehydrate_secs else float("inf")
+ print(f" full re-index structural (build+metrics): {rebuild_secs:.3f}s")
+ print(f" upgrade structural (rehydrate from SQL): {rehydrate_secs:.3f}s")
+ print(f" speedup on the avoided work: {speedup:.1f}x")
+
+ out_dir = REPO_ROOT / "bench" / "results"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ try:
+ sha = _git(REPO_ROOT, "rev-parse", "--short", "HEAD")
+ except Exception:
+ sha = "nogit"
+ out = out_dir / f"upgrade-{sha}.json"
+ out.write_text(
+ json.dumps(
+ {
+ "timestamp": datetime.now(UTC).isoformat(),
+ "files": n,
+ "rebuild_structural_secs": round(rebuild_secs, 3),
+ "rehydrate_secs": round(rehydrate_secs, 3),
+ "speedup": round(speedup, 1),
+ },
+ indent=2,
+ )
+ )
+ print(f"Wrote {out}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/integration/test_upgrade_fast_to_full.py b/tests/integration/test_upgrade_fast_to_full.py
new file mode 100644
index 000000000..d5b0a225a
--- /dev/null
+++ b/tests/integration/test_upgrade_fast_to_full.py
@@ -0,0 +1,128 @@
+"""End-to-end fast→full upgrade: rehydrate + backfill + generate, no re-resolve.
+
+Runs the real pipeline against the sample repo with ``--mode fast`` (no LLM),
+persists it, then exercises the incremental upgrade path:
+
+* the dependency graph is rehydrated from SQL and is structurally + metric-
+ equivalent to the fast build;
+* the git tier is backfilled ESSENTIAL → FULL via the resumable worker, and the
+ JobStore records a COMPLETED ``git.backfill`` checkpoint;
+* docs are generated (mock LLM) against the rehydrated graph;
+* **no graph resolution runs during the upgrade** — ``GraphBuilder.build`` is
+ spied and asserted to be called zero times after the fast index.
+
+No external services; the only LLM is the deterministic ``MockProvider``.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.ingestion.git_indexer import GitIndexer, GitIndexTier
+from repowise.core.ingestion.git_indexer.backfill import BACKFILL_PHASE, backfill_full_tier
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.persistence import init_db, upsert_repository
+from repowise.core.persistence._interfaces.job_store import JobState
+from repowise.core.persistence.stores.sql_job_store import SqlJobStore
+from repowise.core.pipeline import (
+ persist_pipeline_result,
+ rehydrate_graph_builder,
+ run_generation,
+ run_pipeline,
+)
+from repowise.core.pipeline.modes import OrchestratorMode
+from repowise.core.providers.llm.mock import MockProvider
+
+
+async def session():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with factory() as s:
+ yield s
+ await engine.dispose()
+
+
+async def test_fast_index_then_full_upgrade(
+ sample_repo_path: Path,
+ session: AsyncSession,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # --- 1. Fast index + persist (ESSENTIAL git, no docs). ---
+ repo = await upsert_repository(session, name="sample", local_path=str(sample_repo_path))
+ repo_id = repo.id
+
+ result = await run_pipeline(sample_repo_path, mode=OrchestratorMode.FAST)
+ assert result.generated_pages is None # FAST never generates docs
+ assert result.git_metadata_list, "expected git metadata for the sample repo"
+ assert all(
+ m.get("co_change_partners_json", "[]") == "[]" for m in result.git_metadata_list
+ ), "ESSENTIAL tier should not compute co-change"
+
+ await persist_pipeline_result(result, session, repo_id)
+ await session.commit()
+
+ original_nodes = result.graph_builder.graph().number_of_nodes()
+ original_edges = result.graph_builder.graph().number_of_edges()
+ original_pagerank = result.graph_builder.pagerank()
+
+ # --- 2. Forbid graph resolution for the rest of the test. Any rebuild of
+ # the graph during the upgrade is a regression — the persisted graph must
+ # be reused as-is. ---
+ build_calls = {"n": 0}
+ real_build = GraphBuilder.build
+
+ def _spy_build(self, *args, **kwargs):
+ build_calls["n"] += 1
+ return real_build(self, *args, **kwargs)
+
+ monkeypatch.setattr(GraphBuilder, "build", _spy_build)
+
+ # --- 3. Rehydrate the graph from SQL — equivalence + zero resolution. ---
+ rehydrated = await rehydrate_graph_builder(session, repo_id, sample_repo_path)
+ assert rehydrated.graph().number_of_nodes() == original_nodes
+ assert rehydrated.graph().number_of_edges() == original_edges
+ assert rehydrated.pagerank() == original_pagerank
+ assert build_calls["n"] == 0, "rehydration must not re-resolve the graph"
+
+ # --- 4. Backfill the git tier ESSENTIAL -> FULL (resumable via JobStore). ---
+ indexer = GitIndexer(sample_repo_path, tier=GitIndexTier.FULL)
+ job_store = SqlJobStore(session)
+ summary, git_results = await backfill_full_tier(indexer, repo_id, job_store=job_store)
+ await session.commit()
+
+ backfill_jobs = await job_store.list_jobs(repository_id=repo_id, phase=BACKFILL_PHASE)
+ assert backfill_jobs, "backfill should record a JobStore checkpoint"
+ assert backfill_jobs[0].state is JobState.COMPLETED
+ assert summary.files_indexed >= 0
+
+ # --- 5. Generate docs against the rehydrated graph (mock LLM). The jobs
+ # dir is routed to tmp_path so the sample fixture stays clean. ---
+ git_meta_map = {m["file_path"]: m for m in git_results if m.get("file_path")}
+ pages = await run_generation(
+ repo_path=tmp_path,
+ parsed_files=result.parsed_files,
+ source_map=result.source_map,
+ graph_builder=rehydrated,
+ repo_structure=result.repo_structure,
+ git_meta_map=git_meta_map,
+ llm_client=MockProvider(),
+ embedder=None,
+ vector_store=None,
+ concurrency=2,
+ progress=None,
+ )
+
+ assert pages, "the upgrade should generate the docs the fast index skipped"
+ # The entire upgrade (rehydrate + backfill + generate) ran no graph build.
+ assert build_calls["n"] == 0, "the upgrade must not re-resolve the graph"
diff --git a/tests/unit/ingestion/test_git_backfill_resume.py b/tests/unit/ingestion/test_git_backfill_resume.py
new file mode 100644
index 000000000..84ce6b1df
--- /dev/null
+++ b/tests/unit/ingestion/test_git_backfill_resume.py
@@ -0,0 +1,115 @@
+"""Crash-resume contract for the git-tier backfill worker.
+
+``backfill_full_tier`` brackets its run in a JobStore record so an interrupted
+backfill is detectable and re-runnable. These tests cover the two failure
+shapes:
+
+* an in-process exception → the job is marked FAILED with the error;
+* a hard kill mid-run → the job is left RUNNING (orphaned) and is reported by
+ ``find_resumable`` so a re-run can pick it up (and completes cleanly).
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.ingestion.git_indexer import GitIndexTier
+from repowise.core.ingestion.git_indexer.backfill import BACKFILL_PHASE, backfill_full_tier
+from repowise.core.persistence._interfaces.job_store import JobRecord, JobState
+
+
+class _FakeJobStore:
+ def __init__(self) -> None:
+ self.jobs: dict[str, JobRecord] = {}
+ self._seq = 0
+
+ async def create_job(self, *, repository_id, phase, metadata=None) -> JobRecord:
+ self._seq += 1
+ jid = f"job{self._seq}"
+ now = datetime.now(UTC)
+ rec = JobRecord(
+ jid, repository_id, phase, JobState.PENDING, None, now, now, None, metadata or {}
+ )
+ self.jobs[jid] = rec
+ return rec
+
+ async def update_state(self, job_id, state, *, cursor=None, error=None) -> JobRecord:
+ old = self.jobs[job_id]
+ rec = JobRecord(
+ old.id, old.repository_id, old.phase, state, cursor or old.cursor,
+ old.started_at, datetime.now(UTC), error, old.metadata,
+ )
+ self.jobs[job_id] = rec
+ return rec
+
+ async def find_resumable(self, *, repository_id=None) -> list[JobRecord]:
+ return [
+ j
+ for j in self.jobs.values()
+ if j.state in (JobState.PENDING, JobState.RUNNING)
+ and (repository_id is None or j.repository_id == repository_id)
+ ]
+
+
+class _FlakyIndexer:
+ """Fake GitIndexer that fails its first *fail_times* index_repo calls."""
+
+ def __init__(self, fail_times: int = 0) -> None:
+ self.tier = GitIndexTier.ESSENTIAL
+ self._fail_times = fail_times
+ self.calls = 0
+
+ async def index_repo(self, repo_id: str):
+ self.calls += 1
+ # backfill must force FULL for the duration of the run.
+ assert self.tier is GitIndexTier.FULL
+ if self.calls <= self._fail_times:
+ raise RuntimeError("simulated git crash")
+ return SimpleNamespace(files_indexed=3), [{"file_path": "a.py"}]
+
+
+async def test_backfill_exception_marks_job_failed_and_restores_tier():
+ store = _FakeJobStore()
+ indexer = _FlakyIndexer(fail_times=1)
+
+ with pytest.raises(RuntimeError):
+ await backfill_full_tier(indexer, "repo1", job_store=store)
+
+ failed = [j for j in store.jobs.values() if j.state is JobState.FAILED]
+ assert len(failed) == 1
+ assert failed[0].phase == BACKFILL_PHASE
+ assert failed[0].error and "simulated git crash" in failed[0].error
+ # Tier is restored to its original value even on failure.
+ assert indexer.tier is GitIndexTier.ESSENTIAL
+
+
+async def test_orphaned_running_backfill_is_resumable_then_completes():
+ store = _FakeJobStore()
+
+ # Simulate a hard kill mid-backfill: a RUNNING git.backfill job left behind.
+ orphan = await store.create_job(repository_id="repo1", phase=BACKFILL_PHASE)
+ await store.update_state(orphan.id, JobState.RUNNING)
+
+ resumable = await store.find_resumable(repository_id="repo1")
+ assert any(j.phase == BACKFILL_PHASE for j in resumable)
+
+ # Re-run completes cleanly (FULL tier is re-run, per the worker's contract).
+ indexer = _FlakyIndexer(fail_times=0)
+ summary, results = await backfill_full_tier(indexer, "repo1", job_store=store)
+
+ assert summary.files_indexed == 3
+ assert results == [{"file_path": "a.py"}]
+ completed = [j for j in store.jobs.values() if j.state is JobState.COMPLETED]
+ assert len(completed) == 1
+ assert completed[0].cursor == "3"
+
+
+async def test_backfill_runs_without_job_store():
+ """JobStore is optional — the worker still runs and forces FULL."""
+ indexer = _FlakyIndexer(fail_times=0)
+ summary, _results = await backfill_full_tier(indexer, "repo1")
+ assert summary.files_indexed == 3
+ assert indexer.tier is GitIndexTier.ESSENTIAL # restored
diff --git a/tests/unit/ingestion/test_graph_rehydrate.py b/tests/unit/ingestion/test_graph_rehydrate.py
new file mode 100644
index 000000000..23ebb09c8
--- /dev/null
+++ b/tests/unit/ingestion/test_graph_rehydrate.py
@@ -0,0 +1,141 @@
+"""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
+
+
+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", []),
+ }
+ )
+ 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_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