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(pipeline): preserve coverage across an incremental health re-score (#1806)
Sloeb0989d9779c7
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.pyindex 5bd9395ef..4b8de7017 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py@@ -200,7 +200,10 @@ def _run_partial_analysis(Returns ``(partial_health_report, dead_code_report)`` — either may be``None`` if its analysis failed (both are best-effort)."""- from repowise.core.pipeline.incremental import run_partial_analysis+ from repowise.core.pipeline.incremental import (+ load_stored_coverage_map,+ run_partial_analysis,+ )return run_partial_analysis(repo_path,@@ -212,5 +215,6 @@ def _run_partial_analysis(stored_git_meta=stored_git_meta,stored_performance_callers=stored_performance_callers,repo_function_mod_p80=repo_function_mod_p80,+ coverage_map=run_async(load_stored_coverage_map(repo_path, log=console.print)),log=console.print,)diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 0e44727ee..afc1b1bbc 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -493,6 +493,70 @@ async def load_stored_function_mod_p80(repo_path: Any, *, log: LogFn | None = Noreturn None+async def load_stored_coverage_map(+ repo_path: Any, *, log: LogFn | None = None+) -> dict[str, dict]:+ """Load the persisted coverage map for health scoring on an incremental run.++ The incremental health pass re-scores changed files only, but if it builds+ its ``HealthAnalyzer`` without a ``coverage_map`` every re-analyzed file is+ scored as if no coverage had ever been ingested — and the partial-health+ writer then overwrites the stored ``line_coverage_pct`` with ``None`` for+ exactly the files that just changed, eroding coverage one file per update+ (issue #1739).++ Returns ``{path: coverage-dict}`` by reloading the persisted ``CoverageFile``+ rows, mirroring ``_coverage_for_rescore`` in the CLI update path. Empty dict+ when no coverage is stored, the store is unreadable, or the repository row+ is missing — the analyzer then scores without coverage, matching the+ established safe default.+ """+ log = log or _noop_log+ import json++ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():+ return {}+ try:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_repository_by_path,+ load_coverage_for_repo,+ )+ from repowise.core.persistence.database import resolve_db_url++ engine = create_engine(resolve_db_url(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return {}+ rows = await load_coverage_for_repo(session, repo.id)+ finally:+ await engine.dispose()+ coverage_map: dict[str, dict] = {}+ for row in rows:+ try:+ covered = (+ json.loads(row.covered_lines_json) if row.covered_lines_json else []+ )+ except (ValueError, TypeError):+ covered = []+ coverage_map[row.file_path] = {+ "line_coverage_pct": row.line_coverage_pct,+ "branch_coverage_pct": row.branch_coverage_pct,+ "covered_lines": covered,+ "total_coverable_lines": row.total_coverable_lines or 0,+ }+ return coverage_map+ except Exception as exc:+ log(f"[yellow]Stored coverage unavailable: {exc}[/yellow]")+ return {}++def run_partial_analysis(repo_path: Any,graph_builder: Any,@@ -504,6 +568,7 @@ def run_partial_analysis(stored_git_meta: dict[str, dict] | None = None,stored_performance_callers: set[str] | None = None,repo_function_mod_p80: int | None = None,+ coverage_map: dict[str, dict] | None = None,log: LogFn | None = None,) -> tuple[Any, Any]:"""Run partial code-health + repo-wide dead-code analysis.@@ -575,6 +640,7 @@ def run_partial_analysis(parsed_files=parsed_files,duplication_cache_dir=Path(repo_path) / ".repowise",repo_root=repo_path,+ coverage_map=coverage_map,)if _health_scope:_hcfg = HealthConfig.load(repo_path)diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 139957e6f..6c07afb1f 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -430,6 +430,7 @@ async def _incremental_repo_update(# against an empty dict — which reads as "no commits in 90 days" and puts# the whole repo on the 0.7 / safe-to-delete rung of the confidence ladder.from ..pipeline.incremental import (+ load_stored_coverage_map,load_stored_function_mod_p80,load_stored_git_meta,load_stored_performance_callers,@@ -447,6 +448,10 @@ async def _incremental_repo_update(stored_performance_callers = await load_stored_performance_callers(repo_path, performance_changed_paths, log=_log.info)+ # Preserve coverage across an incremental health re-score: without a+ # coverage_map the changed files are re-scored as if no coverage existed+ # and their stored line_coverage_pct is nulled (issue #1739).+ stored_coverage_map = await load_stored_coverage_map(repo_path, log=_log.info)partial_health_report, dead_code_report = run_partial_analysis(repo_path,@@ -458,6 +463,7 @@ async def _incremental_repo_update(stored_git_meta=stored_git_meta,stored_performance_callers=stored_performance_callers,repo_function_mod_p80=stored_function_mod_p80,+ coverage_map=stored_coverage_map,log=_log.info,)diff --git a/tests/unit/pipeline/test_load_stored_coverage_map.py b/tests/unit/pipeline/test_load_stored_coverage_map.pynew file mode 100644index 000000000..70b243201--- /dev/null+++ b/tests/unit/pipeline/test_load_stored_coverage_map.py@@ -0,0 +1,80 @@+"""``load_stored_coverage_map`` reloads persisted coverage rows so the+incremental health pass re-scores changed files against the coverage they+already had, instead of nulling ``line_coverage_pct`` for exactly the files+under active development (issue #1739).+"""++from __future__ import annotations++from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+)+from repowise.core.persistence.crud import (+ get_repository_by_path,+ save_coverage_files,+)+from repowise.core.persistence.database import init_db, resolve_db_url+from repowise.core.pipeline.incremental import load_stored_coverage_map+++async def _seed(repo_path, files: list[dict]) -> None:+ engine = create_engine(resolve_db_url(repo_path))+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ from repowise.core.persistence.crud import upsert_repository++ repo = await upsert_repository(+ session,+ name="coverage-loader-test",+ local_path=str(repo_path),+ url="https://example.test/coverage",+ )+ await session.commit()+ await save_coverage_files(+ session, repo.id, files, source_format="lcov"+ )+ await session.commit()+ finally:+ await engine.dispose()+++async def test_loader_reloads_persisted_coverage(tmp_path):+ """Rows saved by coverage add must come back as a health-coverage map."""+ repo_path = tmp_path / "repo"+ repo_path.mkdir()+ await _seed(+ repo_path,+ [+ {+ "file_path": "src/a.py",+ "line_coverage_pct": 0.8,+ "branch_coverage_pct": 0.5,+ "covered_lines": [1, 2, 3, 4],+ "total_coverable_lines": 5,+ },+ {+ "file_path": "src/b.py",+ "line_coverage_pct": 0.0,+ "branch_coverage_pct": None,+ "covered_lines": [],+ "total_coverable_lines": 10,+ },+ ],+ )++ cm = await load_stored_coverage_map(repo_path)+ assert cm["src/a.py"]["line_coverage_pct"] == 0.8+ assert cm["src/a.py"]["covered_lines"] == [1, 2, 3, 4]+ assert cm["src/b.py"]["line_coverage_pct"] == 0.0+ assert cm["src/b.py"]["covered_lines"] == []+++async def test_loader_no_store_returns_empty(tmp_path):+ """Reading must never conjure a store, and an absent repo is no coverage."""+ assert await load_stored_coverage_map(tmp_path) == {}+ assert not (tmp_path / ".repowise").exists()