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.

fix(coverage): answer the Tests tab for files a partial report never named (#1805)

Nehal kanak kuniyil thottathil189a785d4771
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.py
index 463f15976..abc905637 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
@@ -157,6 +157,32 @@ async def health_coverage(
]
module_rows.sort(key=lambda x: x["line_coverage_pct"])
+ # The hybrid gap. A single stored row is enough to select the measured
+ # basis for the whole repository, but most files in most repos have no
+ # measured row at all (the lcov report never mentioned them) - here that is
+ # 2,209 of 3,608 files. Those files are not unindexed and not untested: the
+ # graph-inferred map has an answer for them and the all-or-nothing basis
+ # rule currently withholds it. Serve the inferred map for exactly the files
+ # with no measured row, so a partial ingest stops hiding the files it did
+ # not mention. ``basis`` stays ``measured`` and ``inferred`` reports only
+ # the non-measured set - a file is never in both, and measured rows never
+ # wear inferred percentages (none are derived here).
+ if include_inferred and not file_path:
+ measured_paths = frozenset(r.file_path for r in all_rows)
+ inferred = await _inferred_coverage(
+ session, repo_id, limit, excluded_paths=measured_paths
+ )
+ if inferred.get("basis") == "inferred":
+ inferred["inferred"]["measured_file_count"] = len(measured_paths)
+ return {
+ "basis": "measured",
+ "summary": summary,
+ "files": files,
+ "modules": module_rows[:module_limit] if module_limit else [],
+ "modules_total": len(module_rows),
+ "inferred": inferred["inferred"],
+ }
+
return {
"basis": "measured",
"summary": summary,
@@ -186,7 +212,11 @@ def _empty_summary() -> dict[str, Any]:
async def _inferred_coverage(
- session: AsyncSession, repo_id: str, limit: int
+ session: AsyncSession,
+ repo_id: str,
+ limit: int,
+ *,
+ excluded_paths: frozenset[str] = frozenset(),
) -> dict[str, Any]:
"""The graph-inferred test map, in the shape the measured one leaves empty.
@@ -197,8 +227,13 @@ async def _inferred_coverage(
walk also means this can never disagree with the ``untested_hotspot``
biomarker, which reads the same function.
- Counts are repo-wide even when ``files`` is trimmed, matching the measured
- branch's ``modules_total``: a truncated page must never read as the repo.
+ ``excluded_paths`` scopes the answer to the files *not* carrying a measured
+ coverage row. On the hybrid basis the measured branch already answers those
+ files; this map fills the gap for the rest, so a file is never in both.
+
+ Counts are repo-wide over the scoped set even when ``files`` is trimmed,
+ matching the measured branch's ``modules_total``: a truncated page must
+ never read as the repo.
Degrades to ``basis: "none"`` rather than raising. An unindexed graph is the
honest unknown, and failing the tab to withhold a secondary signal is the
@@ -214,6 +249,37 @@ async def _inferred_coverage(
"modules": [],
"modules_total": 0,
}
+ # Health metrics are the file list: already exclusion-filtered and
+ # already worst-first, which is the order the ranked list wants, and
+ # they carry the score and NLOC the chart plots. Test files are dropped
+ # - "is this tested" is not a question about a test. ``excluded_paths``
+ # (measured rows) are dropped too: those files are already answered by
+ # the measured map.
+ metrics = await crud.get_health_metrics(session, repo_id)
+ rows = [
+ m
+ for m in metrics
+ if m.file_path not in test_files and m.file_path not in excluded_paths
+ ]
+ if not rows:
+ # No gap: every health row also carries a measured coverage row.
+ # Return the empty shape without paying for the graph walk - a
+ # fully-measured repo should not read every call edge on the tab
+ # just to learn there is nothing to add.
+ return {
+ "basis": "inferred",
+ "summary": _empty_summary(),
+ "files": [],
+ "modules": [],
+ "modules_total": 0,
+ "inferred": {
+ "files": [],
+ "files_total": 0,
+ "files_reached": 0,
+ "files_not_reached": 0,
+ "test_file_count": len(test_files),
+ },
+ }
view = await call_graph_from_db(session, repo_id)
reached = files_reached_by_tests(view, test_files)
except Exception:
@@ -225,13 +291,6 @@ async def _inferred_coverage(
"modules_total": 0,
}
- # Health metrics are the file list: already exclusion-filtered and already
- # worst-first, which is the order the ranked list wants, and they carry the
- # score and NLOC the chart plots. Test files are dropped - "is this tested"
- # is not a question about a test.
- metrics = await crud.get_health_metrics(session, repo_id)
- rows = [m for m in metrics if m.file_path not in test_files]
-
reached_count = sum(1 for m in rows if m.file_path in reached)
files = [
{
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index e6b745136..6ce7385af 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -653,6 +653,13 @@ export interface InferredTestMap {
files_reached: number;
files_not_reached: number;
test_file_count: number;
+ /**
+ * Present only when `basis` is `measured` (the hybrid shape): how many files
+ * carry a measured coverage row. On that shape `inferred` is scoped to the
+ * files *without* a measured row, so this lets the UI state the split
+ * (measured vs graph-answered) honestly. Absent on the pure-inferred shape.
+ */
+ measured_file_count?: number;
}
/** Which tests reach one file, and which tier found them. */
@@ -694,9 +701,13 @@ export interface HealthCoverageResponse {
*/
basis?: CoverageBasis;
/**
- * Present only when `basis` is `inferred`. `summary`, `files` and `modules`
- * are then empty: measured rows and inferred rows never share an array, so no
- * consumer can render one through the other's code path by accident.
+ * Present only when `basis` is `inferred` (pure-inferred shape: `summary`,
+ * `files` and `modules` are empty so no consumer renders one through the
+ * other's code path) OR when `basis` is `measured` and the repo has files
+ * with no measured row (hybrid shape: the measured fields are populated, and
+ * `inferred` holds the graph answer for exactly the non-measured files).
+ * On the hybrid shape `measured_file_count` states the split. In both shapes
+ * the inferred map carries counts only — never a percentage.
*/
inferred?: InferredTestMap;
}
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index 6ac587261..9c2985703 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -25,6 +25,8 @@ import type {
CoverageFileRow,
HealthCoverageResponse,
HealthFinding,
+ InferredTestMap,
+ ReachedFileRow,
} from "@repowise-dev/types/health";
import { Skeleton } from "../ui/skeleton";
@@ -95,6 +97,11 @@ export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {
) : !data || data.summary.file_count === 0 ? (
<NoCoverageState />
) : (
+ // A report was ingested. `data.inferred` may also be present: when the
+ // report never mentioned some files, the graph answers for exactly
+ // those, and a separate section renders it. The measured body and the
+ // inferred gap stay apart — no percentage is ever derived from the
+ // inferred map.
<CoverageBody
data={data}
untestedFindings={untestedFindings ?? []}
@@ -453,10 +460,119 @@ function CoverageBody({
</p>
) : null}
</OverviewSection>
+
+ {data.inferred ? <CoverageGap data={data} onOpenFile={onOpenFile} /> : null}
</div>
);
}
+/**
+ * The files the ingested coverage report never mentioned, answered by the graph.
+ *
+ * This is the hybrid shape: a report exists (so `basis` is `measured` and the
+ * measured body above renders it), but the report's lcov source covered only a
+ * subset of the repo. Every other file was invisible on the Tests tab — not
+ * unindexed and not untested, just never named by the report. The graph knows
+ * whether a test reaches those files, and this section says that.
+ *
+ * It honours the same rules as the pure-inferred view: counts only, no bar and
+ * no percentage (reaching is a file-level fact with no line attribution), and
+ * no health-band colour. `files_total` here is the count of non-measured files,
+ * stated beside `measured_file_count` so the split is explicit.
+ */
+function CoverageGap({
+ data,
+ onOpenFile,
+}: {
+ data: HealthCoverageResponse;
+ onOpenFile: (path: string) => void;
+}) {
+ const map = data.inferred as InferredTestMap;
+ const measured = map.measured_file_count ?? 0;
+ const unreached = map.files.filter((f) => !f.reached);
+
+ return (
+ <OverviewSection
+ title="Files the report didn't cover"
+ description={
+ map.files_total > 0
+ ? `Your coverage report named ${measured.toLocaleString()} files. The dependency graph answers for the other ${map.files_total.toLocaleString()}: ${map.files_reached.toLocaleString()} are reached by a test, ${map.files_not_reached.toLocaleString()} are not. Reaching is not executing, so treat it as a floor, not a measurement.`
+ : "The dependency graph could not answer for the files the coverage report left out."
+ }
+ >
+ <div className="border-t border-[var(--color-border-default)]">
+ <ResponsiveTable
+ columns={gapColumns}
+ rows={unreached.slice(0, 50)}
+ rowKey={(f) => f.file_path}
+ onRowClick={(f) => onOpenFile(f.file_path)}
+ stacked="sm"
+ bare
+ empty={
+ <EmptyState
+ title="Every file is reached"
+ description="The graph found a test that reaches every file the coverage report didn't name."
+ />
+ }
+ />
+ </div>
+ </OverviewSection>
+ );
+}
+
+const gapColumns: ResponsiveColumn<ReachedFileRow>[] = [
+ {
+ key: "file_path",
+ header: "File",
+ priority: 1,
+ render: (f) => (
+ <span
+ className="block truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={f.file_path}
+ >
+ {f.file_path}
+ </span>
+ ),
+ },
+ {
+ key: "reached",
+ header: "Reached",
+ priority: 1,
+ render: (f) => (
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {f.reached ? "yes" : "no"}
+ </span>
+ ),
+ },
+ {
+ key: "nloc",
+ header: "Lines",
+ priority: 3,
+ align: "right",
+ render: (f) => (
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">
+ {f.nloc ?? "—"}
+ </span>
+ ),
+ },
+ {
+ key: "health_score",
+ header: "Health",
+ priority: 2,
+ align: "right",
+ render: (f) =>
+ f.health_score == null ? (
+ <span className="text-[var(--color-text-tertiary)]">—</span>
+ ) : (
+ <span
+ className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}
+ >
+ {f.health_score.toFixed(1)}
+ </span>
+ ),
+ },
+];
+
/**
* The last resort: no report, and the graph had nothing to say either — an
* unindexed repository, or one with no test files at all. When the graph *can*
diff --git a/tests/unit/server/test_health_coverage_basis.py b/tests/unit/server/test_health_coverage_basis.py
index f38b04a4a..decb0b7b3 100644
--- a/tests/unit/server/test_health_coverage_basis.py
+++ b/tests/unit/server/test_health_coverage_basis.py
@@ -122,9 +122,118 @@ async def test_an_ingested_report_answers_as_measured(client, session, tmp_path)
body = await _get(client, repo["id"], limit=500)
assert body["basis"] == "measured"
- # The graph is present and says something, and it stays out of the answer.
- assert "inferred" not in body
assert body["summary"]["line_coverage_pct"] == 40.0
+ # The measured rows fill `files`; the inferred block (served when the
+ # report missed some files) is present but has nothing to add here, because
+ # every file has a measured row. `files_total` is 0, so the UI renders no
+ # gap section.
+ assert body["inferred"]["files_total"] == 0
+ assert body["inferred"]["measured_file_count"] == 1
+
+
+async def test_partial_report_answers_measured_and_fills_the_gap(
+ client, session, tmp_path
+):
+ """A report that missed some files is measured, with the graph filling the gap.
+
+ This is the bug in #1763: one stored row selects the measured basis for the
+ whole repo, and every file the lcov report never mentioned became invisible
+ on the Tests tab. The fix serves the graph-inferred answer for exactly those
+ files, in a separate ``inferred`` block scoped to non-measured paths, so a
+ partial ingest stops hiding the files it did not mention.
+ """
+ repo = await create_test_repo(client, tmp_path)
+ # Only src/a.py has a measured row.
+ await save_coverage_files(
+ session,
+ repo["id"],
+ [
+ {
+ "file_path": "src/a.py",
+ "line_coverage_pct": 40.0,
+ "covered_lines": [1],
+ "total_coverable_lines": 10,
+ "branch_coverage_pct": None,
+ }
+ ],
+ source_format="lcov",
+ )
+ # src/b.py has no measured row but IS reached by a test; src/c.py is not.
+ await save_health_metrics(
+ session,
+ repo["id"],
+ [_metric("src/a.py"), _metric("src/b.py"), _metric("src/c.py")],
+ )
+ await _seed_graph(
+ session,
+ repo["id"],
+ nodes={
+ "tests/test_a.py": True,
+ "src/a.py": False,
+ "src/b.py": False,
+ "src/c.py": False,
+ },
+ edges=_calls("tests/test_a.py", "src/b.py"),
+ )
+ await session.commit()
+
+ body = await _get(client, repo["id"])
+
+ # Measured basis, measured rows in `files`.
+ assert body["basis"] == "measured"
+ assert [f["file_path"] for f in body["files"]] == ["src/a.py"]
+ assert body["summary"]["file_count"] == 1
+
+ # The inferred block answers the non-measured files only — never both.
+ assert body["inferred"]["measured_file_count"] == 1
+ reached = {f["file_path"]: f["reached"] for f in body["inferred"]["files"]}
+ assert reached == {"src/b.py": True, "src/c.py": False}
+ assert body["inferred"]["files_total"] == 2
+ assert body["inferred"]["files_reached"] == 1
+ assert body["inferred"]["files_not_reached"] == 1
+
+ # The inferred payload carries no percentage — the invariant holds on the
+ # hybrid shape too.
+ blob = json.dumps(body["inferred"])
+ assert "pct" not in blob
+
+
+async def test_the_hybrid_inferred_map_carries_no_percentage(
+ client, session, tmp_path
+):
+ """Same no-ratio rule as the pure-inferred shape, on the hybrid block."""
+ repo = await create_test_repo(client, tmp_path)
+ await save_coverage_files(
+ session,
+ repo["id"],
+ [
+ {
+ "file_path": "src/a.py",
+ "line_coverage_pct": 40.0,
+ "covered_lines": [1],
+ "total_coverable_lines": 10,
+ "branch_coverage_pct": None,
+ }
+ ],
+ source_format="lcov",
+ )
+ await save_health_metrics(
+ session,
+ repo["id"],
+ [_metric("src/a.py"), _metric("src/b.py")],
+ )
+ await _seed_graph(
+ session,
+ repo["id"],
+ nodes={"tests/test_a.py": True, "src/a.py": False, "src/b.py": False},
+ edges=_calls("tests/test_a.py", "src/b.py"),
+ )
+ await session.commit()
+
+ body = await _get(client, repo["id"])
+
+ assert body["basis"] == "measured"
+ assert "pct" not in json.dumps(body["inferred"])
async def test_no_report_falls_back_to_the_graph(client, session, tmp_path):