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(index): persist analyzed symbol complexity (#2236)
Raghav Chamadiyaf59ec25ba1b0
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.pyindex 33aa06463..10439bfbd 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py@@ -136,6 +136,7 @@ async def persist_result(timed,tombstone_absent_file_pages,)+ from repowise.core.pipeline.persist import persist_symbol_analysisengine, sf, _repo_id = await open_repo_db(repo_path, repo_name=result.repo_name)@@ -174,6 +175,15 @@ async def persist_result(repo.settings_json = _json.dumps(existing)swept_page_ids: list[str] = []if index_done:+ # Health runs after the INDEX checkpoint and mutates the in-memory+ # symbol complexities. Reconcile them again in this final required+ # transaction: it heals a best-effort checkpoint failure, and if+ # this write also fails the ledger below cannot claim ANALYSIS is+ # complete with parser-default complexity still on disk.+ if getattr(result, "health_report", None) is not None:+ await persist_symbol_analysis(+ session, repo.id, getattr(result, "parsed_files", None)+ )await persist_analysis(result, session, repo.id)await persist_generation(result, session, repo.id)# persist_generation has already upserted the current pages, so thediff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 057c92d3d..6b74155f6 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -649,6 +649,7 @@ async def run_pipeline(# rehydrated analysis (it's by definition persisted) — best-effort.if resume_controller is not None and not skip_analysis:await resume_controller.checkpoint_analysis(+ parsed_files=parsed_files,dead_code_report=dead_code_report,health_report=health_report,decision_report=decision_report,diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 35c67ff61..8e31a1224 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -589,6 +589,33 @@ async def persist_incremental_symbols(await reconcile_symbols_for_files(session, repo_id, reconcile_paths, symbols)+async def persist_symbol_analysis(+ session: Any,+ repo_id: str,+ parsed_files: list[Any] | None,+) -> None:+ """Reconcile symbol rows after analysis mutates their derived fields.++ Health analysis computes ``complexity_estimate`` on the in-memory symbols+ after the resumable INDEX checkpoint has already persisted the parser+ defaults. Re-upsert just those symbol records before ANALYSIS is marked+ complete; graph construction, Git analysis, and the rest of ingestion stay+ untouched. The upsert preserves each persisted row's database identity.+ """+ if not parsed_files:+ return+ from repowise.core.persistence.crud import batch_upsert_symbols++ symbols: list[Any] = []+ for pf in parsed_files:+ for sym in pf.symbols:+ if not getattr(sym, "file_path", None):+ sym.file_path = pf.file_info.path+ symbols.append(sym)+ if symbols:+ await batch_upsert_symbols(session, repo_id, symbols)++def _changed_file_edges(graph_builder: Any,parsed_files: list[Any] | None,diff --git a/packages/core/src/repowise/core/pipeline/resume/controller.py b/packages/core/src/repowise/core/pipeline/resume/controller.pyindex 20b9ce393..ea47f9a9b 100644--- a/packages/core/src/repowise/core/pipeline/resume/controller.py+++ b/packages/core/src/repowise/core/pipeline/resume/controller.py@@ -25,7 +25,7 @@ from typing import Anyimport structlog-from ..persist import persist_analysis, persist_git, persist_ingestion+from ..persist import persist_analysis, persist_git, persist_ingestion, persist_symbol_analysisfrom ..progress import emit_warningfrom .ledger import ResumeLedgerfrom .phases import RESUME_PHASE_ORDER, ResumePhase@@ -188,6 +188,7 @@ class ResumeController:async def checkpoint_analysis(self,*,+ parsed_files: list[Any],dead_code_report: Any | None,health_report: Any | None,decision_report: Any | None,@@ -217,6 +218,7 @@ class ResumeController:await self._ledger.mark_started(ResumePhase.ANALYSIS)try:async with get_session(self._sf) as session:+ await persist_symbol_analysis(session, self._repo_id, parsed_files)await persist_analysis(view, session, self._repo_id)except Exception as exc:logger.warning("resume_checkpoint_analysis_failed", error=str(exc))diff --git a/tests/integration/test_symbol_complexity_parity.py b/tests/integration/test_symbol_complexity_parity.pynew file mode 100644index 000000000..b79c64e12--- /dev/null+++ b/tests/integration/test_symbol_complexity_parity.py@@ -0,0 +1,194 @@+"""Persisted symbol complexity agrees across full, update, and resume paths."""++from __future__ import annotations++import asyncio+import os+import shutil+import sqlite3+import subprocess+from contextlib import closing+from pathlib import Path++import pytest+from click.testing import CliRunner++from repowise.cli.helpers import release_update_lock+from repowise.cli.main import cli+from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+)+from repowise.core.persistence.crud import upsert_repository+from repowise.core.persistence.database import resolve_db_url+from repowise.core.pipeline import run_pipeline+from repowise.core.pipeline.full_index import index_repo_full+from repowise.core.pipeline.modes import OrchestratorMode+from repowise.core.pipeline.resume import ResumeController, ResumeLedger, ResumePhase++SOURCE = """def branch(value):+ if value:+ return 1+ return 0+"""+++def _git(repo: Path, *args: str) -> None:+ env = {+ **os.environ,+ "GIT_AUTHOR_NAME": "Complexity Parity",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Complexity Parity",+ "GIT_COMMITTER_EMAIL": "[email protected]",+ }+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, env=env)+++def _make_repo(path: Path) -> None:+ path.mkdir(parents=True)+ (path / "probe.py").write_text(SOURCE, encoding="utf-8")+ _git(path, "init", "-q")+ _git(path, "add", "-A")+ _git(path, "commit", "-q", "-m", "initial")+++def _copy_without_index(source: Path, destination: Path) -> None:+ shutil.copytree(source, destination, ignore=shutil.ignore_patterns(".repowise"))+ (destination / ".repowise").mkdir()+++def _invoke(runner: CliRunner, repo: Path, *args: str) -> None:+ try:+ result = runner.invoke(cli, [*args, str(repo)], catch_exceptions=False)+ assert result.exit_code == 0, result.output+ finally:+ release_update_lock(repo)+++def _symbol_snapshot(repo: Path) -> list[tuple[str, int]]:+ with closing(sqlite3.connect(repo / ".repowise" / "wiki.db")) as connection:+ return connection.execute(+ "SELECT symbol_id, complexity_estimate FROM wiki_symbols ORDER BY symbol_id"+ ).fetchall()+++async def _leave_index_checkpoint(repo: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ engine = create_engine(resolve_db_url(repo))+ try:+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ row = await upsert_repository(session, name=repo.name, local_path=str(repo))++ import repowise.core.pipeline.orchestrator as orchestrator++ async def _interrupt_analysis(*_args: object, **_kwargs: object) -> None:+ raise RuntimeError("simulated interruption after INDEX")++ with monkeypatch.context() as patch:+ patch.setattr(orchestrator, "_run_health_analysis", _interrupt_analysis)+ with pytest.raises(RuntimeError, match="simulated interruption"):+ await run_pipeline(+ repo,+ mode=OrchestratorMode.FAST,+ resume_controller=ResumeController(sf, row.id, resume=False),+ )++ completed = await ResumeLedger(sf, row.id).completed_phases()+ assert ResumePhase.INDEX in completed+ assert ResumePhase.ANALYSIS not in completed+ finally:+ await engine.dispose()+++async def _resume_after_index(repo: Path) -> None:+ engine = create_engine(resolve_db_url(repo))+ try:+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ row = await upsert_repository(session, name=repo.name, local_path=str(repo))+ await run_pipeline(+ repo,+ mode=OrchestratorMode.FAST,+ resume_controller=ResumeController(sf, row.id, resume=True),+ )+ finally:+ await engine.dispose()+++def test_symbol_complexity_parity_across_clean_incremental_resume_and_workspace(+ tmp_path: Path, monkeypatch+) -> None:+ incremental = tmp_path / "incremental" / "repo"+ _make_repo(incremental)+ runner = CliRunner()+ init_args = (+ "init",+ "--mode",+ "fast",+ "--no-editor-setup",+ "--no-hook",+ "--no-agents",+ "--no-codex",+ "--no-claude-md",+ "--no-cost-tracking",+ "--no-workspace",+ "-y",+ )++ monkeypatch.setenv(+ "REPOWISE_DB_URL", f"sqlite+aiosqlite:///{incremental / '.repowise' / 'wiki.db'}"+ )+ _invoke(runner, incremental, *init_args)+ with (incremental / "probe.py").open("a", encoding="utf-8") as source:+ source.write("\n# harmless incremental edit\n")+ _git(incremental, "add", "-A")+ _git(incremental, "commit", "-q", "-m", "harmless edit")++ clean = tmp_path / "clean" / "repo"+ resume = tmp_path / "resume" / "repo"+ workspace = tmp_path / "workspace" / "repo"+ for target in (clean, resume, workspace):+ _copy_without_index(incremental, target)++ _invoke(runner, incremental, "update", "--index-only", "--no-workspace", "--no-agents")++ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{clean / '.repowise' / 'wiki.db'}")+ import repowise.core.pipeline.resume.controller as resume_controller_module++ async def _fail_checkpoint_reconciliation(*_args: object, **_kwargs: object) -> None:+ raise RuntimeError("simulated symbol checkpoint failure")++ # The mid-run checkpoint is best-effort. The final required persistence+ # transaction must retry the symbol reconciliation before it marks ANALYSIS+ # complete, so this clean run still converges rather than storing CCN=1.+ with monkeypatch.context() as patch:+ patch.setattr(+ resume_controller_module,+ "persist_symbol_analysis",+ _fail_checkpoint_reconciliation,+ )+ _invoke(runner, clean, *init_args)+ # A later CLI resume re-parses source but reuses the completed analysis.+ # Final persistence must not replace its computed CCN with parser defaults.+ _invoke(runner, clean, *init_args, "--resume")++ resume_db = resume / ".repowise" / "wiki.db"+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{resume_db}")+ asyncio.run(_leave_index_checkpoint(resume, monkeypatch))+ asyncio.run(_resume_after_index(resume))++ workspace_db = workspace / ".repowise" / "wiki.db"+ monkeypatch.setenv("REPOWISE_DB_URL", f"sqlite+aiosqlite:///{workspace_db}")+ asyncio.run(index_repo_full(workspace))++ snapshots = {+ "clean": _symbol_snapshot(clean),+ "incremental": _symbol_snapshot(incremental),+ "resume": _symbol_snapshot(resume),+ "workspace": _symbol_snapshot(workspace),+ }+ assert snapshots == {name: [("probe.py::branch", 2)] for name in snapshots}diff --git a/tests/unit/pipeline/test_resume.py b/tests/unit/pipeline/test_resume.pyindex 20c7d1439..2a408a4da 100644--- a/tests/unit/pipeline/test_resume.py+++ b/tests/unit/pipeline/test_resume.py@@ -297,3 +297,37 @@ async def test_a_successful_checkpoint_says_nothing(sf, monkeypatch):)assert progress.messages == []+++async def test_failed_symbol_analysis_reconciliation_keeps_analysis_retryable(sf, monkeypatch):+ """ANALYSIS cannot complete while post-health symbol state is stale."""+ repo_id = await _make_repo(sf)++ async def _boom(*_a: object, **_k: object) -> None:+ raise RuntimeError("symbol write failed")++ async def _ok(*_a: object, **_k: object) -> None:+ return None++ monkeypatch.setattr("repowise.core.pipeline.resume.controller.persist_symbol_analysis", _boom)+ monkeypatch.setattr("repowise.core.pipeline.resume.controller.persist_analysis", _ok)++ progress = _RecordingProgress()+ ctrl = ResumeController(sf, repo_id, resume=False)+ await ctrl.checkpoint_analysis(+ parsed_files=[],+ dead_code_report=None,+ health_report=None,+ decision_report=None,+ git_metadata_list=[],+ progress=progress,+ )++ assert ResumePhase.ANALYSIS not in await ResumeLedger(sf, repo_id).completed_phases()+ assert progress.messages == [+ (+ "warning",+ "Analysis checkpoint not saved (symbol write failed); "+ "a resumed run will have to recompute dead code, health and decisions.",+ )+ ]