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(health): one test-reach definition for the Tests tab and the file page (#4334)

Raghav Chamadiya21f339b1dd75
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index a02c84f1c..480e35ea1 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -283,6 +283,10 @@ files, 159 production files provably executed):
is 77%.
- Framework-invoked code with no static caller (migrations run by naming convention, for
example) is not reached by the graph.
+- The Tests tab and a file's page share one definition of reached: a test calls into the
+ file or imports it, directly or through a chain of imports.
+ The tab's unreached list is a floor, so routes, CLI commands and plugin registries a
+ framework invokes can appear there with tests behind them.
- Inferred answers are file-level; only measured data is line-level.
- Measured data is only as current as the last ingest: each ingest replaces the previous
rows, so ingest at the commit you intend to query. Rows read `stale` once the index
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 c847e0b5b..906fe5d52 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
@@ -10,18 +10,25 @@ and ``modules`` come back empty and the answer rides in ``inferred``, so a UI
cannot render derived data through the measured code path by accident. Nothing
here derives a percentage from the inferred map: it has no line attribution, so
any ratio built from it would be a coverage figure the data cannot support.
+
+Both inferred routes share one definition of "a test reaches this file":
+:func:`any_tests_reaching` (call graph, then import graph, then a test-only
+helper or package entry file, then the whole import closure). The Tests tab and
+the file page can therefore never disagree about a file. A walk that fails answers
+``basis: "unavailable"``, never ``"none"``.
"""
from __future__ import annotations
import asyncio
+import logging
from typing import Any
from fastapi import Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.test_reachability import (
- cached_files_reached_by_tests,
+ any_tests_reaching,
cached_hub_files,
cached_test_files,
read_under,
@@ -37,6 +44,8 @@ from repowise.server.schemas.patch_coverage import PatchCoverageResponse
from ._router import router
+_log = logging.getLogger(__name__)
+
def _score(m: Any) -> float | None:
"""A file's health score; ``None`` where health has no dialect for it."""
@@ -199,12 +208,9 @@ async def _inferred_coverage(
) -> dict[str, Any]:
"""The graph-inferred test map, in the shape the measured one leaves empty.
- Reuses the health engine's forward walk rather than the attributed reverse
- one. This is the batch question - "which files does any test reach" - which
- is one multi-source search over the whole graph, where the reverse walk runs
- a query per level per seed and is built for a change's files. Sharing the
- walk also means this can never disagree with the ``untested_hotspot``
- biomarker, which reads the same function.
+ Reached means :func:`any_tests_reaching`, the same answer the file page
+ gives, so a file listed here as unreached never shows tests on its own
+ page. One batched reverse walk, cached per index state.
``excluded_paths`` scopes the answer to the files *not* carrying a measured
coverage row. On the hybrid basis the measured branch already answers those
@@ -214,9 +220,10 @@ async def _inferred_coverage(
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
- wrong trade.
+ ``basis: "none"`` means there are no test files to walk from. A walk that
+ raises is logged and answers ``basis: "unavailable"``: failing the tab over
+ a secondary signal is the wrong trade, and so is passing a failure off as
+ the graph having nothing to say.
"""
try:
test_files = await cached_test_files(session, repo_id)
@@ -259,8 +266,7 @@ async def _inferred_coverage(
"test_file_count": len(test_files),
},
}
- # Walked once per index state: the edge read is the cost of this tab.
- reached = await cached_files_reached_by_tests(session, repo_id)
+ reached = set(await any_tests_reaching(session, repo_id, [m.file_path for m in rows]))
# A file of only types has nothing a test could run: not a gap.
repo = await session.get(Repository, repo_id)
# Reads and parses files: off the event loop.
@@ -271,8 +277,9 @@ async def _inferred_coverage(
)
rows = [m for m in rows if m.file_path not in types]
except Exception:
+ _log.exception("inferred test map failed for repository %s", repo_id)
return {
- "basis": "none",
+ "basis": "unavailable",
"summary": crud.empty_coverage_summary(),
"files": [],
"modules": [],
@@ -313,10 +320,15 @@ async def health_tests_reaching(
) -> dict:
"""Which test files reach one file, and which tier of the graph found them.
- The attributed reverse walk, seeded with a single file - the shape it was
- built for. ``via`` separates ``call-graph`` (a test's calls run into this
- file) from the weaker ``import-graph`` (a test only imports it), so the file
- page can say which claim it is making.
+ The same definition as the Tests tab, :func:`any_tests_reaching`. ``via``
+ says which claim the file page is making: ``call-graph`` (a test's calls run
+ into this file), the weaker ``import-graph`` (a test imports it), or
+ ``indirect-import`` (a test imports a file that imports it: a test-only
+ helper, a package entry file, or a longer import chain). The core labels
+ every import route ``import-graph``; ``indirect-import`` is this route's
+ name for the routes past the first hop. ``mocked-only`` names a file whose
+ only reaching tests replace it with a double: the tab counts it as
+ reached, so the page lists those tests and says what they do.
``tests`` is capped at ``MAX_TESTS_PER_TARGET``; ``total`` is what the walk
found and ``truncated`` says whether the two differ. A file reached by 124
@@ -326,7 +338,7 @@ async def health_tests_reaching(
coverage report attributes lines to tests and this attributes files. A file
nothing reaches returns ``basis: "none"`` rather than an empty ``inferred``
answer, so "no test reaches this" stays distinguishable from "the graph had
- nothing to say".
+ nothing to say". A walk that raises answers ``basis: "unavailable"``.
"""
repo = await crud.get_repository(session, repo_id)
if repo is None:
@@ -342,25 +354,52 @@ async def health_tests_reaching(
"truncated": False,
}
try:
- # A listing: tests that reach the file only through a hub go last.
- hubs = await cached_hub_files(session, repo_id)
- found = await tests_reaching_by_tier(session, repo_id, [file_path], hubs=hubs)
+ row = (await any_tests_reaching(session, repo_id, [file_path])).get(file_path)
+ listing = None
+ if row is not None and row.reached is not None:
+ test_files = set(await cached_test_files(session, repo_id))
+ # The direct tiers, only to name the tier and order the list: tests
+ # that reach the file only through a hub go last.
+ hubs = await cached_hub_files(session, repo_id)
+ listing = (
+ await tests_reaching_by_tier(
+ session, repo_id, [file_path], test_files=test_files, hubs=hubs
+ )
+ ).get(file_path)
except Exception:
+ _log.exception("tests reaching %s failed for repository %s", file_path, repo_id)
+ return {**empty, "basis": "unavailable"}
+ if row is None:
return empty
- reached = found.get(file_path)
- if reached is None or not reached.tests:
+ if row.reached is None:
+ # ``mocked_only``: the only tests reaching the file replace it with a
+ # double. The tab counts it as reached, so the page names those tests.
+ tests = sorted(row.mocked_by)
+ via = "mocked-only"
+ total = len(tests)
+ else:
+ # The shared answer decides which tests count; the direct tiers only
+ # order them. A test the direct walk names but the shared one masks
+ # (it replaces the file) is left out.
+ allowed = list(row.reached.all_tests or row.reached.tests)
+ keep = set(allowed)
+ direct = [t for t in (listing.all_tests or listing.tests) if t in keep] if listing else []
+ tests = [*direct, *(t for t in allowed if t not in set(direct))]
+ via = listing.via if direct else "indirect-import"
+ total = row.reached.total or len(tests)
+ tests = tests[: len(row.reached.tests)]
+ if not tests:
return empty
- total = reached.total or len(reached.tests)
return {
"file_path": file_path,
"basis": "inferred",
"reached": True,
- "tests": reached.tests,
- "via": reached.via,
+ "tests": tests,
+ "via": via,
# The walk's own count, which ``tests`` may be a ranked, trimmed
# slice of. Without it a caller renders the cap as the answer.
"total": total,
- "truncated": total > len(reached.tests),
+ "truncated": total > len(tests),
}
diff --git a/packages/server/src/repowise/server/schemas/coverage.py b/packages/server/src/repowise/server/schemas/coverage.py
index 7c14e9681..a05fc5c86 100644
--- a/packages/server/src/repowise/server/schemas/coverage.py
+++ b/packages/server/src/repowise/server/schemas/coverage.py
@@ -71,13 +71,17 @@ class CoverageHistoryPoint(_Strict):
class CoverageResponse(BaseModel):
- """``GET /health/coverage``. ``basis`` is absent when the graph was not consulted."""
+ """``GET /health/coverage``. ``basis`` is absent when the graph was not consulted.
+
+ ``unavailable`` means the graph walk failed, which is not the same as ``none``
+ (no test files to walk from).
+ """
summary: CoverageSummary
files: list[dict[str, Any]]
modules: list[dict[str, Any]]
modules_total: int
- basis: Literal["measured", "inferred", "none"] | None = None
+ basis: Literal["measured", "inferred", "none", "unavailable"] | None = None
inferred: dict[str, Any] | None = None
#: Retained reports, oldest first, partial ones left out. Measured basis only.
history: list[CoverageHistoryPoint] | None = None
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index b075d2468..1dd1d5e32 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1332,13 +1332,18 @@ export interface CoverageReportPaths {
unmatched_sample: string[];
}
-/** ``GET /health/coverage``. ``basis`` is absent when the graph was not consulted. */
+/**
+ * ``GET /health/coverage``. ``basis`` is absent when the graph was not consulted.
+ *
+ * ``unavailable`` means the graph walk failed, which is not the same as ``none``
+ * (no test files to walk from).
+ */
export interface CoverageResponse {
summary: CoverageSummary;
files: Record<string, unknown>[];
modules: Record<string, unknown>[];
modules_total: number;
- basis?: "measured" | "inferred" | "none" | null;
+ basis?: "measured" | "inferred" | "none" | "unavailable" | null;
inferred?: Record<string, unknown> | null;
history?: CoverageHistoryPoint[] | null;
}
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 1423cc552..61b4a3f18 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -1337,19 +1337,23 @@ export type {
* Which signal answered "is this tested". `measured` is a coverage report: it
* records the lines a test really executed. `inferred` is the dependency graph:
* a test whose calls reach this file, which says control *can* flow there, not
- * that a run did. `none` is the honest unknown.
+ * that a run did. `none` is the honest unknown. `unavailable` means the graph
+ * walk failed, so nothing can be said either way until it is retried.
*
* The two are never merged and never averaged. They are different claims, and a
* reader who cannot tell them apart cannot tell a measured test from a guessed
* one. `basis` says which one answered; nothing blends them.
*/
-export type CoverageBasis = "measured" | "inferred" | "none";
+export type CoverageBasis = "measured" | "inferred" | "none" | "unavailable";
/**
* Which tier of the graph found a test. `call-graph` means a test's calls reach
- * the file, the stronger claim; `import-graph` means it only imports it.
+ * the file, the stronger claim; `import-graph` means it only imports it;
+ * `indirect-import` means it imports a file that imports it: a test-only
+ * helper, a package entry file, or a longer import chain; `mocked-only` means
+ * every test that reaches it replaces it with a double.
*/
-export type ReachedVia = "call-graph" | "import-graph";
+export type ReachedVia = "call-graph" | "import-graph" | "indirect-import" | "mocked-only";
/**
* One file on the inferred basis. `reached` is the whole of what this basis
@@ -1398,8 +1402,8 @@ export interface TestsReachingFile {
reached: boolean;
/**
* Empty when `reached` is false, and capped server-side. Render `total`
- * beside it, never `tests.length` on its own: the cut is alphabetical, so a
- * trimmed list states a cap as if it were the answer.
+ * beside it, never `tests.length` on its own, or a trimmed list states a
+ * cap as if it were the answer.
*/
tests: string[];
/** Null when `reached` is false. */
diff --git a/packages/ui/__tests__/health/inferred-tests.test.tsx b/packages/ui/__tests__/health/inferred-tests.test.tsx
index 4982d59b1..47c78171e 100644
--- a/packages/ui/__tests__/health/inferred-tests.test.tsx
+++ b/packages/ui/__tests__/health/inferred-tests.test.tsx
@@ -11,15 +11,22 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
+import { SWRConfig } from "swr";
import type {
HealthCoverageResponse,
+ HealthFinding,
InferredTestMap,
ReachedFileRow,
TestsReachingFile,
} from "@repowise-dev/types/health";
import { RiskCoverageScatter } from "../../src/health/risk-coverage-scatter.js";
-import { InferredTestsView } from "../../src/health/inferred-tests-view.js";
+import { CoverageView } from "../../src/health/coverage-view.js";
+import type { CodeHealthAdapter } from "../../src/health/code-health-adapter.js";
+import {
+ InferredTestsView,
+ UNREACHED_TITLE,
+} from "../../src/health/inferred-tests-view.js";
import { TestsReachingList } from "../../src/health/tests-reaching-list.js";
function row(
@@ -124,7 +131,7 @@ describe("RiskCoverageScatter, inferred basis", () => {
});
describe("InferredTestsView", () => {
- it("leads with the count of risky files nothing reaches", () => {
+ it("leads with the count of weak files no test reaches, as a floor", () => {
render(
<InferredTestsView
data={response()}
@@ -133,11 +140,41 @@ describe("InferredTestsView", () => {
/>,
);
- expect(screen.getByText("Files nothing tests")).toBeInTheDocument();
+ // The hero and the list title make the same floor statement.
+ expect(screen.getAllByText(UNREACHED_TITLE)).toHaveLength(2);
// src/b.py alone: unreached and under the at-risk score. src/a.py is
// reached, and an unreached file scoring well is not the headline. The
// singular unit is the assertion — it can only render from a count of one.
- expect(screen.getByText("risky file")).toBeInTheDocument();
+ expect(screen.getByText("weak file")).toBeInTheDocument();
+ // The list's known blind spot is named, not left for the reader to find.
+ expect(screen.getByText(/misses code a framework invokes/)).toBeInTheDocument();
+ });
+
+ it("counts the hero from the listed rows, not from the findings", () => {
+ // A finding for a reached file, and one for a well-scored unreached file:
+ // neither may move the count, which describes the list below it.
+ const findings = [
+ { file_path: "src/a.py" },
+ { file_path: "src/c.py" },
+ ] as HealthFinding[];
+ const data = response({
+ files: [
+ row({ file_path: "src/a.py", reached: true, health_score: 3 }),
+ row({ file_path: "src/b.py", reached: false, health_score: 3 }),
+ row({ file_path: "src/c.py", reached: false, health_score: 9 }),
+ ],
+ });
+ const { container } = render(
+ <InferredTestsView data={data} untestedFindings={findings} onOpenFile={vi.fn()} />,
+ );
+
+ expect(screen.getByText("weak file")).toBeInTheDocument();
+ // The flagged file still leads the list.
+ const rows = [...container.querySelectorAll("span[title]")].map((el) =>
+ el.getAttribute("title"),
+ );
+ expect(rows.indexOf("src/c.py")).toBeLessThan(rows.indexOf("src/b.py"));
+ expect(rows).not.toContain("src/a.py");
});
it("renders no percentage and no progress bar anywhere", () => {
@@ -168,7 +205,7 @@ describe("InferredTestsView", () => {
// Both sides named, and the denominator is files rather than lines: there
// is no line-level evidence behind this basis to count.
expect(screen.getByText("1 of 2 files")).toBeInTheDocument();
- expect(screen.getByText(/Nothing reaches the other 1/)).toBeInTheDocument();
+ expect(screen.getByText(/The graph finds no test for the other\s+1/)).toBeInTheDocument();
});
it("says the ranking was trimmed rather than letting it read as the repo", () => {
@@ -237,6 +274,57 @@ describe("TestsReachingList", () => {
expect(screen.getByText(/without necessarily running any of it/)).toBeInTheDocument();
});
+ it("names the indirect tier instead of saying nothing imports the file", async () => {
+ render(
+ <TestsReachingList
+ filePath="src/a.py"
+ cacheKey="k7"
+ fetcher={async () => answer({ via: "indirect-import" })}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(
+ screen.getByText(/import a file that imports this one/),
+ ).toBeInTheDocument(),
+ );
+ expect(screen.getByText(/indirect import/)).toBeInTheDocument();
+ });
+
+ it("says when the only tests reaching the file replace it", async () => {
+ render(
+ <TestsReachingList
+ filePath="src/a.py"
+ cacheKey="k9"
+ fetcher={async () => answer({ via: "mocked-only" })}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByText(/replace it with a double/)).toBeInTheDocument(),
+ );
+ expect(screen.getByText(/only tests that replace it/)).toBeInTheDocument();
+ });
+
+ it("says the answer is unknown when the server could not compute it", async () => {
+ render(
+ <TestsReachingList
+ filePath="src/a.py"
+ cacheKey="k8"
+ fetcher={async () =>
+ answer({ basis: "unavailable", reached: false, tests: [], via: null })
+ }
+ />,
+ );
+
+ await waitFor(() =>
+ expect(
+ screen.getByText(/could not load which tests reach this file/i),
+ ).toBeInTheDocument(),
+ );
+ expect(screen.queryByText(/No test reaches this file/)).not.toBeInTheDocument();
+ });
+
it("names the static limits when nothing reaches the file", async () => {
render(
<TestsReachingList
@@ -247,11 +335,11 @@ describe("TestsReachingList", () => {
);
await waitFor(() =>
- expect(screen.getByText(/No test in the repository calls into this file/)).toBeInTheDocument(),
+ expect(screen.getByText(/No test reaches this file through the graph/)).toBeInTheDocument(),
);
- // The caveat is the point: a framework hook is invisible to a static walk,
- // and claiming "untested" without saying so would overstate the evidence.
- expect(screen.getByText(/framework hook/)).toBeInTheDocument();
+ // The caveat is the point: framework-invoked code is invisible to a static
+ // walk, and claiming "untested" without saying so would overstate the evidence.
+ expect(screen.getByText(/Code a framework invokes/)).toBeInTheDocument();
});
it("names the true total when the list was cut, not the length shown", async () => {
@@ -268,7 +356,7 @@ describe("TestsReachingList", () => {
await waitFor(() =>
expect(screen.getByText("124 test files")).toBeInTheDocument(),
);
- expect(screen.getByText(/listing 2 of 124, cut alphabetically/)).toBeInTheDocument();
+ expect(screen.getByText(/listing 2 of 124/)).toBeInTheDocument();
});
it("renders nothing when the host has not wired the endpoint", () => {
@@ -299,7 +387,30 @@ describe("TestsReachingList", () => {
).toBeInTheDocument(),
);
expect(
- screen.queryByText(/No test in the repository calls into this file/),
+ screen.queryByText(/No test reaches this file/),
).not.toBeInTheDocument();
});
});
+
+describe("CoverageView, unavailable basis", () => {
+ it("says the walk failed instead of claiming no tests were found", async () => {
+ const adapter = {
+ cacheKey: "unavailable-test",
+ getCoverage: vi.fn().mockResolvedValue({ ...response(), basis: "unavailable", inferred: undefined }),
+ listFindings: vi.fn().mockResolvedValue([]),
+ navigate: vi.fn(),
+ fileHref: (p: string) => `/files/${p}`,
+ } as unknown as CodeHealthAdapter;
+
+ render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ <CoverageView adapter={adapter} />
+ </SWRConfig>,
+ );
+
+ expect(
+ await screen.findByText("Couldn't work out which files tests reach"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/found no\s+test files/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsx
index 8c5017819..60ee03863 100644
--- a/packages/ui/src/health/coverage-view.tsx
+++ b/packages/ui/src/health/coverage-view.tsx
@@ -78,6 +78,11 @@ export interface CoverageViewCopy {
/** "No untested hotspots across N measured files". */
cleanTitle?: (measuredFiles: number) => string;
cleanDescription?: string;
+ /** "No test reaches these through the graph": the inferred hero and list. */
+ unreachedTitle?: string;
+ /** Shown when the server could not compute which files tests reach. */
+ unavailableTitle?: string;
+ unavailableBody?: string;
}
/** The prompt input for one file row. */
@@ -145,6 +150,17 @@ export function CoverageView({
message={toFriendlyMessage(error)}
onRetry={() => void mutate()}
/>
+ ) : data?.basis === "unavailable" ? (
+ // The graph walk failed server-side. Unknown, so never the "no tests
+ // found" state below.
+ <ApiError
+ title={copy?.unavailableTitle ?? "Couldn't work out which files tests reach"}
+ message={
+ copy?.unavailableBody ??
+ "The dependency graph walk failed on the server, so this page cannot say either way. The server log has the error."
+ }
+ onRetry={() => void mutate()}
+ />
) : data?.basis === "inferred" && data.inferred ? (
// No report was ever ingested, and the graph can answer anyway. This
// branch never renders a measured field: the two bases are separate
@@ -154,6 +170,7 @@ export function CoverageView({
data={data}
untestedFindings={untestedFindings ?? []}
onOpenFile={openFilePage}
+ unreachedTitle={copy?.unreachedTitle}
/>
) : !data || data.summary.file_count === 0 ? (
<NoCoverageState />
@@ -591,7 +608,7 @@ function CoverageGap({
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.`
+ ? `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, and it finds no test for ${map.files_not_reached.toLocaleString()}. Treat that as a floor, not a measurement: it misses code a framework invokes, such as routes, CLI commands and plugin registries.`
: "The dependency graph could not answer for the files the coverage report left out."
}
>
diff --git a/packages/ui/src/health/inferred-tests-view.tsx b/packages/ui/src/health/inferred-tests-view.tsx
index facc0e56a..0b9f9c6d4 100644
--- a/packages/ui/src/health/inferred-tests-view.tsx
+++ b/packages/ui/src/health/inferred-tests-view.tsx
@@ -47,17 +47,23 @@ import { scoreBadgeClass } from "./tokens";
import { COVERAGE_REPORT_FORMATS_LABEL } from "./coverage-formats";
import { CiHint } from "../shared/ci-hint";
-/** Below this, a file nothing reaches is worth leading with. */
+/** Below this, a file no test reaches is worth leading with. */
const AT_RISK_SCORE = 6;
+/** The floor statement the hero and the list share. */
+export const UNREACHED_TITLE = "No test reaches these through the graph";
+
export function InferredTestsView({
data,
untestedFindings,
onOpenFile,
+ unreachedTitle = UNREACHED_TITLE,
}: {
data: HealthCoverageResponse;
untestedFindings: HealthFinding[];
onOpenFile: (path: string) => void;
+ /** Localised {@link UNREACHED_TITLE}. */
+ unreachedTitle?: string | undefined;
}) {
const map = data.inferred as InferredTestMap;
const PAGE = 25;
@@ -78,26 +84,20 @@ export function InferredTestsView({
);
// The hero. Scoped to what is actionable rather than to the whole repo: a
- // small integer cannot be misread as coverage, and "files nothing tests" on
- // its own would be a number nobody can act on in one sitting.
- //
- // Prefers the biomarker, which weighs churn and dependents, and falls back to
- // the plain score cut when the health pass has not run.
- const atRisk = useMemo(() => {
- const unreached = new Set(
- map.files.filter((f) => !f.reached).map((f) => f.file_path),
- );
- const flagged = untestedFindings.filter((f) => unreached.has(f.file_path));
- if (flagged.length > 0) return flagged.map((f) => f.file_path);
- return map.files
- .filter(
+ // small integer cannot be misread as coverage. Counted from the same rows as
+ // the list below, so the two can never describe different sets.
+ const atRisk = useMemo(
+ () =>
+ map.files.filter(
(f) => !f.reached && f.health_score != null && f.health_score < AT_RISK_SCORE,
- )
- .map((f) => f.file_path);
- }, [map.files, untestedFindings]);
+ ).length,
+ [map.files],
+ );
+ // The untested-hotspot findings only order the list (churn and dependents
+ // make a gap there cost more); they never add or remove a row.
const ranked = useMemo(() => {
- const rank = new Map(atRisk.map((p, i) => [p, i]));
+ const rank = new Map(untestedFindings.map((f, i) => [f.file_path, i]));
return map.files
.filter((f) => !f.reached)
.sort((a, b) => {
@@ -108,7 +108,7 @@ export function InferredTestsView({
if (rb != null) return 1;
return (a.health_score ?? 10) - (b.health_score ?? 10);
});
- }, [map.files, atRisk]);
+ }, [map.files, untestedFindings]);
const trimmed = map.files_total > map.files.length;
@@ -158,35 +158,37 @@ export function InferredTestsView({
return (
<div className="flex flex-col gap-6 sm:gap-8">
<PageLede
- label="Files nothing tests"
- value={formatNumber(atRisk.length)}
- unit={atRisk.length === 1 ? "risky file" : "risky files"}
+ label={unreachedTitle}
+ value={formatNumber(atRisk)}
+ unit={atRisk === 1 ? "weak file" : "weak files"}
layout="beside"
>
<p>
No coverage report has been ingested, so this reads the dependency
graph instead: a file is <strong className="font-semibold text-[var(--color-text-primary)]">reached</strong>{" "}
- when some test&apos;s calls run into code defined in it. Your{" "}
+ when a test calls into it or imports it, directly or through a chain
+ of imports. Your{" "}
{formatNumber(map.test_file_count)} test files reach{" "}
<strong className="font-semibold text-[var(--color-text-primary)]">
{formatNumber(map.files_reached)} of {formatNumber(map.files_total)} files
</strong>
- . Nothing reaches the other {formatNumber(map.files_not_reached)}.
+ . The graph finds no test for the other{" "}
+ {formatNumber(map.files_not_reached)}.
</p>
<p className="mt-2.5">
- The figure beside this is the part worth acting on: files nothing
- reaches that we also score as weak. Reaching is not executing, so treat
- it as a floor rather than a measurement. A call edge says control{" "}
- <em>can</em> flow into the file, which makes &ldquo;something tests
- this&rdquo; safe to trust and &ldquo;this much is tested&rdquo;
- something it cannot tell you.
+ The figure beside this counts those files that also score as weak.
+ Treat the list as a floor: it misses code a framework invokes rather
+ than your code calling it, such as route handlers, CLI commands and
+ plugin registries. Reaching is not executing either, so &ldquo;a test
+ reaches this&rdquo; is safe to trust and &ldquo;this much is
+ tested&rdquo; is something it cannot tell you.
</p>
</PageLede>
<OverviewSection
title="Health against tests"
- description="Every file placed by its 0–10 defect-health score (higher is healthier), split by whether any test reaches it, sized by lines of code. There is no percentage axis here because there is no line-level evidence to build one from. The left column is the page: weak code nothing runs. Click a file to open it."
+ description="Every file placed by its 0–10 defect-health score (higher is healthier), split by whether any test reaches it, sized by lines of code. There is no percentage axis here because there is no line-level evidence to build one from. The left column is the page: weak code no test reaches through the graph. Click a file to open it."
>
<RiskCoverageScatter
basis="inferred"
@@ -196,8 +198,8 @@ export function InferredTestsView({
</OverviewSection>
<OverviewSection
- title="Nothing reaches these"
- description="Worst health first, and the files the untested-hotspot marker flagged lead the list because churn and dependents make a gap there cost more. Open a file to see what the graph does and does not know about it."
+ title={unreachedTitle}
+ description="Worst health first, and the files the untested-hotspot marker flagged lead the list because churn and dependents make a gap there cost more. Code a framework invokes (routes, CLI commands, plugin registries) can land here with tests behind it, so open a file to check before writing tests for it."
>
<div className="border-t border-[var(--color-border-default)]">
<ResponsiveTable
@@ -251,8 +253,8 @@ function AddResolutionSection() {
<p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
Hand us a report and the two columns above become a continuous axis,
every file moves to its own coverage figure, and the untested-hotspot
- list narrows from &ldquo;nothing calls this&rdquo; to the exact lines no
- test executed. Reaching becomes measuring.
+ list narrows from &ldquo;no test reaches this&rdquo; to the lines no test
+ executed. Reaching becomes measuring.
</p>
<pre className="w-fit overflow-x-auto rounded-md bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">
pytest --cov --cov-report=lcov{"\n"}
diff --git a/packages/ui/src/health/tests-reaching-list.tsx b/packages/ui/src/health/tests-reaching-list.tsx
index be1076a93..4c7bd5c93 100644
--- a/packages/ui/src/health/tests-reaching-list.tsx
+++ b/packages/ui/src/health/tests-reaching-list.tsx
@@ -32,10 +32,11 @@ export interface TestsReachingListProps {
* figure the data cannot support, and the moment it becomes one we have rebuilt
* the confusion the core spent its whole design avoiding.
*
- * `via` is carried through rather than flattened because the two tiers are
+ * `via` is carried through rather than flattened because the tiers are
* different claims. A test whose calls run into the file is strong evidence; a
- * test that merely imports it is real but much cruder, and a reader deciding
- * whether this file is guarded needs to know which one they have.
+ * test that merely imports it, directly or through another module, is real
+ * but much cruder, and a reader deciding whether this file
+ * is guarded needs to know which one they have.
*/
export function TestsReachingList({
filePath,
@@ -53,7 +54,9 @@ export function TestsReachingList({
if (!fetcher) return null;
if (isLoading) return <Skeleton className="h-16 w-full max-w-[52ch] rounded-md" />;
- if (error) {
+ // A failed request and a walk the server could not finish read the same: the
+ // answer is unknown, which must not render as "no test reaches this".
+ if (error || data?.basis === "unavailable") {
return (
<div className="flex flex-col gap-1.5">
{heading ? <Heading>Tests reaching this file</Heading> : null}
@@ -64,17 +67,18 @@ export function TestsReachingList({
);
}
- // A file nothing reaches is the honest answer, not an error, and it is the
+ // A file no test reaches is the honest answer, not an error, and it is the
// one the reader most needs: it is the whole left column of the chart.
if (!data || !data.reached || data.tests.length === 0) {
return (
<div className="flex flex-col gap-1.5">
{heading ? <Heading>Tests reaching this file</Heading> : null}
<p className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
- No test in the repository calls into this file, and none imports it.
- That is a static reading of the dependency graph, so a test that
- reaches it only through a framework hook or a name looked up at run
- time would not show up here.
+ No test reaches this file through the graph: none calls into it or
+ imports it, directly or through any chain of imports.
+ That is a floor, not a verdict. Code a framework invokes, such as a
+ route handler, a CLI command or a plugin registry, and names looked up
+ at run time are invisible to it.
</p>
</div>
);
@@ -119,11 +123,8 @@ export function TestsReachingList({
))}
</ul>
<p className="border-t border-[var(--color-border-default)] pt-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- {data.via === "call-graph" ? "call graph" : "import graph"} · no report
- needed
- {count > shown
- ? ` · listing ${shown} of ${count}, cut alphabetically`
- : ""}
+ {TIER_LABEL[data.via ?? "call-graph"]} · no report needed
+ {count > shown ? ` · listing ${shown} of ${count}` : ""}
</p>
</div>
);
@@ -137,6 +138,13 @@ function Heading({ children }: { children: React.ReactNode }) {
);
}
+const TIER_LABEL: Record<ReachedVia, string> = {
+ "call-graph": "call graph",
+ "import-graph": "import graph",
+ "indirect-import": "indirect import",
+ "mocked-only": "only tests that replace it",
+};
+
/**
* Names the claim rather than the tier. "Reached via call-graph" is our word for
* it; "runs into this file" is what it means to the person reading.
@@ -145,5 +153,11 @@ function viaSentence(via: ReachedVia | null): string {
if (via === "import-graph") {
return "import this file. Nothing calls into it, so they load it without necessarily running any of it.";
}
+ if (via === "mocked-only") {
+ return "reach this file only to replace it with a double, so none of them runs its code.";
+ }
+ if (via === "indirect-import") {
+ return "import a file that imports this one: a test helper, a package entry file, or a longer import chain. None imports or calls it directly, so they load it without necessarily running any of it.";
+ }
return "run into this file: their calls reach code defined here, within three hops.";
}
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 17cd4ff7e..d5962237e 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -993,7 +993,10 @@
"promptAction": "Copy prompt for your agent",
"cleanTitle": "No untested hotspots across {files} measured files",
"cleanBody": "Every file that changes often or that much of the code depends on has tests watching it.",
- "batchPromptAction": "Copy prompt for these {count}"
+ "batchPromptAction": "Copy prompt for these {count}",
+ "unreachedTitle": "No test reaches these through the graph",
+ "unavailableTitle": "Couldn't work out which files tests reach",
+ "unavailableBody": "The dependency graph walk failed on the server, so this page cannot say either way. The server log has the error."
},
"docDrift": {
"cleanTitle": "No documentation drift found",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 40a4ea900..a71f9fde0 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -993,7 +993,10 @@
"promptAction": "为你的智能体复制提示词",
"cleanTitle": "{files} 个已测量文件中没有未测试的热点",
"cleanBody": "所有频繁变更或被大量代码依赖的文件都有测试覆盖。",
- "batchPromptAction": "为这 {count} 项复制提示词"
+ "batchPromptAction": "为这 {count} 项复制提示词",
+ "unreachedTitle": "依赖图中没有测试触及这些文件",
+ "unavailableTitle": "无法确定测试触及了哪些文件",
+ "unavailableBody": "服务器上的依赖图遍历失败,因此本页无法给出任何结论。错误详情见服务器日志。"
},
"docDrift": {
"cleanTitle": "未发现文档漂移",
diff --git a/packages/web/src/components/tests/tests-view.tsx b/packages/web/src/components/tests/tests-view.tsx
index 27bb96f04..115981520 100644
--- a/packages/web/src/components/tests/tests-view.tsx
+++ b/packages/web/src/components/tests/tests-view.tsx
@@ -51,6 +51,9 @@ export function TestsView({ repoId: id }: { repoId: string }) {
batchPromptLabel: (count) => t("batchPromptAction", { count }),
cleanTitle: (files) => t("cleanTitle", { files: formatNumber(files) }),
cleanDescription: t("cleanBody"),
+ unreachedTitle: t("unreachedTitle"),
+ unavailableTitle: t("unavailableTitle"),
+ unavailableBody: t("unavailableBody"),
}),
[t],
);
diff --git a/tests/unit/server/test_health_coverage_basis.py b/tests/unit/server/test_health_coverage_basis.py
index 0df31d7d8..ff6f621bd 100644
--- a/tests/unit/server/test_health_coverage_basis.py
+++ b/tests/unit/server/test_health_coverage_basis.py
@@ -604,6 +604,119 @@ async def test_the_file_endpoint_404s_for_an_unknown_repo(client):
assert resp.status_code == 404
+# ------------------------------------------------------------------ #
+# One reach definition for the tab and the file page
+# ------------------------------------------------------------------ #
+
+
+async def test_the_tab_and_the_file_page_agree_on_every_file(client, session, tmp_path):
+ """A file is reached on the tab exactly when its own page lists tests.
+
+ Covers each tier: a call, an import only, an import through a test-only
+ helper, one further up a chain of source imports, and a file whose only
+ test replaces it. A file a test only imports is reached on both surfaces.
+ """
+ repo = await create_test_repo(client, tmp_path)
+ # The replacing test's text is read from the checkout.
+ (tmp_path / "test-repo" / "tests").mkdir()
+ (tmp_path / "test-repo" / "tests" / "test_mock.py").write_text(
+ 'from unittest.mock import patch\n@patch("app.swapped")\ndef test_it(m): ...\n',
+ encoding="utf-8",
+ )
+ files = [
+ "src/called.py",
+ "src/imported.py",
+ "src/behind_helper.py",
+ "src/deep.py",
+ "app/swapped.py",
+ "src/lonely.py",
+ ]
+ await save_health_metrics(session, repo["id"], [_metric(p) for p in files])
+ await _seed_graph(
+ session,
+ repo["id"],
+ nodes={
+ "tests/test_a.py": True,
+ "tests/test_mock.py": True,
+ "app/__init__.py": False,
+ "tests/support.py": False,
+ "src/top.py": False,
+ "src/mid.py": False,
+ "src/app.py": False,
+ **{p: False for p in files},
+ },
+ edges=[
+ *_calls("tests/test_a.py", "src/called.py"),
+ *_calls("tests/test_mock.py", "app/swapped.py"),
+ ("tests/test_a.py", "src/imported.py", "imports"),
+ ("tests/test_a.py", "tests/support.py", "imports"),
+ ("tests/support.py", "src/behind_helper.py", "imports"),
+ # A chain through source files nothing else marks as test support.
+ ("tests/test_a.py", "src/top.py", "imports"),
+ ("src/top.py", "src/mid.py", "imports"),
+ ("src/app.py", "src/mid.py", "imports"),
+ ("src/mid.py", "src/deep.py", "imports"),
+ ],
+ )
+ await session.commit()
+
+ tab = await _get(client, repo["id"])
+ on_tab = {f["file_path"]: f["reached"] for f in tab["inferred"]["files"]}
+ pages = {p: await _reaching(client, repo["id"], p) for p in files}
+
+ assert on_tab == {p: page["reached"] for p, page in pages.items()}
+ assert on_tab == {
+ "src/called.py": True,
+ "src/imported.py": True,
+ "src/behind_helper.py": True,
+ "src/deep.py": True,
+ "app/swapped.py": True,
+ "src/lonely.py": False,
+ }
+ assert tab["inferred"]["files_reached"] == 5
+ assert tab["inferred"]["files_not_reached"] == 1
+ assert {p: page["via"] for p, page in pages.items()} == {
+ "src/called.py": "call-graph",
+ "src/imported.py": "import-graph",
+ "src/behind_helper.py": "indirect-import",
+ "src/deep.py": "indirect-import",
+ "app/swapped.py": "mocked-only",
+ "src/lonely.py": None,
+ }
+ assert pages["src/behind_helper.py"]["tests"] == ["tests/test_a.py"]
+ assert pages["app/swapped.py"]["tests"] == ["tests/test_mock.py"]
+
+
+async def test_a_failed_walk_answers_unavailable_not_none(
+ client, session, tmp_path, monkeypatch
+):
+ """A failure is not "the graph had nothing to say", on either route."""
+ from repowise.server.routers.code_health import coverage_routes
+
+ async def broken(*args, **kwargs):
+ raise RuntimeError("walk failed")
+
+ monkeypatch.setattr(coverage_routes, "any_tests_reaching", broken)
+ monkeypatch.setattr(coverage_routes, "tests_reaching_by_tier", broken)
+ repo = await create_test_repo(client, tmp_path)
+ await save_health_metrics(session, repo["id"], [_metric("src/a.py")])
+ await _seed_graph(
+ session,
+ repo["id"],
+ nodes={"tests/test_a.py": True, "src/a.py": False},
+ edges=_calls("tests/test_a.py", "src/a.py"),
+ )
+ await session.commit()
+
+ body = await _get(client, repo["id"])
+ assert body["basis"] == "unavailable"
+ assert "inferred" not in body
+
+ detail = await _reaching(client, repo["id"], "src/a.py")
+ assert detail["basis"] == "unavailable"
+ assert detail["reached"] is False
+
+
async def test_a_file_of_only_types_is_not_a_row_nothing_reaches(client, session, tmp_path):
"""A ``.d.ts`` or a module of ``TypedDict`` classes has nothing a test could run."""
repo = await create_test_repo(client, tmp_path)