Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off globalConsole:off - a synchronous wrapper around one vitest project.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7const HELP = `Usage:
8 node scripts/render-metrics.ts run [--out <file>] [--runs <n>]
9 node scripts/render-metrics.ts compare <before.json> <after.json> [--top <n>]
10
11run Runs the web render scenarios (apps/web/test/renderScenarios.renders.tsx,
12 vitest project "renders") on this checkout and writes one JSON object of
13 { scenario: { commits, renders, components } }. With --runs above 1 (default 3)
14 it fails unless every run produced identical counts.
15compare Prints a markdown table of commit and render deltas per scenario, plus the
16 components whose counts changed most (default top 10).
17
18commits are React commits that rendered at least one component (null where frame
19timing splits them); renders are function and class component renders, counted from the
20fibers React worked on. Every scenario waits for the tree to go quiet before and after
21its counted window, so layout follow-ups are included.
22
23Comparing two refs needs both checkouts, since the scenarios run each tree's code:
24 node scripts/render-metrics.ts run --out ../main-renders.json # on main
25 node scripts/render-metrics.ts run --out ../branch-renders.json # on the branch
26 node scripts/render-metrics.ts compare ../main-renders.json ../branch-renders.json
27A second checkout comes from \`git worktree add ../<name> main\`; copy the harness files
28in if that tree predates them.`;
29
30export interface ScenarioReport {
31 /** null where a scenario's commit count depends on frame timing. */
32 readonly commits: number | null;
33 readonly renders: number;
34 readonly components: Readonly<Record<string, number>>;
35}
36export type RenderMetrics = Readonly<Record<string, ScenarioReport>>;
37
38const root = NodePath.resolve(import.meta.dirname, "..");
39
40export function runOnce(): RenderMetrics {
41 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-renders-"));
42 try {
43 const result = NodeChildProcess.spawnSync("vp", ["test", "run", "--project", "renders"], {
44 cwd: NodePath.join(root, "apps/web"),
45 env: { ...process.env, T3CODE_RENDER_REPORT_DIR: directory },
46 stdio: ["ignore", "inherit", "inherit"],
47 });
48 if (result.status !== 0) throw new Error(`render scenarios failed (exit ${result.status})`);
49 const files = NodeFS.readdirSync(directory)
50 .filter((file) => file.endsWith(".json"))
51 .toSorted();
52 return Object.fromEntries(
53 files.map((file) => [
54 file.replace(/\.json$/, ""),
55 JSON.parse(NodeFS.readFileSync(NodePath.join(directory, file), "utf8")) as ScenarioReport,
56 ]),
57 );
58 } finally {
59 NodeFS.rmSync(directory, { recursive: true, force: true });
60 }
61}
62
63/** Scenarios whose counts differ between runs, by name. */
64export function nondeterministic(runs: ReadonlyArray<RenderMetrics>): string[] {
65 const [first, ...rest] = runs;
66 if (!first) return [];
67 return Object.keys(first).filter((scenario) =>
68 rest.some((run) => JSON.stringify(run[scenario]) !== JSON.stringify(first[scenario])),
69 );
70}
71
72const signed = (value: number) => (value > 0 ? `+${value}` : `${value}`);
73const change = (before: number | null, after: number | null) =>
74 before === null || after === null
75 ? "n/a"
76 : before === after
77 ? `${after}`
78 : `${before} → ${after} (${signed(after - before)}${before ? `, ${signed(Math.round(((after - before) / before) * 100))}%` : ""})`;
79
80export function renderComparison(before: RenderMetrics, after: RenderMetrics, top = 10): string {
81 const scenarios = [...new Set([...Object.keys(before), ...Object.keys(after)])].toSorted();
82 const lines = [
83 "### Render scenarios",
84 "",
85 "| scenario | commits | renders |",
86 "| :-- | --: | --: |",
87 ];
88 const empty: ScenarioReport = { commits: 0, renders: 0, components: {} };
89 for (const scenario of scenarios) {
90 const a = before[scenario] ?? empty;
91 const b = after[scenario] ?? empty;
92 lines.push(
93 `| ${scenario} | ${change(a.commits, b.commits)} | ${change(a.renders, b.renders)} |`,
94 );
95 }
96 for (const scenario of scenarios) {
97 const a = before[scenario]?.components ?? {};
98 const b = after[scenario]?.components ?? {};
99 const moved = [...new Set([...Object.keys(a), ...Object.keys(b)])]
100 .map((name) => [name, a[name] ?? 0, b[name] ?? 0] as const)
101 .filter(([, x, y]) => x !== y)
102 .sort(([n, x, y], [m, p, q]) => Math.abs(q - p) - Math.abs(y - x) || n.localeCompare(m))
103 .slice(0, top);
104 if (moved.length === 0) continue;
105 lines.push("", `<details><summary>${scenario}: components that changed most</summary>`, "");
106 lines.push("| component | renders |", "| :-- | --: |");
107 for (const [name, x, y] of moved) lines.push(`| \`${name}\` | ${change(x, y)} |`);
108 lines.push("", "</details>");
109 }
110 return lines.join("\n");
111}
112
113function option(args: ReadonlyArray<string>, name: string): string | undefined {
114 const index = args.indexOf(name);
115 return index === -1 ? undefined : args[index + 1];
116}
117
118if (import.meta.main) {
119 const [command, ...args] = process.argv.slice(2);
120 if (command === "run") {
121 const runs = Number(option(args, "--runs") ?? 3);
122 const results = Array.from({ length: runs }, runOnce);
123 const unstable = nondeterministic(results);
124 if (unstable.length) {
125 for (const scenario of unstable) {
126 const counts = results.map((run) => `${run[scenario]?.commits}/${run[scenario]?.renders}`);
127 console.error(`${scenario} differed between runs (commits/renders): ${counts.join(", ")}`);
128 const first = results[0]?.[scenario]?.components ?? {};
129 for (const [index, run] of results.entries()) {
130 const other = run[scenario]?.components ?? {};
131 const names = [...new Set([...Object.keys(first), ...Object.keys(other)])];
132 const moved = names.filter((name) => first[name] !== other[name]);
133 if (moved.length) {
134 const detail = moved.map((name) => `${name} ${first[name] ?? 0}→${other[name] ?? 0}`);
135 console.error(` run ${index + 1} vs run 1: ${detail.join(", ")}`);
136 }
137 }
138 }
139 process.exitCode = 1;
140 } else {
141 const json = JSON.stringify(results[0], null, 2);
142 const out = option(args, "--out");
143 if (out) NodeFS.writeFileSync(out, json + "\n");
144 else console.log(json);
145 console.error(`${runs} run(s) produced identical counts.`);
146 }
147 } else if (command === "compare" && args[0] && args[1]) {
148 const read = (path: string) => JSON.parse(NodeFS.readFileSync(path, "utf8")) as RenderMetrics;
149 console.log(
150 renderComparison(read(args[0]), read(args[1]), Number(option(args, "--top") ?? 10)),
151 );
152 } else {
153 console.log(HELP);
154 if (command !== "--help" && command !== "-h" && command !== undefined) process.exitCode = 1;
155 }
156}