perf(problems): rebuild only the changed file's Problems entries per diagnostics update (#4040)

A diagnostics event for one file made the Problems view merge, filter and sort every file's diagnostics again, and the tab header and tool window badge recounted every error in the workspace. Each file's merged list and Problems node are now cached by its sources map (replaced only when that file changes), and the store keeps project severity counts up to date per event, recomputing them on a profile change. Output is unchanged.

Part of #3937

Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com>
This commit is contained in:
Bert Verhelst
2026-11-18 17:04:39 +08:00
committed by GitHub
co-authored by bertyhell
parent eb37d9e96a
commit 895d042dd7
6 changed files with 326 additions and 51 deletions
+62 -31
View File
@@ -40,6 +40,7 @@ import {
producerFor,
sortProblems,
useProblems,
type FileDiagnostics,
type ProblemOrder,
type ProblemsMap,
} from "./problemsStore";
@@ -113,9 +114,8 @@ export function useProblemsHeaderMenu(): MenuItem[] {
const group = (s: Severity): "error" | "warning" | "info" => (s === "hint" ? "info" : s);
type Node =
| { kind: "file"; key: string; path: string; items: Diagnostic[] }
| { kind: "diag"; key: string; path: string; d: Diagnostic };
type FileNode = { kind: "file"; key: string; path: string; items: Diagnostic[]; error: boolean };
type Node = FileNode | { kind: "diag"; key: string; path: string; d: Diagnostic };
/** The inspection that reported `d` (for Disable inspection / Change Severity). */
export function diagInspection(map: ProblemsMap, path: string, d: Diagnostic): InspectionRef | null {
@@ -129,23 +129,64 @@ const plural = (n: number, word: string) => (n ? `${n} ${word}${n === 1 ? "" : "
const SEVERITY_ICON: Record<Severity, string> = { error: "error", warning: "warning", info: "info", hint: "info" };
interface CachedFileNode {
path: string;
show: ViewState["show"];
order: ProblemOrder;
node: FileNode | null;
}
// Keyed by the file's sources map, which the store replaces only when that file's diagnostics
// change: a single-file update re-filters and re-sorts that file alone.
const fileNodes = new WeakMap<FileDiagnostics, CachedFileNode>();
function fileNode(map: ProblemsMap, path: string, show: ViewState["show"], order: ProblemOrder): FileNode | null {
const sources = map.get(path);
if (!sources) return null;
const hit = fileNodes.get(sources);
if (
hit?.path === path &&
hit.show.error === show.error &&
hit.show.warning === show.warning &&
hit.show.info === show.info &&
hit.order.bySeverity === order.bySeverity &&
hit.order.byName === order.byName
)
return hit.node;
const items = sortProblems(
fileDiagnostics(map, path).filter((d) => show[group(d.severity)]),
order,
);
const node: FileNode | null = items.length
? { kind: "file", key: path, path, items, error: items.some((d) => d.severity === "error") }
: null;
fileNodes.set(sources, { path, show: { ...show }, order: { ...order }, node });
return node;
}
export function buildProblemNodes(
map: ProblemsMap,
paths: readonly string[],
show: ViewState["show"],
order: ProblemOrder = DEFAULT_PROBLEM_ORDER,
): Node[] {
const files: Node[] = [];
): FileNode[] {
const files: FileNode[] = [];
for (const path of paths) {
const items = sortProblems(
fileDiagnostics(map, path).filter((d) => show[group(d.severity)]),
order,
);
if (!items.length) continue;
files.push({ kind: "file", key: path, path, items });
const node = fileNode(map, path, show, order);
if (node) files.push(node);
}
const rank = (n: Node) => (n.kind === "file" ? (n.items.some((d) => d.severity === "error") ? 0 : 1) : 2);
return files.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
return files.sort((a, b) => Number(!a.error) - Number(!b.error) || a.path.localeCompare(b.path));
}
const diagNodes = new WeakMap<FileNode, Node[]>();
function diagChildren(n: FileNode): Node[] {
let children = diagNodes.get(n);
if (!children) {
children = n.items.map((d, i) => ({ kind: "diag", key: `${n.path}\u0000${i}`, path: n.path, d }));
diagNodes.set(n, children);
}
return children;
}
function open(path: string, d: Diagnostic, focus = true): Promise<void> {
@@ -200,19 +241,15 @@ export function ProblemsHeaderActions() {
/** Scope tabs in the tool window header: "File: name 2" / "Project Errors". */
export function ProblemsTabs() {
const map = useProblems((s) => s.map);
const tab = useProblemsView((s) => s.tab);
const setTab = useProblemsView((s) => s.setTab);
const current = useCurrentPath();
const fileCount = current
? countSeverities(filePaths(map, current).flatMap((path) => fileDiagnostics(map, path)))
: null;
const projectErrors = useMemo(() => {
let n = 0;
for (const sources of map.values())
for (const items of sources.values()) n += items.filter((d) => d.severity === "error").length;
return n;
}, [map]);
const fileCount = useProblems((s) => {
if (!current) return 0;
const c = countSeverities(filePaths(s.map, current).flatMap((path) => fileDiagnostics(s.map, path)));
return c.error + c.warning;
});
const projectErrors = useProblems((s) => s.counts.error);
return (
<Tabs
variant="compact"
@@ -231,10 +268,7 @@ export function ProblemsTabs() {
"File"
),
text: "File",
trailing:
fileCount && fileCount.error + fileCount.warning > 0 ? (
<span className={styles.tabCount}>{fileCount.error + fileCount.warning}</span>
) : undefined,
trailing: fileCount > 0 ? <span className={styles.tabCount}>{fileCount}</span> : undefined,
},
{
id: "project",
@@ -297,10 +331,7 @@ export function ProblemsView() {
);
const getChildren = useCallback(
(n: Node): Node[] | undefined =>
n.kind === "file"
? n.items.map((d, i) => ({ kind: "diag", key: `${n.path}\u0000${i}`, path: n.path, d }) as Node)
: undefined,
(n: Node): Node[] | undefined => (n.kind === "file" ? diagChildren(n) : undefined),
[],
);
+1 -6
View File
@@ -29,12 +29,7 @@ import { installWorkspaceEditUndo } from "./workspaceUndo";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
function useErrorBadge(): number | null {
return useProblems((s) => {
let n = 0;
for (const sources of s.map.values())
for (const items of sources.values()) for (const d of items) if (d.severity === "error") n++;
return n || null;
});
return useProblems((s) => s.counts.error || null);
}
export function activate(): () => void {
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { Diagnostic } from "@/bindings";
import { useProject } from "@/platform/project";
import {
applyDiagnosticsEvent,
clearProblems,
@@ -7,6 +8,7 @@ import {
currentProblemsPath,
fileDiagnostics,
filePaths,
installProblemsEvents,
mergeDiagnostics,
problemsReport,
profiledProblems,
@@ -151,3 +153,53 @@ describe("problemsReport", () => {
expect(problemsReport(mergeDiagnostics(new Map(), "/p/a", "x", [d(0, "info")]), "/p")).toBeNull();
});
});
describe("incremental bookkeeping", () => {
let seed = 7;
const random = (n: number) => (seed = (seed * 48271) % 2147483647) % n;
const SEVERITIES = ["error", "warning", "info", "hint"] as const;
const items = (): Diagnostic[] =>
Array.from({ length: random(5) }, () => ({
...d(random(3), SEVERITIES[random(4)]),
range: { start: { line: random(3), col: random(2) }, end: { line: 3, col: 0 } },
code: String(random(1000)),
}));
// The merge as it was before it was cached.
const fullMerge = (map: ReturnType<typeof useProblems.getState>["map"], path: string) =>
[...(map.get(path)?.values() ?? [])]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity),
);
it("keeps the project counts and each file's merged list equal to a full rescan", () => {
clearProblems();
useProject.setState({ settings: {} as never });
const off = installProblemsEvents();
try {
for (let step = 0; step < 400; step++) {
if (step === 150)
useProject.setState({
settings: { inspections: { default: { "lsp:eslint": { enabled: false } } } } as never,
});
if (step === 250)
useProject.setState({
settings: { inspections: { default: { "lsp:ra": { severity: "weakWarning" } } } } as never,
});
if (step === 300) clearProblems();
const path = `/p/${random(12)}.rs`;
applyDiagnosticsEvent(path, ["ra", "eslint"][random(2)]!, items());
const { map, counts } = useProblems.getState();
expect(counts).toEqual(projectCounts(map));
for (const p of map.keys()) expect(fileDiagnostics(map, p)).toEqual(fullMerge(map, p));
}
} finally {
off();
useProject.setState({ settings: {} as never });
clearProblems();
}
});
});
+37 -13
View File
@@ -49,18 +49,26 @@ export function mergeDiagnostics(
const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2, hint: 3 };
// A file's sources map is replaced whenever its diagnostics change, so it keys the merged list.
const merged = new WeakMap<FileDiagnostics, readonly Diagnostic[]>();
/** All diagnostics of a file across sources, ordered by position then severity. */
export function fileDiagnostics(map: ProblemsMap, path: string): Diagnostic[] {
export function fileDiagnostics(map: ProblemsMap, path: string): readonly Diagnostic[] {
const sources = map.get(path);
if (!sources) return [];
return [...sources.values()]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],
);
let items = merged.get(sources);
if (!items) {
items = [...sources.values()]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],
);
merged.set(sources, items);
}
return items;
}
/** The producer (inspection) that reported `d`, one of `path`'s problems in `map`. */
@@ -158,21 +166,34 @@ interface ProblemsState {
raw: ProblemsMap;
/** What the views show. */
map: ProblemsMap;
/** `projectCounts(map)`, kept up to date per event. */
counts: SeverityCounts;
}
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map() }));
const NO_COUNTS: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 };
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map(), counts: NO_COUNTS }));
function recount(counts: SeverityCounts, removed: readonly Diagnostic[], added: readonly Diagnostic[]) {
const c = { ...counts };
for (const d of removed) c[d.severity]--;
for (const d of added) c[d.severity]++;
return c;
}
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
useProblems.setState((s) => {
const raw = mergeDiagnostics(s.raw, path, source, items);
if (raw === s.raw) return s;
const map = mergeDiagnostics(s.map, path, source, applyProfile(inspectionProfile(), source, items));
return { raw, map };
if (map === s.map) return { raw };
const before = s.map.get(path)?.get(source) ?? [];
return { raw, map, counts: recount(s.counts, before, map.get(path)?.get(source) ?? []) };
});
}
export function clearProblems() {
useProblems.setState({ raw: new Map(), map: new Map() });
useProblems.setState({ raw: new Map(), map: new Map(), counts: NO_COUNTS });
}
export function installProblemsEvents(): () => void {
@@ -180,7 +201,10 @@ export function installProblemsEvents(): () => void {
// Typo, file references, SQL: inspections the editor runs itself.
const offLocal = onLocalDiagnostics(applyDiagnosticsEvent);
const offProfile = subscribeInspectionProfile(() =>
useProblems.setState((s) => ({ map: profiledProblems(s.raw, inspectionProfile()) })),
useProblems.setState((s) => {
const map = profiledProblems(s.raw, inspectionProfile());
return { map, counts: projectCounts(map) };
}),
);
return () => {
off();
@@ -0,0 +1,92 @@
/**
* Problems tool window under a diagnostics storm: a workspace of 2,000 files with 30,000
* diagnostics, then 200 single-file updates, each rendered by the mounted header tabs and list.
* One sample is the time for all 200 updates; prints each sample and the median.
* Skipped unless asked for:
*
* PROBLEMS_BENCH=1 pnpm vitest run src/features/code-insight/problemsStorm.bench.test.tsx --silent=false
*/
import { act, render } from "@testing-library/react";
import { describe, it } from "vitest";
import type { Diagnostic, Severity } from "@/bindings";
import { ProblemsTabs, ProblemsView, useProblemsView } from "./ProblemsView";
import { applyDiagnosticsEvent, clearProblems } from "./problemsStore";
const FILES = 2000;
const LSP_PER_FILE = 10;
const LINT_PER_FILE = 5;
const UPDATES = 200;
let seed = 1;
const random = () => (seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31;
const SEVERITIES: Severity[] = ["error", "warning", "warning", "info", "hint"];
function diagnostics(count: number, salt: number): Diagnostic[] {
return Array.from({ length: count }, (_, i) => {
const line = Math.floor(random() * 400);
const col = Math.floor(random() * 80);
return {
range: { start: { line, col }, end: { line, col: col + 4 } },
severity: SEVERITIES[(i + salt) % SEVERITIES.length]!,
message: `Problem ${Math.floor(random() * 500)} near symbol${salt}_${i}`,
source: null,
code: null,
} as Diagnostic;
});
}
const paths = Array.from({ length: FILES }, (_, i) => `/p/src/module${i % 40}/File${i}.ts`);
const initial = paths.map((path, i) => ({
path,
lsp: diagnostics(LSP_PER_FILE, i),
lint: diagnostics(LINT_PER_FILE, i + 1),
}));
const updates = Array.from({ length: UPDATES }, (_, k) => ({
path: paths[Math.floor(random() * FILES)]!,
items: diagnostics(LSP_PER_FILE, k + 7),
}));
function loadWorkspace() {
clearProblems();
for (const f of initial) {
applyDiagnosticsEvent(f.path, "lsp", f.lsp);
applyDiagnosticsEvent(f.path, "eslint", f.lint);
}
}
function storm(tab: "file" | "project") {
loadWorkspace();
useProblemsView.setState({ tab });
const view = render(
<>
<ProblemsTabs />
<ProblemsView />
</>,
);
// Only the updates are timed, not loading the workspace or the first render.
const start = performance.now();
for (const u of updates) act(() => applyDiagnosticsEvent(u.path, "lsp", u.items));
const ms = performance.now() - start;
view.unmount();
return ms;
}
const RUNS = 7;
function measure(tab: "file" | "project") {
storm(tab); // warm-up
const samples = Array.from({ length: RUNS }, () => storm(tab)).sort((a, b) => a - b);
const median = samples[RUNS >> 1]!;
console.log(
`${tab} tab: median ${median.toFixed(1)} ms per ${UPDATES} updates (${(median / UPDATES).toFixed(2)} ms/update); ` +
`samples ${samples.map((s) => s.toFixed(1)).join(", ")}`,
);
}
describe.skipIf(!process.env.PROBLEMS_BENCH)(
`Problems: ${FILES} files, ${FILES * (LSP_PER_FILE + LINT_PER_FILE)} diagnostics, ${UPDATES} single-file updates`,
() => {
it("Project Errors tab", () => measure("project"), 600_000);
it("File tab", () => measure("file"), 600_000);
},
);
+82 -1
View File
@@ -2,7 +2,8 @@ import { describe, expect, it } from "vitest";
import { groupUsages, trimPreview, usageCount } from "./usages";
import { serversSummary, type ServerEntry } from "./servers";
import { buildProblemNodes } from "./ProblemsView";
import { mergeDiagnostics, sortProblems } from "./problemsStore";
import type { Diagnostic } from "@/bindings";
import { mergeDiagnostics, sortProblems, type ProblemOrder, type ProblemsMap } from "./problemsStore";
import { toggleExcludedUsages } from "./UsagesView";
import { childId, directionLabel } from "./hierarchy";
@@ -66,6 +67,86 @@ describe("buildProblemNodes", () => {
expect(errorsOnly.map((n) => n.key)).toEqual(["/b"]);
expect(errorsOnly[0]!.kind === "file" && errorsOnly[0]!.items.length).toBe(1);
});
it("matches a full rebuild across single-file updates, filters and sort orders", () => {
let seed = 11;
const random = (n: number) => (seed = (seed * 48271) % 2147483647) % n;
const SEVERITIES = ["error", "warning", "info", "hint"] as const;
const MESSAGES = ["alpha", "Alpha", "beta 2", "beta 10"];
const items = (): Diagnostic[] =>
Array.from({ length: random(6) }, () => ({
range: { start: { line: random(3), col: random(2) }, end: { line: 3, col: 0 } },
severity: SEVERITIES[random(4)]!,
message: MESSAGES[random(4)]!,
source: null,
code: String(random(1000)),
}));
// buildProblemNodes as it was before per-file caching.
const rebuild = (map: ProblemsMap, paths: string[], show: Record<string, boolean>, order: ProblemOrder) => {
const files = paths.flatMap((path) => {
const all = [...(map.get(path)?.values() ?? [])]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity),
);
const shown = sortProblems(
all.filter((d) => show[d.severity === "hint" ? "info" : d.severity]),
order,
);
return shown.length ? [{ path, items: shown }] : [];
});
const rank = (f: { items: Diagnostic[] }) => (f.items.some((d) => d.severity === "error") ? 0 : 1);
return files.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
};
// Neighbours differ in one flag, so a cache that ignored any of them would serve stale nodes.
const shows = ["111", "101", "100", "000", "010", "011"].map(([e, w, i]) => ({
error: e === "1",
warning: w === "1",
info: i === "1",
}));
const orders = ["10", "00", "01", "11"].map(([s, n]) => ({ bySeverity: s === "1", byName: n === "1" }));
let map: ProblemsMap = new Map();
for (let step = 0; step < 300; step++) {
const path = `/p/${["b", "A", "a", "c10", "c2"][random(5)]}/${random(4)}.ts`;
map = mergeDiagnostics(map, path, ["lsp", "eslint"][random(2)]!, items());
const show = shows[Math.floor(step / 20) % shows.length]!;
const order = orders[Math.floor(step / 35) % orders.length]!;
const paths = [...map.keys()];
const nodes = buildProblemNodes(map, paths, { ...show }, { ...order });
expect(nodes.map((n) => ({ path: n.path, items: n.items }))).toEqual(rebuild(map, paths, show, order));
const some = paths.filter((_, i) => i % 3 === 0);
expect(buildProblemNodes(map, some, show, order).map((n) => ({ path: n.path, items: n.items }))).toEqual(
rebuild(map, some, show, order),
);
}
});
it("reuses the nodes of files an update didn't touch", () => {
const diag = (line: number) => ({
range: { start: { line, col: 0 }, end: { line, col: 1 } },
severity: "error" as const,
message: "x",
source: null,
code: null,
});
const show = { error: true, warning: true, info: true };
let map = mergeDiagnostics(new Map(), "/a", "s", [diag(1)]);
map = mergeDiagnostics(map, "/b", "s", [diag(2)]);
const [a, b] = buildProblemNodes(map, ["/a", "/b"], show);
map = mergeDiagnostics(map, "/b", "s", [diag(3)]);
const [a2, b2] = buildProblemNodes(map, ["/a", "/b"], show);
expect(a2).toBe(a);
expect(b2).not.toBe(b);
const shared = map.get("/a")!;
const twice = new Map([
["/a", shared],
["/c", shared],
]);
expect(buildProblemNodes(twice, ["/a", "/c"], show).map((n) => n.path)).toEqual(["/a", "/c"]);
});
});
describe("hierarchy", () => {