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.

perf(health): stop shipping every file's findings in the refactoring-targets list (#1345)

Raghav Chamadiya1c96a33fd840
diff --git a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
index 77a625ef0..17ac8bfb3 100644
--- a/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/refactoring_routes.py
@@ -13,7 +13,6 @@ from repowise.server.deps import get_db_session
from ._router import router
from .aggregation import _clean_module
-from .serializers import _finding_to_dict
_SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2, "critical": 3}
@@ -60,7 +59,16 @@ async def refactoring_targets(
),
session: AsyncSession = Depends(get_db_session),
) -> dict:
- """Refactoring candidates ranked by impact / effort."""
+ """Refactoring candidates ranked by impact / effort.
+
+ A target carries its *primary* finding plus ``finding_count``, not the
+ findings themselves. Serializing every file's full finding list here cost
+ 1.8 MB at the default ``limit=200`` (2.9 MB at 500) to render a list that
+ shows none of it — the work was done for all ~2,400 files with findings,
+ before the ``[:limit]`` slice, and ~90% was then discarded. The two
+ consumers both sit behind a click and fetch what they need from
+ ``GET /health/findings?file_path=``.
+ """
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
@@ -115,7 +123,6 @@ async def refactoring_targets(
"biomarkers": sorted({x.biomarker_type for x in fs}),
"effort_bucket": effort_bucket,
"impact_per_effort": ratio,
- "all_findings": [_finding_to_dict(f) for f in fs],
}
)
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 6e2896a71..cfc22cd82 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -531,6 +531,13 @@ export interface RefactoringTarget {
biomarkers: string[];
effort_bucket: "S" | "M" | "L" | "XL";
impact_per_effort: number;
+ /**
+ * No longer served by the OSS `/health/refactoring-targets` route: building it
+ * for every file with findings, before the `limit` slice, cost 1.8 MB per
+ * request to feed two click-gated consumers. Fetch a file's findings from
+ * `GET /health/findings?file_path=` instead. Kept optional because the hosted
+ * backend still sends it and a client may hold a cached older payload.
+ */
all_findings?: Array<{
id: string;
biomarker_type: string;
diff --git a/packages/ui/__tests__/health/refactoring-card.test.tsx b/packages/ui/__tests__/health/refactoring-card.test.tsx
new file mode 100644
index 000000000..62a36c286
--- /dev/null
+++ b/packages/ui/__tests__/health/refactoring-card.test.tsx
@@ -0,0 +1,113 @@
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import {
+ RefactoringCard,
+ type RefactoringTarget,
+ type RefactoringTargetFinding,
+} from "../../src/health/refactoring-card.js";
+
+function target(partial: Partial<RefactoringTarget> = {}): RefactoringTarget {
+ return {
+ file_path: "packages/core/pipeline/incremental.py",
+ score: 1.0,
+ nloc: 900,
+ primary_biomarker: "brain_method",
+ primary_severity: "high",
+ primary_reason: "Oversized, deeply-nested function.",
+ primary_function: "_run",
+ primary_line_start: 10,
+ primary_line_end: 400,
+ total_impact: 6.2,
+ finding_count: 3,
+ biomarkers: ["brain_method"],
+ effort_bucket: "XL",
+ impact_per_effort: 1.24,
+ ...partial,
+ };
+}
+
+function findings(): RefactoringTargetFinding[] {
+ return [
+ {
+ id: "a",
+ biomarker_type: "brain_method",
+ severity: "high",
+ function_name: "_run",
+ health_impact: 3.2,
+ reason: "Oversized, deeply-nested function.",
+ },
+ {
+ id: "b",
+ biomarker_type: "error_handling",
+ severity: "low",
+ function_name: null,
+ health_impact: 0.15,
+ reason: "broad `except Exception` catches unrelated errors.",
+ },
+ ];
+}
+
+describe("RefactoringCard lazy findings", () => {
+ it("offers the expander from finding_count, without the findings themselves", () => {
+ // The list response no longer ships `all_findings`; the expander must not
+ // disappear just because the payload got smaller.
+ render(<RefactoringCard target={target()} onLoadFindings={async () => []} />);
+ expect(screen.getByRole("button", { name: /Show all 3 findings/ })).toBeInTheDocument();
+ });
+
+ it("fetches findings on first expand and reuses them on re-expand", async () => {
+ const load = vi.fn(async () => findings());
+ render(<RefactoringCard target={target()} onLoadFindings={load} />);
+
+ expect(load).not.toHaveBeenCalled(); // nothing fetched until the click
+
+ fireEvent.click(screen.getByRole("button", { name: /Show all 3 findings/ }));
+ await waitFor(() =>
+ expect(screen.getByText(/broad `except Exception`/)).toBeInTheDocument(),
+ );
+ expect(load).toHaveBeenCalledWith("packages/core/pipeline/incremental.py");
+
+ // Collapse and re-expand: cached, so no second request.
+ fireEvent.click(screen.getByRole("button", { name: /Hide all 3 findings/ }));
+ fireEvent.click(screen.getByRole("button", { name: /Show all 3 findings/ }));
+ await waitFor(() =>
+ expect(screen.getByText(/broad `except Exception`/)).toBeInTheDocument(),
+ );
+ expect(load).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the card usable when the findings fetch fails", async () => {
+ const load = vi.fn(async () => {
+ throw new Error("boom");
+ });
+ render(<RefactoringCard target={target()} onLoadFindings={load} />);
+ fireEvent.click(screen.getByRole("button", { name: /Show all 3 findings/ }));
+ await waitFor(() =>
+ expect(screen.getByText("Could not load findings.")).toBeInTheDocument(),
+ );
+ // The header still carries the primary finding.
+ expect(screen.getByText(/Oversized, deeply-nested function/)).toBeInTheDocument();
+ });
+
+ it("prefers findings already on the target over a fetch", async () => {
+ const load = vi.fn(async () => []);
+ render(
+ <RefactoringCard
+ target={target({ all_findings: findings() })}
+ onLoadFindings={load}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Show all 3 findings/ }));
+ await waitFor(() =>
+ expect(screen.getByText(/broad `except Exception`/)).toBeInTheDocument(),
+ );
+ expect(load).not.toHaveBeenCalled();
+ });
+
+ it("hides the expander when the file has no findings", () => {
+ render(
+ <RefactoringCard target={target({ finding_count: 0 })} onLoadFindings={async () => []} />,
+ );
+ expect(screen.queryByRole("button", { name: /findings/ })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index 9135907b9..f1627be0e 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -37,6 +37,7 @@ import {
type FindingStatus,
type RefactoringTarget,
} from "./refactoring-target-list";
+import type { RefactoringTargetFinding } from "./refactoring-card";
import { FilterSelect, FilterChip, ViewToggle } from "./code-health-controls";
import { ImpactEffortQuadrant } from "./impact-effort-quadrant";
import { biomarkerLabel } from "./biomarker-glossary";
@@ -119,6 +120,28 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);
+ // The targets list no longer ships `all_findings` — it cost 1.8 MB per
+ // request to serve two click-gated consumers. Both fetch here instead.
+ // `limit` is generous: this is one file's findings, and the worst file in a
+ // large repo carries a few hundred.
+ const loadFindings = async (filePath: string) =>
+ (await adapter.listFindings({
+ file_path: filePath,
+ limit: 1000,
+ })) as RefactoringTargetFinding[];
+
+ // The prompt promises the agent "every marker", so hydrate before opening
+ // rather than letting the builder fall back to the primary finding alone.
+ const openPrompt = async (t: RefactoringTarget) => {
+ setPromptTarget(t);
+ try {
+ setPromptTarget({ ...t, all_findings: await loadFindings(t.file_path) });
+ } catch {
+ // Leave the un-hydrated target in place: the builder degrades to the
+ // primary finding, which is better than no prompt at all.
+ }
+ };
+
const queueKey = useMemo(
() =>
JSON.stringify({ cacheKey, biomarker, minSeverity, maxEffort, sort, queueLimit }),
@@ -372,7 +395,8 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
targets={g.targets}
onSelect={(t) => setSelectedFile(t.file_path)}
onStatusChange={handleStatus}
- onGeneratePrompt={(t) => setPromptTarget(t)}
+ onGeneratePrompt={(t) => void openPrompt(t)}
+ onLoadFindings={loadFindings}
/>
</section>
))}
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index 2372ae07b..d5c6c508b 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -51,6 +51,16 @@ export interface RefactoringCardProps {
onSelect?: ((target: RefactoringTarget) => void) | undefined;
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;
+ /**
+ * Fetch this file's findings, called on first expand. The list response
+ * deliberately omits them — serializing every file's findings to render a
+ * list that shows none of them cost 1.8 MB per request. Falls back to
+ * `target.all_findings` when the host does not supply this, so a card fed by
+ * an older payload still expands.
+ */
+ onLoadFindings?:
+ | ((filePath: string) => Promise<RefactoringTargetFinding[]>)
+ | undefined;
expandable?: boolean;
/** Flash-highlight the card (e.g. after a quadrant dot click scrolled to it). */
highlighted?: boolean;
@@ -75,10 +85,31 @@ export function RefactoringCard({
onSelect,
onStatusChange,
onGeneratePrompt,
+ onLoadFindings,
expandable = true,
highlighted = false,
}: RefactoringCardProps) {
const [expanded, setExpanded] = useState(false);
+ const [loaded, setLoaded] = useState<RefactoringTargetFinding[] | null>(null);
+ const [loadFailed, setLoadFailed] = useState(false);
+
+ // `finding_count` is on every target, so the expander's presence and its
+ // label no longer depend on shipping the findings themselves.
+ const findings = target.all_findings ?? loaded;
+ const hasFindings = target.finding_count > 0;
+
+ const toggle = async () => {
+ const next = !expanded;
+ setExpanded(next);
+ if (!next || findings || !onLoadFindings) return;
+ setLoadFailed(false);
+ try {
+ setLoaded(await onLoadFindings(target.file_path));
+ } catch {
+ // Keep the card usable: the header already carries the primary finding.
+ setLoadFailed(true);
+ }
+ };
return (
<div
data-refactoring-card={target.file_path}
@@ -165,19 +196,25 @@ export function RefactoringCard({
</div>
) : null}
</div>
- {expandable && target.all_findings && target.all_findings.length > 0 ? (
+ {expandable && hasFindings ? (
<>
<button
type="button"
- onClick={() => setExpanded((e) => !e)}
+ onClick={toggle}
+ aria-expanded={expanded}
className="flex w-full items-center gap-2 px-4 py-2 text-xs text-[var(--color-text-secondary)] border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]"
>
{expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
- {expanded ? "Hide" : "Show"} all {target.all_findings.length} findings
+ {expanded ? "Hide" : "Show"} all {target.finding_count} findings
</button>
- {expanded ? (
+ {expanded && !findings ? (
+ <p className="border-t border-[var(--color-border-default)] px-4 py-2 text-xs text-[var(--color-text-tertiary)]">
+ {loadFailed ? "Could not load findings." : "Loading findings…"}
+ </p>
+ ) : null}
+ {expanded && findings ? (
<ul className="divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)]">
- {target.all_findings.map((f) => (
+ {findings.map((f) => (
<li key={f.id} className="px-4 py-2 space-y-1">
<div className="flex items-center gap-2 flex-wrap">
<SeverityMark severity={f.severity} />
diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsx
index 68f647f18..8a2335ec9 100644
--- a/packages/ui/src/health/refactoring-target-list.tsx
+++ b/packages/ui/src/health/refactoring-target-list.tsx
@@ -1,10 +1,19 @@
-import { RefactoringCard, type RefactoringTarget, type FindingStatus } from "./refactoring-card";
+import {
+ RefactoringCard,
+ type RefactoringTarget,
+ type RefactoringTargetFinding,
+ type FindingStatus,
+} from "./refactoring-card";
export interface RefactoringTargetListProps {
targets: RefactoringTarget[];
onSelect?: ((target: RefactoringTarget) => void) | undefined;
onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;
onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;
+ /** Per-card lazy fetch of a file's findings; see `RefactoringCardProps`. */
+ onLoadFindings?:
+ | ((filePath: string) => Promise<RefactoringTargetFinding[]>)
+ | undefined;
emptyMessage?: string;
/** File path of the card to flash-highlight (quadrant click). */
highlightedPath?: string | null | undefined;
@@ -15,6 +24,7 @@ export function RefactoringTargetList({
onSelect,
onStatusChange,
onGeneratePrompt,
+ onLoadFindings,
emptyMessage = "No refactoring targets match the current filters.",
highlightedPath,
}: RefactoringTargetListProps) {
@@ -34,6 +44,7 @@ export function RefactoringTargetList({
onSelect={onSelect}
onStatusChange={onStatusChange}
onGeneratePrompt={onGeneratePrompt}
+ onLoadFindings={onLoadFindings}
highlighted={highlightedPath === t.file_path}
/>
))}