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
perf(health): stop two dashboard routes reading tables they barely use (#1356)
Raghav Chamadiyaeb9a9b4667d0
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsindex 2be784473..29f915724 100644--- a/packages/api-client/src/code-health.ts+++ b/packages/api-client/src/code-health.ts@@ -104,7 +104,7 @@ export async function updateFindingStatus(export async function getHealthCoverage(repoId: string,- opts?: { file_path?: string; limit?: number },+ opts?: { file_path?: string; limit?: number; module_limit?: number },): Promise<HealthCoverageResponse> {return apiGet<HealthCoverageResponse>(`/api/repos/${repoId}/health/coverage`,diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 950f05fd1..bb668d644 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -31,11 +31,13 @@ from .dead_code import (from .health import (HEALTH_SNAPSHOT_RETENTION,HealthSnapshotHeadline,+ HealthSnapshotScalars,get_average_health,get_deduction_by_path,get_file_language_map,get_health_findings,get_health_metrics,+ get_health_snapshot_file_counts,get_health_snapshot_headline,get_health_summary,get_perf_coverage,@@ -59,6 +61,7 @@ from .refactoring import (__all__ = ["HEALTH_SNAPSHOT_RETENTION","HealthSnapshotHeadline",+ "HealthSnapshotScalars","covered_source_files","files_covered_by","get_average_health",@@ -69,6 +72,7 @@ __all__ = ["get_file_language_map","get_health_findings","get_health_metrics",+ "get_health_snapshot_file_counts","get_health_snapshot_headline","get_health_summary","get_perf_coverage",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.pyindex 16d1d5b7b..01878ddcf 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py@@ -3,7 +3,7 @@from __future__ import annotationsimport json-from typing import Any+from typing import Any, Literal, overloadfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -74,25 +74,86 @@ async def save_coverage_files(await session.flush()+#: Every column of ``CoverageFile`` except ``covered_lines_json``. That blob is+#: the per-file set of covered line numbers, and it dominates the table: 467 KB+#: of the 549 KB stored for this repo's 1,401 rows. Only the single-file detail+#: view reads it, so every repo-wide caller was hydrating it to throw it away.+_COVERAGE_SCALAR_COLUMNS = (+ CoverageFile.file_path,+ CoverageFile.source_format,+ CoverageFile.line_coverage_pct,+ CoverageFile.branch_coverage_pct,+ CoverageFile.total_coverable_lines,+ CoverageFile.ingested_at,+ CoverageFile.ingested_commit_sha,+)+++@overload+async def load_coverage_for_repo(+ session: AsyncSession,+ repository_id: str,+ *,+ file_paths: list[str] | None = ...,+ include_covered_lines: Literal[True] = ...,+) -> list[CoverageFile]: ...+++@overload+async def load_coverage_for_repo(+ session: AsyncSession,+ repository_id: str,+ *,+ file_paths: list[str] | None = ...,+ include_covered_lines: Literal[False],+) -> list[Any]: ...++async def load_coverage_for_repo(session: AsyncSession,repository_id: str,*,file_paths: list[str] | None = None,-) -> list[CoverageFile]:- q = select(CoverageFile).where(CoverageFile.repository_id == repository_id)+ include_covered_lines: bool = True,+) -> list[Any]:+ """Coverage rows for a repo, optionally scoped to *file_paths*.++ ``include_covered_lines=False`` returns ``Row`` objects carrying every+ column except ``covered_lines_json``. They are attribute-accessed exactly+ like the ORM entities, so a caller that reads named fields needs no change+ — but a caller that touches ``covered_lines_json`` must ask for it.+ """+ q = (+ select(CoverageFile)+ if include_covered_lines+ else select(*_COVERAGE_SCALAR_COLUMNS)+ ).where(CoverageFile.repository_id == repository_id)if file_paths is not None:q = q.where(CoverageFile.file_path.in_(file_paths))result = await session.execute(q)- return list(result.scalars().all())+ if include_covered_lines:+ return list(result.scalars().all())+ return list(result.all())async def get_coverage_summary(session: AsyncSession,repository_id: str,+ *,+ rows: list[Any] | None = None,) -> dict[str, Any]:- """Repo-level coverage aggregate. Returns an empty shape when no rows."""- rows = await load_coverage_for_repo(session, repository_id)+ """Repo-level coverage aggregate. Returns an empty shape when no rows.++ *rows* lets a caller that has already loaded the coverage table hand it+ over instead of paying for a second full read. It must be exactly what this+ function would have read itself — ``load_coverage_for_repo(repository_id)``,+ i.e. **every** row for the repo. Handing over a subset (a ``file_paths=``+ read, say) would silently report that subset's coverage as the repo's.+ """+ if rows is None:+ rows = await load_coverage_for_repo(+ session, repository_id, include_covered_lines=False+ )if not rows:return {"file_count": 0,diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex 6349f30c0..95d4b6c21 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -695,39 +695,121 @@ async def list_health_snapshots(return rows+class HealthSnapshotScalars(NamedTuple):+ """One snapshot's numeric columns, with no per-file map behind them."""++ taken_at: datetime | None+ average_health: float+ hotspot_health: float++class HealthSnapshotHeadline(NamedTuple):- """The three snapshot scalars a dashboard header actually reads."""+ """The snapshot figures a dashboard header actually reads.++ ``recent`` is empty unless the caller asked for it, and is ordered+ **oldest-first** to match ``list_health_snapshots`` — a trend line reads+ left to right, and the newest row is ``recent[-1]``.+ """hotspot_health: float | Nonetaken_at: datetime | Nonesnapshot_count: int+ recent: tuple[HealthSnapshotScalars, ...] = ()async def get_health_snapshot_headline(- session: AsyncSession, repository_id: str+ session: AsyncSession,+ repository_id: str,+ *,+ recent: int = 0,) -> HealthSnapshotHeadline:"""Latest snapshot's ``hotspot_health`` / ``taken_at``, plus how many exist.``list_health_snapshots`` hydrates whole entities, and every row carries a``per_file_scores_json`` blob sized by the repo's file count — on this- codebase that is ~186 KB each, 2.2 MB across the retained history. A caller- that only needs the header scalars was reading all of it to use two floats.-- Two columns, no JSON. Callers that genuinely need the per-file maps (the- trend routes, the file drawer's sparkline) should keep using- ``list_health_snapshots``.+ codebase that is ~186 KB each, 2.8 MB across the retained history and ~9 MB+ at ``HEALTH_SNAPSHOT_RETENTION``. A caller that only needs scalars was+ reading all of it to use a handful of floats.++ Pass ``recent=N`` for the newest N rows' scalars as well — a sparkline and a+ delta-vs-previous both want a bounded window of numbers, not the history.+ ``snapshot_count`` is always the **true** total, independent of ``recent``,+ so a capped window can never be mistaken for the whole history.++ No JSON column is touched. Callers that genuinely need the per-file maps+ (the trend routes, the file drawer's sparkline) should keep using+ ``list_health_snapshots``; a caller that needs only their *sizes* wants+ ``get_health_snapshot_file_counts``."""rows = (await session.execute(- select(HealthSnapshot.hotspot_health, HealthSnapshot.taken_at)+ select(+ HealthSnapshot.hotspot_health,+ HealthSnapshot.taken_at,+ HealthSnapshot.average_health,+ ).where(HealthSnapshot.repository_id == repository_id).order_by(HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc()))).all()if not rows:return HealthSnapshotHeadline(None, None, 0)- hotspot_health, taken_at = rows[-1]- return HealthSnapshotHeadline(float(hotspot_health), taken_at, len(rows))+ hotspot_health, taken_at, _ = rows[-1]+ window = rows[-recent:] if recent > 0 else []+ return HealthSnapshotHeadline(+ float(hotspot_health),+ taken_at,+ len(rows),+ tuple(+ HealthSnapshotScalars(r_taken_at, float(r_avg), float(r_hotspot))+ for r_hotspot, r_taken_at, r_avg in window+ ),+ )+++async def get_health_snapshot_file_counts(+ session: AsyncSession,+ repository_id: str,+ *,+ limit: int = 2,+) -> list[int]:+ """How many files the newest *limit* snapshots scored, oldest-first.++ The only thing the overview's ``file_count`` delta wants out of+ ``per_file_scores_json`` is its key count, and it compares two rows. Loading+ the whole retained history to measure two of its maps read 2.8 MB to use+ 375 KB of it.++ Ordering matches ``list_health_snapshots`` exactly, so "the newest two"+ cannot mean different rows here than there.++ Anything that is not a ``{path: score}`` object counts 0 — unparseable, but+ also a bare JSON array or string, which ``len()`` would happily measure into+ a file count meaning nothing. The caller reads 0 as "unknown" and omits the+ delta rather than publishing a number it cannot justify. This is deliberately+ stricter than the ``len(json.loads(...))`` it replaced;+ ``save_health_snapshot`` only ever writes an object, so it can only bite on+ rows that did not come from it.+ """+ if limit <= 0:+ return []+ rows = (+ await session.execute(+ select(HealthSnapshot.per_file_scores_json)+ .where(HealthSnapshot.repository_id == repository_id)+ .order_by(HealthSnapshot.taken_at.desc(), HealthSnapshot.id.desc())+ .limit(limit)+ )+ ).all()+ counts: list[int] = []+ for (blob,) in reversed(rows):+ try:+ parsed = json.loads(blob or "{}")+ except (TypeError, ValueError):+ counts.append(0)+ continue+ counts.append(len(parsed) if isinstance(parsed, dict) else 0)+ return countsasync def upsert_health_findings(diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.pyindex 6944a1d31..97d0cf98b 100644--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py@@ -37,6 +37,7 @@ async def health_coverage(repo_id: str,file_path: str | None = Query(None),limit: int = Query(500, ge=1, le=5000),+ module_limit: int = Query(1000, ge=0, le=5000),session: AsyncSession = Depends(get_db_session),) -> dict:"""Coverage summary + per-file rows.@@ -44,27 +45,50 @@ async def health_coverage(Pass ``file_path`` to fetch a single file's full covered-line set.Without ``file_path`` we return the summary + a list of per-filerows trimmed by ``limit`` (covered_lines arrays stripped).++ ``limit`` caps ``files``; ``module_limit`` caps ``modules``. Separate+ parameters because they bound unrelated things — one is a page of files, the+ other a rollup as long as the repo's covered-directory count — and one+ ``limit`` governing both meant a caller asking for a single file row was+ told the repo had a single module.++ ``modules_total`` is always the full count, so a trimmed rollup can never be+ read as the whole repo. ``module_limit=0`` returns none of them, for callers+ that want the summary and nothing else."""repo = await crud.get_repository(session, repo_id)if repo is None:raise HTTPException(status_code=404, detail="Repository not found")- summary = await crud.get_coverage_summary(session, repo_id)+ # One narrow read of the whole table, shared by all three blocks below.+ # ``summary`` and ``modules`` are both repo-wide aggregates, so this cannot+ # be scoped by ``file_path`` or trimmed by ``limit`` — and none of the three+ # reads ``covered_lines_json``, which is most of the table's bytes.+ all_rows = await crud.load_coverage_for_repo(+ session, repo_id, include_covered_lines=False+ )+ summary = await crud.get_coverage_summary(session, repo_id, rows=all_rows)if summary.get("ingested_at") is not None:summary = {**summary, "ingested_at": summary["ingested_at"].isoformat()}- rows = await crud.load_coverage_for_repo(- session, repo_id, file_paths=[file_path] if file_path else None- )- metrics = await crud.get_health_metrics(session, repo_id)- metric_by_path = {m.file_path: m for m in metrics}if file_path:- files = [_coverage_row_to_dict(r, include_covered_lines=True) for r in rows]+ # The one caller that wants the covered-line set, for one file.+ detail = await crud.load_coverage_for_repo(+ session, repo_id, file_paths=[file_path], include_covered_lines=True+ )+ files = [_coverage_row_to_dict(r, include_covered_lines=True) for r in detail]else:- rows_sorted = sorted(rows, key=lambda r: r.line_coverage_pct)+ rows_sorted = sorted(all_rows, key=lambda r: r.line_coverage_pct)files = [_coverage_row_to_dict(r) for r in rows_sorted[:limit]]# Attach per-file health score so the UI can render a coverage- # x score matrix without a second request.+ # x score matrix without a second request. Scoped to the rows we are+ # actually returning: a repo-wide read hydrates every metric row and+ # pays for the grouped deduction aggregate behind its worst-first+ # ordering, neither of which this join uses.+ metrics = await crud.get_health_metrics(+ session, repo_id, file_paths=[f["file_path"] for f in files]+ )+ metric_by_path = {m.file_path: m for m in metrics}for f in files:m = metric_by_path.get(f["file_path"])if m is not None:@@ -72,8 +96,10 @@ async def health_coverage(f["nloc"] = m.nloc# Aggregate by directory for module-level bars (cheap; one pass).+ # Always over the repo-wide read, never over ``files``: this is what the+ # repo's coverage looks like by directory, not what this page of it does.modules: dict[str, dict[str, Any]] = {}- for r in rows:+ for r in all_rows:mod = r.file_path.rsplit("/", 1)[0] if "/" in r.file_path else "(root)"bucket = modules.setdefault(mod, {"covered": 0, "total": 0, "files": 0})bucket["files"] += 1@@ -96,5 +122,6 @@ async def health_coverage(return {"summary": summary,"files": files,- "modules": module_rows[:limit],+ "modules": module_rows[:module_limit] if module_limit else [],+ "modules_total": len(module_rows),}diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.pyindex 7c78b5f0e..86ce0535b 100644--- a/packages/server/src/repowise/server/routers/overview.py+++ b/packages/server/src/repowise/server/routers/overview.py@@ -38,6 +38,10 @@ router = APIRouter(dependencies=[Depends(verify_api_key)],)+#: How many snapshots the health card's trend line plots. Also the width of the+#: scalar window this route reads, so the read and the chart cannot drift.+HEALTH_HISTORY_POINTS = 12+def _index_storage_bytes(repowise_dir: Path) -> int:"""Total on-disk size of a repo's ``.repowise/`` directory."""@@ -373,7 +377,17 @@ async def overview_summary(health_summary = await crud.get_health_summary(session, repo_id, metrics=health_metrics, findings=findings)- snapshots = await crud.list_health_snapshots(session, repo_id)+ # Three scopes, three reads. This payload wants the *count* of retained+ # snapshots, the newest ``HEALTH_HISTORY_POINTS`` rows' scalars for the+ # sparkline, and the newest two rows' per-file maps for the file-count+ # delta — and nothing else. Loading the history as entities to get that+ # pulled every row's ``per_file_scores_json``: 2.8 MB on this index, ~9 MB+ # at the retention cap, for 375 KB of actual use. Capping the read at two+ # rows instead would be wrong in two visible ways — it would flatten the+ # sparkline and report a snapshot count of 2.+ snapshot = await crud.get_health_snapshot_headline(+ session, repo_id, recent=HEALTH_HISTORY_POINTS+ )hotspot_health: float | None = Nonelast_indexed_at: str | None = Nonedeltas: dict[str, float | None] = {@@ -381,21 +395,16 @@ async def overview_summary("hotspot_health": None,"file_count": None,}- if snapshots:- latest = snapshots[-1]- hotspot_health = round(float(latest.hotspot_health), 2)- last_indexed_at = latest.taken_at.isoformat() if latest.taken_at else None- if len(snapshots) >= 2:- prev, cur = snapshots[-2], snapshots[-1]- deltas["average_health"] = round(float(cur.average_health) - float(prev.average_health), 2)- deltas["hotspot_health"] = round(float(cur.hotspot_health) - float(prev.hotspot_health), 2)- try:- prev_files = len(json.loads(prev.per_file_scores_json or "{}"))- cur_files = len(json.loads(cur.per_file_scores_json or "{}"))- if prev_files and cur_files:- deltas["file_count"] = cur_files - prev_files- except Exception:- pass+ if snapshot.snapshot_count:+ hotspot_health = round(float(snapshot.hotspot_health), 2)+ last_indexed_at = snapshot.taken_at.isoformat() if snapshot.taken_at else None+ if len(snapshot.recent) >= 2:+ prev, cur = snapshot.recent[-2], snapshot.recent[-1]+ deltas["average_health"] = round(cur.average_health - prev.average_health, 2)+ deltas["hotspot_health"] = round(cur.hotspot_health - prev.hotspot_health, 2)+ file_counts = await crud.get_health_snapshot_file_counts(session, repo_id, limit=2)+ if len(file_counts) == 2 and all(file_counts):+ deltas["file_count"] = file_counts[1] - file_counts[0]severity_breakdown = {"critical": 0, "high": 0, "medium": 0, "low": 0}for f in findings:@@ -584,14 +593,15 @@ async def overview_summary("severity_breakdown": severity_breakdown,"defect_accuracy": defect_accuracy,"last_indexed_at": last_indexed_at,- "snapshot_count": len(snapshots),+ # The true total, not the length of the windowed read above.+ "snapshot_count": snapshot.snapshot_count,"history": [{"taken_at": s.taken_at.isoformat() if s.taken_at else None,- "average_health": round(float(s.average_health), 2),- "hotspot_health": round(float(s.hotspot_health), 2),+ "average_health": round(s.average_health, 2),+ "hotspot_health": round(s.hotspot_health, 2),}- for s in snapshots[-12:]+ for s in snapshot.recent],},"languages": languages,diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex cfc22cd82..cfd7fef90 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -506,7 +506,14 @@ export interface CoverageSummary {export interface HealthCoverageResponse {summary: CoverageSummary;files: CoverageFileRow[];+ /** Capped by the request's `module_limit`, which is independent of `limit`. */modules: ModuleCoverageRow[];+ /**+ * How many modules exist, whatever `modules` carries — so a trimmed or+ * declined rollup is never read as the repo having that few. Optional: the+ * hosted backend does not send it yet.+ */+ modules_total?: number;}/* ------------------------------------------------------------------ *diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.tsindex 10866c468..e743d0900 100644--- a/packages/ui/src/health/code-health-adapter.ts+++ b/packages/ui/src/health/code-health-adapter.ts@@ -57,6 +57,7 @@ export interface CodeHealthAdapter {getCoverage(opts?: {file_path?: string;limit?: number;+ module_limit?: number;}): Promise<HealthCoverageResponse>;/** Build an href to a file detail page. */diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex e007ea026..e7043d818 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -122,6 +122,9 @@ function CoverageBody({onGeneratePrompt: (row: CoverageFilePromptInput) => void;}) {const { summary, files, modules } = data;+ // The true count, not the length of what came back. They differ only if the+ // rollup was capped, but the lede claims to describe the repo.+ const moduleCount = data.modules_total ?? modules.length;const [search, setSearch] = useState("");const [sortField, setSortField] = useState<string>("line_coverage_pct");const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");@@ -359,7 +362,7 @@ function CoverageBody({return (<div className="flex flex-col gap-6 sm:gap-8">- <CoverageLede summary={summary} files={files} moduleCount={modules.length} />+ <CoverageLede summary={summary} files={files} moduleCount={moduleCount} /><OverviewSectiontitle="Health against coverage"diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 3006c7a94..4bcc0ac7b 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -196,11 +196,14 @@ export default function CodeHealthPage() {() => getDeadCodeSummary(repoId),{ revalidateOnFocus: false },);- // Coverage's own tab pulls 5,000 file rows; this asks for the summary alone,- // on its own key, so a badge never drags the heavy payload onto page load.+ // Coverage's own tab pulls 5,000 file rows and the module rollup; this badge+ // reads one number off `summary`, so it declines both. `limit` and+ // `module_limit` cap different blocks — one file row and no modules is 0.7 KB+ // against the tab's 442 KB, and `modules_total` still reports the real count+ // to anyone who asks for it.const { data: coverage } = useSWR<HealthCoverageResponse>(`code-health-coverage-summary:${repoId}`,- () => getHealthCoverage(repoId, { limit: 1 }),+ () => getHealthCoverage(repoId, { limit: 1, module_limit: 0 }),{ revalidateOnFocus: false },);const coveragePct = coverage?.summary.line_coverage_pct;diff --git a/tests/unit/persistence/test_coverage_narrow_read.py b/tests/unit/persistence/test_coverage_narrow_read.pynew file mode 100644index 000000000..ca6d323e5--- /dev/null+++ b/tests/unit/persistence/test_coverage_narrow_read.py@@ -0,0 +1,117 @@+"""``load_coverage_for_repo(include_covered_lines=False)`` and the summary's+``rows=`` hand-off.++``covered_lines_json`` is most of what the coverage table stores — 467 KB of+549 KB on this codebase — and only the single-file detail view reads it. The+narrow read exists so the repo-wide callers stop hydrating it, and the rows it+returns have to stay attribute-compatible with the entities they replace,+because the serializers and the summary read them by name either way.+"""++from __future__ import annotations++import pytest++from repowise.core.persistence.crud import (+ get_coverage_summary,+ load_coverage_for_repo,+ save_coverage_files,+ upsert_repository,+)++_FILES = [+ {"file_path": "src/a.py", "line_coverage_pct": 20.0, "covered_lines": [1, 2],+ "total_coverable_lines": 10, "branch_coverage_pct": 10.0},+ {"file_path": "src/b.py", "line_coverage_pct": 80.0, "covered_lines": [1, 2, 3, 4],+ "total_coverable_lines": 5, "branch_coverage_pct": None},+]++# Every field the route serializers and the summary read off a row.+_READ_BY_CALLERS = (+ "file_path",+ "source_format",+ "line_coverage_pct",+ "branch_coverage_pct",+ "total_coverable_lines",+ "ingested_at",+ "ingested_commit_sha",+)+++async def repo(async_session, tmp_path):+ r = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ await save_coverage_files(async_session, r.id, _FILES, source_format="lcov")+ return r+++async def test_narrow_read_drops_the_blob_and_keeps_everything_else(+ async_session, repo+) -> None:+ narrow = await load_coverage_for_repo(+ async_session, repo.id, include_covered_lines=False+ )++ assert len(narrow) == 2+ for row in narrow:+ for field in _READ_BY_CALLERS:+ assert hasattr(row, field), field+ assert not hasattr(row, "covered_lines_json")+++async def test_wide_read_still_carries_the_blob(async_session, repo) -> None:+ """The CLI's coverage-map builders depend on this being the default."""+ wide = await load_coverage_for_repo(async_session, repo.id)++ assert {r.file_path: r.covered_lines_json for r in wide} == {+ "src/a.py": "[1, 2]",+ "src/b.py": "[1, 2, 3, 4]",+ }+++async def test_narrow_and_wide_agree_on_every_other_column(+ async_session, repo+) -> None:+ narrow = {r.file_path: r for r in+ await load_coverage_for_repo(async_session, repo.id,+ include_covered_lines=False)}+ wide = {r.file_path: r for r in await load_coverage_for_repo(async_session, repo.id)}++ assert narrow.keys() == wide.keys()+ for path, n in narrow.items():+ for field in _READ_BY_CALLERS:+ assert getattr(n, field) == getattr(wide[path], field), f"{path}.{field}"+++async def test_narrow_read_honors_file_paths(async_session, repo) -> None:+ rows = await load_coverage_for_repo(+ async_session, repo.id, file_paths=["src/b.py"], include_covered_lines=False+ )++ assert [r.file_path for r in rows] == ["src/b.py"]+++async def test_summary_from_handed_over_rows_matches_its_own_read(+ async_session, repo+) -> None:+ """The ``rows=`` hand-off must not change a single figure."""+ rows = await load_coverage_for_repo(+ async_session, repo.id, include_covered_lines=False+ )++ assert await get_coverage_summary(async_session, repo.id, rows=rows) == (+ await get_coverage_summary(async_session, repo.id)+ )+++async def test_summary_weights_branch_coverage_over_rows_that_have_it(+ async_session, repo+) -> None:+ """Guards the narrow row's ``None`` branch column, which the weighting skips."""+ summary = await get_coverage_summary(async_session, repo.id)++ assert summary["file_count"] == 2+ # 2 covered of 10, plus 4 of 5.+ assert summary["covered_lines"] == 6+ assert summary["total_lines"] == 15+ assert summary["branch_coverage_pct"] == 10.0diff --git a/tests/unit/persistence/test_health_overview_reads.py b/tests/unit/persistence/test_health_overview_reads.pyindex 2d7540095..5ae75e160 100644--- a/tests/unit/persistence/test_health_overview_reads.py+++ b/tests/unit/persistence/test_health_overview_reads.py@@ -11,7 +11,10 @@ from __future__ import annotationsfrom datetime import UTC, datetime, timedelta+from sqlalchemy import select+from repowise.core.persistence.crud import (+ get_health_snapshot_file_counts,get_health_snapshot_headline,get_health_summary,save_health_findings,@@ -19,6 +22,7 @@ from repowise.core.persistence.crud import (save_health_snapshot,upsert_repository,)+from repowise.core.persistence.models import HealthSnapshotdef _metric(path: str, score: float, nloc: int = 10) -> dict:@@ -135,4 +139,172 @@ async def test_snapshot_headline_on_a_repo_with_no_history(async_session, tmp_pa"""No snapshots is not an error: the header renders "not measured"."""repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))- assert await get_health_snapshot_headline(async_session, repo.id) == (None, None, 0)+ headline = await get_health_snapshot_headline(async_session, repo.id, recent=12)++ assert headline.hotspot_health is None+ assert headline.taken_at is None+ assert headline.snapshot_count == 0+ assert headline.recent == ()+++async def _history(session, repo_id: str, n: int, *, files: int = 1) -> datetime:+ """*n* snapshots one day apart, inserted newest-first."""+ base = datetime(2026, 1, 1, tzinfo=UTC)+ for offset in reversed(range(n)):+ await save_health_snapshot(+ session,+ repo_id,+ hotspot_health=float(offset),+ average_health=float(offset) / 2,+ worst_performer_path="a.py",+ worst_performer_score=1.0,+ per_file_scores={f"f{i}.py": 1.0 for i in range(files + offset)},+ taken_at=base + timedelta(days=offset),+ )+ return base+++async def test_snapshot_headline_window_is_bounded_but_the_count_is_not(+ async_session, tmp_path+) -> None:+ """The read is capped at ``recent``; ``snapshot_count`` still tells the truth.++ This is the whole point of the split. Capping the *read* at the window the+ sparkline plots would have made the count read 12 on a 15-snapshot repo,+ which is the misreport that made the obvious ``limit=2`` fix wrong.+ """+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ base = await _history(async_session, repo.id, 15)++ headline = await get_health_snapshot_headline(async_session, repo.id, recent=12)++ assert headline.snapshot_count == 15+ assert len(headline.recent) == 12+ # Oldest-first, ending on the newest row — the order a trend line plots.+ assert headline.recent[-1].taken_at.replace(tzinfo=UTC) == base + timedelta(days=14)+ assert headline.recent[0].taken_at.replace(tzinfo=UTC) == base + timedelta(days=3)+ assert headline.recent[-1].hotspot_health == 14.0+ assert headline.recent[-1].average_health == 7.0+ # And the scalars agree with what the unwindowed headline reports.+ assert headline.hotspot_health == 14.0+++async def test_snapshot_headline_window_never_exceeds_the_history(+ async_session, tmp_path+) -> None:+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ await _history(async_session, repo.id, 3)++ headline = await get_health_snapshot_headline(async_session, repo.id, recent=12)++ assert headline.snapshot_count == 3+ assert len(headline.recent) == 3+++async def test_snapshot_headline_asks_for_no_window_by_default(+ async_session, tmp_path+) -> None:+ """The header-only caller pays for no rows it will not read."""+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ await _history(async_session, repo.id, 4)++ headline = await get_health_snapshot_headline(async_session, repo.id)++ assert headline.recent == ()+ assert headline.snapshot_count == 4+++async def test_snapshot_file_counts_reads_the_newest_rows_oldest_first(+ async_session, tmp_path+) -> None:+ """``{path: score}`` key counts for the delta, without the other 13 maps."""+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ # Row at day *offset* carries ``files + offset`` entries, so 15 snapshots+ # end on 15 files and the one before it on 14.+ await _history(async_session, repo.id, 15)++ assert await get_health_snapshot_file_counts(async_session, repo.id, limit=2) == [14, 15]+ assert await get_health_snapshot_file_counts(async_session, repo.id, limit=3) == [+ 13,+ 14,+ 15,+ ]+++async def test_snapshot_file_counts_matches_the_headline_ordering(+ async_session, tmp_path+) -> None:+ """Both reads must agree on which rows are "the newest two".++ They order in opposite directions — the headline ascends and takes the+ tail, this one descends and takes a ``LIMIT`` — so a tie broken differently+ would pair a delta with the wrong pair of scalars.+ """+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ stamp = datetime(2026, 1, 1, tzinfo=UTC)+ for files in (1, 2, 3, 4):+ await save_health_snapshot(+ async_session,+ repo.id,+ hotspot_health=float(files),+ average_health=float(files),+ worst_performer_path="a.py",+ worst_performer_score=1.0,+ per_file_scores={f"f{i}.py": 1.0 for i in range(files)},+ taken_at=stamp, # every row on the same timestamp: id breaks the tie+ )++ headline = await get_health_snapshot_headline(async_session, repo.id, recent=2)+ counts = await get_health_snapshot_file_counts(async_session, repo.id, limit=2)++ assert headline.snapshot_count == 4+ assert [s.hotspot_health for s in headline.recent] == [float(c) for c in counts]+++async def test_snapshot_file_counts_tolerates_an_unusable_map(+ async_session, tmp_path+) -> None:+ """A malformed blob counts 0, which the caller reads as "no delta"."""+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ await _history(async_session, repo.id, 2)+ rows = (+ await async_session.execute(+ select(HealthSnapshot).order_by(HealthSnapshot.taken_at.asc())+ )+ ).scalars().all()+ rows[0].per_file_scores_json = "{not json"+ rows[1].per_file_scores_json = "[]"+ await async_session.flush()++ assert await get_health_snapshot_file_counts(async_session, repo.id, limit=2) == [0, 0]+++async def test_snapshot_file_counts_refuse_a_map_that_is_not_a_map(+ async_session, tmp_path+) -> None:+ """A JSON array parses fine and ``len()``s fine, and means nothing.++ Deliberately stricter than the ``len(json.loads(...))`` this replaced, which+ would have reported a three-element array as three files and published a+ delta off it.+ """+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))+ await _history(async_session, repo.id, 2)+ rows = (+ await async_session.execute(+ select(HealthSnapshot).order_by(HealthSnapshot.taken_at.asc())+ )+ ).scalars().all()+ rows[0].per_file_scores_json = "[1, 2, 3]"+ rows[1].per_file_scores_json = '"a.py"'+ await async_session.flush()++ assert await get_health_snapshot_file_counts(async_session, repo.id, limit=2) == [0, 0]+++async def test_snapshot_file_counts_on_a_repo_with_no_history(+ async_session, tmp_path+) -> None:+ repo = await upsert_repository(async_session, name="repo", local_path=str(tmp_path))++ assert await get_health_snapshot_file_counts(async_session, repo.id) == []diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex 6dd4f8fc0..a26807bef 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -29,6 +29,7 @@ def _create_test_app():from repowise.server.routers import (c4,+ code_health,costs,dead_code,decisions,@@ -86,6 +87,8 @@ def _create_test_app():app.include_router(git.router)app.include_router(files.router)app.include_router(dead_code.router)+ # Same position as app.py, so route precedence in tests matches production.+ app.include_router(code_health.router)app.include_router(owners.router)app.include_router(modules.router)app.include_router(decisions.router)diff --git a/tests/unit/server/test_health_coverage_route.py b/tests/unit/server/test_health_coverage_route.pynew file mode 100644index 000000000..0ead72a9d--- /dev/null+++ b/tests/unit/server/test_health_coverage_route.py@@ -0,0 +1,198 @@+"""``/health/coverage``: what ``limit`` caps, and what it must not.++``limit`` names the file list. It was also being applied to ``modules`` — a+repo-level aggregate — so the tab badge, which asks for one file row precisely+because it wants a cheap response, was told the repo had one module. The+``?file_path=`` branch had the same defect from the other direction: it+aggregated ``modules`` over the single-row read, so asking about one file+reported that file's directory as the whole repo.++The tests below enumerate ``limit`` x ``file_path`` rather than inspecting one+response: both bugs live in the interaction between the two parameters, and+neither is visible from a single call.+"""++from __future__ import annotations++import pytest++from repowise.core.persistence.crud import save_coverage_files, save_health_metrics++from .conftest import create_test_repo++# Three files in three directories, so a truncated or subset-derived module+# list is distinguishable from a complete one at any limit under three.+_FILES = [+ {"file_path": "src/a.py", "line_coverage_pct": 10.0, "covered_lines": [1],+ "total_coverable_lines": 10, "branch_coverage_pct": 5.0},+ {"file_path": "lib/b.py", "line_coverage_pct": 50.0, "covered_lines": [1, 2],+ "total_coverable_lines": 20, "branch_coverage_pct": 40.0},+ {"file_path": "tools/c.py", "line_coverage_pct": 90.0, "covered_lines": [1, 2, 3],+ "total_coverable_lines": 30, "branch_coverage_pct": 80.0},+]+++def _metric(path: str, score: float, nloc: int) -> dict:+ return {+ "file_path": path,+ "score": score,+ "max_ccn": 1,+ "max_nesting": 1,+ "nloc": nloc,+ "duplication_pct": 0.0,+ "has_test_file": True,+ "line_coverage_pct": 0.0,+ "branch_coverage_pct": 0.0,+ "module": path.split("/")[0],+ }+++async def seeded(client, session, tmp_path):+ repo = await create_test_repo(client, tmp_path)+ await save_coverage_files(session, repo["id"], _FILES, source_format="lcov")+ await save_health_metrics(+ session,+ repo["id"],+ [+ _metric("src/a.py", 3.0, 100),+ _metric("lib/b.py", 6.0, 200),+ _metric("tools/c.py", 9.0, 300),+ ],+ )+ await session.commit()+ return repo+++async def _get(client, repo_id: str, **params) -> dict:+ resp = await client.get(f"/api/repos/{repo_id}/health/coverage", params=params)+ assert resp.status_code == 200, resp.text+ return resp.json()++[email protected]("limit", [1, 2])+async def test_the_file_limit_does_not_cap_the_module_rollup(+ client, seeded, limit+) -> None:+ """``limit`` caps ``files``; ``module_limit`` caps ``modules``.++ Only limits below the module count can show this, hence 1 and 2 against+ three modules — at 3 or 500 the old slice was a no-op and the assertion+ would hold with the bug present.+ """+ body = await _get(client, seeded["id"], limit=limit)++ assert len(body["files"]) == limit+ assert {m["module"] for m in body["modules"]} == {"src", "lib", "tools"}+ assert body["modules_total"] == 3+++async def test_module_limit_caps_modules_without_touching_files(+ client, seeded+) -> None:+ body = await _get(client, seeded["id"], limit=3, module_limit=1)++ assert len(body["files"]) == 3+ assert len(body["modules"]) == 1+ # The truncation is never silent.+ assert body["modules_total"] == 3+++async def test_module_limit_zero_declines_the_rollup_but_still_counts_it(+ client, seeded+) -> None:+ """What the tab badge sends: the summary, and none of the rest."""+ body = await _get(client, seeded["id"], limit=1, module_limit=0)++ assert body["modules"] == []+ assert body["modules_total"] == 3+ assert body["summary"]["file_count"] == 3++[email protected]("limit", [1, 3, 500])+async def test_modules_cover_the_repo_when_one_file_is_requested(+ client, seeded, limit+) -> None:+ """``?file_path=`` scopes ``files``, and nothing else.++ The module aggregation used to run over the single-row read, so this+ returned one module — the requested file's directory — presented as the+ repo's module coverage.+ """+ body = await _get(client, seeded["id"], file_path="src/a.py", limit=limit)++ assert [f["file_path"] for f in body["files"]] == ["src/a.py"]+ assert body["files"][0]["covered_lines"] == [1]+ assert {m["module"] for m in body["modules"]} == {"src", "lib", "tools"}+++async def test_summary_stays_repo_wide_for_a_single_file_request(+ client, seeded+) -> None:+ """Guards the shared read, not a past bug.++ ``summary`` is now computed from rows the route loaded rather than from a+ read of its own, so handing it the ``file_path=`` subset would silently+ report one file's coverage as the repo's.+ """+ everything = await _get(client, seeded["id"], limit=500)+ one_file = await _get(client, seeded["id"], file_path="src/a.py")++ assert one_file["summary"] == everything["summary"]+ assert one_file["summary"]["file_count"] == 3+ # 1 + 10 + 27 covered of 60 coverable.+ assert one_file["summary"]["covered_lines"] == 38+++async def test_module_rollup_counts_every_file_not_just_the_returned_page(+ client, seeded+) -> None:+ body = await _get(client, seeded["id"], limit=1)++ by_name = {m["module"]: m for m in body["modules"]}+ assert by_name["src"]["files"] == 1+ assert by_name["src"]["total_lines"] == 10+ assert by_name["tools"]["line_coverage_pct"] == 90.0+ # Worst coverage first, so the bars read as a ranking.+ assert [m["module"] for m in body["modules"]] == ["src", "lib", "tools"]+++async def test_health_scores_are_attached_to_the_returned_rows(client, seeded) -> None:+ """The metrics read is scoped to the page; the join must still land."""+ body = await _get(client, seeded["id"], limit=2)++ assert [(f["file_path"], f["health_score"], f["nloc"]) for f in body["files"]] == [+ ("src/a.py", 3.0, 100),+ ("lib/b.py", 6.0, 200),+ ]+++async def test_a_file_with_no_health_metric_still_returns_its_coverage(+ client, session, tmp_path+) -> None:+ """A scoped metrics read must not turn a miss into a dropped row."""+ repo = await create_test_repo(client, tmp_path)+ await save_coverage_files(session, repo["id"], _FILES, source_format="lcov")+ await save_health_metrics(session, repo["id"], [_metric("lib/b.py", 6.0, 200)])+ await session.commit()++ body = await _get(client, repo["id"], limit=500)++ assert [f["file_path"] for f in body["files"]] == [+ "src/a.py",+ "lib/b.py",+ "tools/c.py",+ ]+ assert "health_score" not in body["files"][0]+ assert body["files"][1]["health_score"] == 6.0+++async def test_covered_lines_are_withheld_from_the_list_response(+ client, seeded+) -> None:+ """The list response carries no covered-line arrays; the detail one does."""+ listed = await _get(client, seeded["id"], limit=500)+ detail = await _get(client, seeded["id"], file_path="tools/c.py")++ assert all("covered_lines" not in f for f in listed["files"])+ assert detail["files"][0]["covered_lines"] == [1, 2, 3]