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.

test(update): end-to-end layer-freshness, torn-persist rollback, lock contention, checkpointer coverage (#707)

Raghav Chamadiya8143c75bf87f
diff --git a/tests/unit/cli/test_update_e2e.py b/tests/unit/cli/test_update_e2e.py
new file mode 100644
index 000000000..3566c255f
--- /dev/null
+++ b/tests/unit/cli/test_update_e2e.py
@@ -0,0 +1,168 @@
+"""End-to-end ``repowise update`` on a real fixture repo.
+
+The test that would have caught #669: a real (index-only) full pipeline run
+seeds wiki.db, a new commit lands, and one CliRunner ``update`` invocation
+must refresh every index layer — graph nodes, health metrics, the knowledge
+graph rows AND the exported knowledge-graph.json, the DB head_commit stamp,
+and state.json — not just the subset the incremental path happened to touch.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+from pathlib import Path
+
+from click.testing import CliRunner
+from sqlalchemy import select
+
+from repowise.cli.main import cli
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _git(repo: Path, *args: str) -> str:
+ result = subprocess.run(["git", *args], cwd=str(repo), capture_output=True, text=True)
+ return result.stdout.strip()
+
+
+def _make_git_repo(tmp_path: Path) -> Path:
+ repo = tmp_path / "repo"
+ repo.mkdir(parents=True)
+ _git(repo, "init")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "Test")
+ (repo / "a.py").write_text("def alpha():\n return 1\n")
+ (repo / "b.py").write_text("from a import alpha\n\n\ndef beta():\n return alpha() + 1\n")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "initial")
+ return repo
+
+
+def _index_full(repo: Path) -> None:
+ """Real index-only init: full pipeline + persistence + KG artifact."""
+ from repowise.core.pipeline.full_index import index_repo_full
+
+ asyncio.run(index_repo_full(repo))
+
+
+async def _db_snapshot(repo: Path) -> dict:
+ """Read the layers the update must keep fresh from wiki.db."""
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ )
+ from repowise.core.persistence.database import resolve_db_url
+ from repowise.core.persistence.models import (
+ GraphNode,
+ HealthFileMetric,
+ KnowledgeGraphLayer,
+ Repository,
+ )
+
+ engine = create_engine(resolve_db_url(repo))
+ try:
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ repo_row = (await session.execute(select(Repository))).scalars().first()
+ graph_node_ids = {
+ n.node_id for n in (await session.execute(select(GraphNode))).scalars()
+ }
+ health_paths = {
+ m.file_path for m in (await session.execute(select(HealthFileMetric))).scalars()
+ }
+ kg_layer_count = len(
+ list((await session.execute(select(KnowledgeGraphLayer))).scalars())
+ )
+ return {
+ "head_commit": repo_row.head_commit if repo_row else None,
+ "graph_node_ids": graph_node_ids,
+ "health_paths": health_paths,
+ "kg_layer_count": kg_layer_count,
+ }
+ finally:
+ await engine.dispose()
+
+
+# ---------------------------------------------------------------------------
+# The test
+# ---------------------------------------------------------------------------
+
+
+def test_update_refreshes_every_index_layer(tmp_path: Path) -> None:
+ repo = _make_git_repo(tmp_path)
+ _index_full(repo)
+
+ base = _git(repo, "rev-parse", "HEAD")
+ from repowise.cli.helpers import save_state
+
+ save_state(repo, {"last_sync_commit": base, "docs_enabled": False})
+
+ kg_path = repo / ".repowise" / "knowledge-graph.json"
+ assert kg_path.is_file(), "init must export the KG artifact"
+ assert "c.py" not in kg_path.read_text(encoding="utf-8")
+
+ # A new file changes the graph shape, so every layer must move.
+ (repo / "c.py").write_text(
+ "from b import beta\n\n\ndef gamma():\n return beta() * 2\n"
+ )
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "add c.py")
+ new_head = _git(repo, "rev-parse", "HEAD")
+
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])
+ assert result.exit_code == 0, result.output
+
+ # state.json advanced.
+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state["last_sync_commit"] == new_head
+
+ snap = asyncio.run(_db_snapshot(repo))
+ # DB freshness stamp (the /repos + MCP _meta signal) matches HEAD.
+ assert snap["head_commit"] == new_head
+ # Graph rows include the new file.
+ assert "c.py" in snap["graph_node_ids"]
+ # Health metrics were computed for the new file.
+ assert "c.py" in snap["health_paths"]
+ # KG rows exist (layers persisted by the refresh, not just at init).
+ assert snap["kg_layer_count"] >= 1
+
+ # The exported artifact was rewritten for the new graph shape (#669:
+ # this file used to stay frozen at init forever), and state.json carries
+ # the refreshed fingerprint that gates the next rebuild.
+ kg_after = json.loads(kg_path.read_text(encoding="utf-8"))
+ assert any("c.py" in (n.get("filePath") or n.get("id") or "") for n in kg_after["nodes"])
+ assert state.get("knowledge_graph", {}).get("fingerprint")
+
+
+def test_update_degrades_visibly_when_a_step_fails(tmp_path: Path, monkeypatch) -> None:
+ """A failing best-effort persist step must surface in the degraded list
+ (exit 0, warning block rendered) instead of being silently swallowed."""
+ repo = _make_git_repo(tmp_path)
+ _index_full(repo)
+
+ base = _git(repo, "rev-parse", "HEAD")
+ from repowise.cli.helpers import save_state
+
+ save_state(repo, {"last_sync_commit": base, "docs_enabled": False})
+
+ (repo / "c.py").write_text("def gamma():\n return 3\n")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "add c.py")
+
+ import repowise.core.pipeline.persist as persist_mod
+
+ async def _boom(*args, **kwargs):
+ raise RuntimeError("graph nodes exploded")
+
+ monkeypatch.setattr(persist_mod, "persist_graph_nodes", _boom)
+
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])
+
+ assert result.exit_code == 0, result.output
+ assert "degraded step(s)" in result.output
+ assert "Graph nodes persist" in result.output
diff --git a/tests/unit/cli/test_update_persist_reliability.py b/tests/unit/cli/test_update_persist_reliability.py
new file mode 100644
index 000000000..ddcbe6a1f
--- /dev/null
+++ b/tests/unit/cli/test_update_persist_reliability.py
@@ -0,0 +1,192 @@
+"""Reliability contracts of the update persistence layer.
+
+Pins the three PR-3 behaviors: the full-mode persist is one transaction (a
+mid-persist failure rolls everything back instead of leaving a torn store),
+lock acquisition is atomic under contention (exactly one winner), and the
+page checkpointer degrades to a no-op instead of breaking generation.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select
+
+from repowise.cli.commands.update_cmd.persistence import (
+ PageCheckpointer,
+ _persist_full_update_async,
+)
+from repowise.core.generation.models import GeneratedPage
+
+
+def _page(page_id: str) -> GeneratedPage:
+ now = datetime.now(UTC).isoformat()
+ return GeneratedPage(
+ page_id=page_id,
+ page_type="file_page",
+ title=page_id,
+ content=f"# {page_id}\n",
+ source_hash="deadbeef",
+ model_name="mock-model",
+ provider_name="mock",
+ input_tokens=1,
+ output_tokens=1,
+ cached_tokens=0,
+ generation_level=1,
+ target_path=page_id.split(":", 1)[-1],
+ created_at=now,
+ updated_at=now,
+ )
+
+
+class _BombPage:
+ """A page whose first attribute access explodes mid-upsert."""
+
+ def __getattr__(self, name: str):
+ raise RuntimeError("torn mid-persist")
+
+
+async def _count_pages(repo_path: Path) -> int:
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.models import Page
+
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ try:
+ sf = create_session_factory(engine)
+ async with get_session(sf) as session:
+ return len(list((await session.execute(select(Page))).scalars()))
+ finally:
+ await engine.dispose()
+
+
+# ---------------------------------------------------------------------------
+# Torn persist rolls back atomically
+# ---------------------------------------------------------------------------
+
+
+def test_torn_full_persist_rolls_back_all_pages(tmp_path: Path) -> None:
+ """Page upserts run in ONE transaction: if the third page fails, the two
+ already-upserted pages must not survive as a torn half-persist."""
+ (tmp_path / ".repowise").mkdir()
+
+ with pytest.raises(RuntimeError, match="torn mid-persist"):
+ asyncio.run(
+ _persist_full_update_async(
+ repo_path=tmp_path,
+ repo_name="repo",
+ generated_pages=[_page("file_page:a.py"), _page("file_page:b.py"), _BombPage()],
+ file_diffs=[],
+ git_meta_map={},
+ new_decision_markers=[],
+ decision_vector_store=None,
+ provider=None,
+ partial_health_report=None,
+ dead_code_report=None,
+ graph_builder=None,
+ knowledge_graph_result=None,
+ degraded=[],
+ )
+ )
+
+ assert asyncio.run(_count_pages(tmp_path)) == 0
+
+
+def test_full_persist_collects_degraded_steps(tmp_path: Path) -> None:
+ """A best-effort step failure lands in the degraded list; pages commit."""
+ (tmp_path / ".repowise").mkdir()
+ degraded: list[str] = []
+
+ asyncio.run(
+ _persist_full_update_async(
+ repo_path=tmp_path,
+ repo_name="repo",
+ generated_pages=[_page("file_page:a.py")],
+ file_diffs=[],
+ git_meta_map={},
+ new_decision_markers=[],
+ decision_vector_store=None,
+ provider=None,
+ partial_health_report=None,
+ dead_code_report=None,
+ # persist_graph_nodes(None) raises -> degraded, not fatal.
+ graph_builder=None,
+ knowledge_graph_result=None,
+ degraded=degraded,
+ )
+ )
+
+ assert asyncio.run(_count_pages(tmp_path)) == 1
+ assert any(entry.startswith("Graph nodes persist:") for entry in degraded)
+
+
+# ---------------------------------------------------------------------------
+# Lock contention: exactly one winner
+# ---------------------------------------------------------------------------
+
+
+def test_concurrent_acquire_has_exactly_one_winner(tmp_path: Path) -> None:
+ from repowise.core.update_lock import try_acquire_update_lock
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ results = list(
+ pool.map(lambda i: try_acquire_update_lock(tmp_path, f"c{i}"), range(8))
+ )
+
+ winners = [r for r in results if r is None]
+ losers = [r for r in results if r is not None]
+ assert len(winners) == 1
+ # Every loser saw the winner's live payload, not a half-written file.
+ assert all(loser.get("pid") for loser in losers)
+
+
+# ---------------------------------------------------------------------------
+# PageCheckpointer
+# ---------------------------------------------------------------------------
+
+
+def test_checkpointer_persists_pages_as_they_land(tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+
+ async def _run() -> PageCheckpointer:
+ # Real schema, like the update path (init created it long before).
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import create_engine, init_db
+
+ engine = create_engine(get_db_url_for_repo(tmp_path))
+ await init_db(engine)
+ await engine.dispose()
+
+ cp = PageCheckpointer(tmp_path, "repo")
+ await cp.start()
+ cp.on_page_ready(_page("file_page:a.py"))
+ cp.on_page_ready(_page("file_page:b.py"))
+ await cp.close()
+ return cp
+
+ cp = asyncio.run(_run())
+ assert cp.failure is None
+ assert cp.persisted == 2
+ assert asyncio.run(_count_pages(tmp_path)) == 2
+
+
+def test_checkpointer_failure_degrades_without_hanging(tmp_path: Path) -> None:
+ """No schema (init_db never ran here): the first write fails, the sink
+ flips off, and close() still returns promptly."""
+ (tmp_path / ".repowise").mkdir()
+
+ async def _run() -> PageCheckpointer:
+ cp = PageCheckpointer(tmp_path, "repo")
+ await cp.start()
+ cp.on_page_ready(_page("file_page:a.py"))
+ cp.on_page_ready(_page("file_page:b.py"))
+ await cp.close()
+ return cp
+
+ cp = asyncio.run(asyncio.wait_for(_run(), timeout=30))
+ assert cp.failure is not None
+ assert cp.persisted == 0