Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9539: test(perf): one-command core-path comparison; digest the whole dataset generator (#10927)
Bohan Jiang9776231579fb
diff --git a/e2e/perf/README.md b/e2e/perf/README.mdindex 9c91bb07a0..f27eedc48f 100644--- a/e2e/perf/README.md+++ b/e2e/perf/README.md@@ -189,10 +189,11 @@ fails rather than reporting a fast time.The dataset (`lib/core-dataset.ts`) takes its sizes from productionaggregates: ~1,000 issues, ~1,800 notifications of which ~950 unread, and the-issues above. Text, structure and image bytes are deterministic; the report-carries a digest, and `scripts/perf-core-report.mjs` refuses to compare-reports from different datasets. The first run seeds a `perf-core` workspace-(about a minute) and later runs reuse it.+issues above. Text, structure and image bytes are deterministic. The report+carries a digest of the generator's source and the image bytes, so any edit to+`lib/core-dataset.ts` gives a new digest, and both comparison scripts refuse+to compare reports from different datasets. The first run seeds a `perf-core`+workspace (about a minute); later runs reuse it until the digest changes.```bashmake up C=api ARGS="--ephemeral"@@ -211,8 +212,20 @@ absorbs work that a mid-range laptop shows as stalls, and a fix that onlyhelps there (#10767's left-nav toggle) is invisible unthrottled. Sidebartoggles also report main-thread work per toggle, the most stable of thenumbers.-To compare refs, build each ref in its own worktree and run the spec from one-checkout against each server in turn, never two at once.+To compare two refs, run `perf-compare.mjs` inside the API's environment. It+builds each ref in its own worktree, serves it against the local API, runs the+spec from this checkout, then stops it before the next side starts:++```bash+make up C=api ARGS="--ephemeral"+make env-exec ARGS="-- node scripts/perf-compare.mjs --scenario core-paths --base origin/main --head HEAD --out perf-report"+```++`--scenario core-issue` or `core-inbox` measures one path. The `PERF_*`+settings above pass through. It writes `base.json`, `head.json` and+`comparison.md`, whose table is the one `perf-core-report.mjs` prints; attach+it to the PR. The **UI performance report** workflow does not offer these+scenarios, because a GitHub runner has no local API to run them against.## Inbox jumpdiff --git a/e2e/perf/lib/core-dataset.ts b/e2e/perf/lib/core-dataset.tsindex 864962a963..5032758ed5 100644--- a/e2e/perf/lib/core-dataset.ts+++ b/e2e/perf/lib/core-dataset.ts@@ -8,9 +8,14 @@* people actually report as slow (MUL-9538 and friends); `p99` is the 99th* percentile issue.*- * Everything is synthetic and deterministic: the same DATASET_VERSION gives- * the same text, structure and image bytes, and the manifest's digest proves- * it, so two refs measured against one seeded database see identical data.+ * Everything is synthetic and deterministic: the same generator gives the same+ * text, structure and image bytes, so two refs measured against one seeded+ * database see identical data. The digest covers this file's own source and+ * the image bytes, so any change to how the data is generated (run output+ * length, thread shape, where images land, the background Inbox) gives a new+ * digest, and reports from before and after it are never compared as if they+ * measured the same work. Bump DATASET_VERSION as well when the data itself+ * changes, so the reports say so in words.* Rows go straight into the isolated local database (no agent ever runs);* images go through the real upload endpoint so their URLs, dimensions and* bytes are what the app normally serves.@@ -19,6 +24,7 @@ import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";import pg from "pg";import { TestApiClient } from "../../fixtures";import { mediaBytes } from "../fixtures/image-heavy-thread";@@ -137,13 +143,18 @@ function description(title: string): string {].join("\n\n");}-/** The structure and text of the dataset; its hash identifies what was measured. */+/**+ * Identifies what was measured. Every size, text and seeding rule lives in+ * this file, so hashing its source covers them all, including the ones no list+ * of parameters would remember to name. An edit that changes nothing (a+ * comment) also changes the digest; the cost is one reseed, about a minute.+ * Not covered: the shared helpers seeding goes through (`TestApiClient`, the+ * upload endpoint) and server-side defaults; the report's counts show those.+ */export function datasetDigest(): string {- const spec = datasetSpec();- const rand = rng(9539);- const bodies = spec.issues.map((issue) => Array.from({ length: issue.comments }, (_, i) => commentBody(rand, i)));return createHash("sha256")- .update(JSON.stringify({ version: DATASET_VERSION, spec, bodies }))+ .update(DATASET_VERSION)+ .update(readFileSync(fileURLToPath(import.meta.url))).update(mediaBytes().original).digest("hex").slice(0, 16);diff --git a/scripts/perf-compare.mjs b/scripts/perf-compare.mjsindex 314f6ef259..ef241506dd 100755--- a/scripts/perf-compare.mjs+++ b/scripts/perf-compare.mjs@@ -17,12 +17,23 @@* `--scenario` picks the measurement: `typing-under-live-runs` (default) or* `image-thread` (MUL-8182). Both write the same report path, so one run* measures exactly one of them.+ *+ * `core-paths`, `core-issue` and `core-inbox` (MUL-9539) run the core-path+ * benchmark, which needs a real local API instead of synthetic HTTP. Run the+ * script inside the API's environment so both builds talk to it and share+ * its seeded dataset:+ *+ * make env-exec ARGS="-- node scripts/perf-compare.mjs --scenario core-paths --base <ref> --head <ref>"+ *+ * The spec takes its own rounds from PERF_REPEATS / PERF_WARMUP, and every+ * other PERF_* setting (PERF_CPU_THROTTLE, PERF_INBOX_ROWS, …) passes through.*/import { execFileSync, spawn } from "node:child_process";import { mkdtempSync, mkdirSync, rmSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { connect, createServer } from "node:net";+import { renderCoreReport } from "./perf-core-report.mjs";const repoRoot = execFileSync("git", ["rev-parse", "--show-toplevel"]).toString().trim();const args = process.argv.slice(2);@@ -53,6 +64,11 @@ const SCENARIOS = {["js_heap_mb", "JS heap (MB)"],],},+ ...Object.fromEntries([+ ["core-paths", "Core paths: big issues and Inbox switching (MUL-9539)"],+ ["core-issue", "Core paths: big issues (MUL-9539)"],+ ["core-inbox", "Core paths: Inbox switching (MUL-9539)"],+ ].map(([name, title]) => [name, { title, spec: "core-paths.spec.ts", core: true }])),};const scenarioName = flag("scenario", "typing-under-live-runs");const scenario = SCENARIOS[scenarioName];@@ -63,6 +79,31 @@ if (!baseRef || !scenario) {process.exit(2);}+/**+ * The local API a core scenario measures against: the one whose environment+ * `make env-exec` exported. Both builds use it, and the dataset it holds is+ * seeded once and reused, so the two sides see the same data.+ */+let apiUrl;+if (scenario.core) {+ const missing = ["MULTICA_DEV_PROFILE", "DATABASE_URL", "PORT"].filter((name) => !process.env[name]);+ if (missing.length > 0) {+ console.error(+ `--scenario ${scenarioName} needs a local API: start one with \`make up C=api ARGS="--ephemeral"\`, then run this ` ++ `script through \`make env-exec ARGS="-- node scripts/perf-compare.mjs ..."\` (missing ${missing.join(", ")}).`,+ );+ process.exit(2);+ }+ apiUrl = `http://localhost:${process.env.PORT}`;+ try {+ const response = await fetch(`${apiUrl}/health`);+ if (!response.ok) throw new Error(`status ${response.status}`);+ } catch (error) {+ console.error(`the local API at ${apiUrl} is not healthy (${error instanceof Error ? error.message : error}); is \`make up C=api\` running?`);+ process.exit(2);+ }+}+const run = (cmd, cmdArgs, opts = {}) =>execFileSync(cmd, cmdArgs, { stdio: "inherit", ...opts });@@ -227,10 +268,17 @@ async function measure(ref, label) {// two real builds to avoid the ambiguity costs minutes on every local run,// and buys nothing on CI, where the runner is always cold anyway.const buildStart = Date.now();+ // A core scenario's app calls the API on its own origin, which the server+ // proxies to REMOTE_API_URL, as in production. `make env-exec` exports the+ // API environment's direct URLs; left in place at build or at runtime they+ // send the browser cross-origin to the API, whose origin check refuses+ // this server's random port, and the issue history never renders.+ const sameOrigin = scenario.core ? { NEXT_PUBLIC_API_URL: "", NEXT_PUBLIC_WS_URL: "" } : {};+ const buildEnv = { ...process.env, ...sameOrigin };const buildLog = execFileSync("pnpm",["exec", "turbo", "build", "--filter=@multica/web", `--cache-dir=${buildCache}`],- { cwd: checkout, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] },+ { cwd: checkout, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], env: buildEnv },);process.stdout.write(buildLog);const buildS = seconds(buildStart);@@ -240,7 +288,7 @@ async function measure(ref, label) {const startStart = Date.now();server = spawn("pnpm", ["--filter", "@multica/web", "start"], {cwd: checkout,- env: { ...process.env, PORT: String(port), REMOTE_API_URL: "http://127.0.0.1:1" },+ env: { ...process.env, ...sameOrigin, PORT: String(port), REMOTE_API_URL: apiUrl ?? "http://127.0.0.1:1" },stdio: "ignore",detached: true,});@@ -257,14 +305,20 @@ async function measure(ref, label) {const measureStart = Date.now();let scenarioExit = 0;try {+ // The core spec runs its own warmup and rounds, each in a fresh browser+ // context, and writes one report covering all of them (PERF_REPEATS).+ // --repeat-each on top would multiply the rounds, not set them.+ const repeat = scenario.core ? [] : [`--repeat-each=${process.env.PERF_REPEATS ?? "1"}`];run("pnpm", ["exec", "playwright", "test", "--config=playwright.perf.config.ts",- `--repeat-each=${process.env.PERF_REPEATS ?? "1"}`, ...(scenario.spec ? [scenario.spec] : [])], {+ ...repeat, ...(scenario.spec ? [scenario.spec] : [])], {cwd: repoRoot,env: {...process.env,PLAYWRIGHT_BASE_URL: `http://127.0.0.1:${port}`,PERF_REPORT_PATH: reportPath,PERF_SCENARIO: scenarioName,+ PERF_REF: sha.slice(0, 10),+ PERF_LABEL: label,},});} catch (error) {@@ -278,6 +332,12 @@ async function measure(ref, label) {} catch {report = { status: "invalid", invalid: ["the scenario produced no readable report"] };}+ // The core spec's report has no verdict of its own: a step whose content+ // never appears fails the test, so the process exit is the verdict.+ if (scenario.core && !report.status) {+ report.status = scenarioExit === 0 ? "ok" : "invalid";+ report.invalid = scenarioExit === 0 ? [] : [`the scenario process exited ${scenarioExit}`];+ }// The scenario process has the last word. A report that says `ok` from a// run whose process then failed is not a sample: whatever failed after the// numbers were written is exactly what nobody has looked at.@@ -311,6 +371,7 @@ const METRICS = [];function markdown(base, head) {+ if (scenario.core) return coreMarkdown(base, head);const usable = base.status === "ok" && head.status === "ok";const rows = [...METRICS, ...scenario.metrics].map(([key, label]) => {const a = base[key];@@ -343,6 +404,35 @@ function markdown(base, head) {].join("\n");}+const timingLine = (r) =>+ `install ${r.timings_s.install}s · build ${r.timings_s.build}s${r.build_cached ? " (restored from cache — not a real build)" : ""} · start ${r.timings_s.start}s · measure ${r.timings_s.measure}s`;++/** The core-path table from scripts/perf-core-report.mjs, one column per ref. */+function coreMarkdown(base, head) {+ const usable = base.status === "ok" && head.status === "ok";+ const sideLine = (name, r) =>+ `- ${name} \`${r.ref}\` (${r.sha.slice(0, 9)}) — ${r.status}${r.invalid?.length ? `: ${r.invalid.join("; ")}` : ""}`;+ let table;+ try {+ table = renderCoreReport([{ label: "base", report: base }, { label: "head", report: head }]);+ } catch (error) {+ table = `**Not comparable:** ${error instanceof Error ? error.message : error}`;+ }+ return [+ `## ${scenario.title}`,+ "",+ usable+ ? "Each side measured in turn on this machine against the same local API and dataset. This is a report, not a merge gate — read small differences as noise until a second run agrees."+ : `**Not a usable comparison.** base: \`${base.status}\`, head: \`${head.status}\`.`,+ table,+ "",+ sideLine("base", base),+ sideLine("head", head),+ `- base timings: ${timingLine(base)}`,+ `- head timings: ${timingLine(head)}`,+ ].join("\n");+}+mkdirSync(outDir, { recursive: true });// The files this script writes, cleared up front: a comparison that aborts// early must not leave the previous run's summary looking like its own.@@ -367,6 +457,8 @@ try {// The comparison itself only fails when a sample is not usable. A slower// head is information for the reviewer, not a failure of this script.exitCode = base.status === "ok" && head.status === "ok" ? 0 : 1;+ // Core reports from two datasets do not describe the same work.+ if (scenario.core && base.dataset?.digest !== head.dataset?.digest) exitCode = 1;} catch (error) {const message = error instanceof Error ? error.message : String(error);console.error(`\ncomparison aborted: ${message}`);diff --git a/scripts/perf-compare.test.sh b/scripts/perf-compare.test.shindex 4b4904c479..fa5aa3be8e 100755--- a/scripts/perf-compare.test.sh+++ b/scripts/perf-compare.test.sh@@ -18,6 +18,7 @@ work="$(mktemp -d)"repo="$work/repo"bin="$work/bin"server_log="$work/servers.jsonl"+call_log="$work/calls.jsonl"mkdir -p "$repo" "$bin" "$work/tmp"touch "$server_log"@@ -31,8 +32,10 @@ kill_recorded() {}' "$server_log" || true}+api_pid=""cleanup() {kill_recorded+ [ -z "$api_pid" ] || kill "$api_pid" 2>/dev/null || truerm -rf "$work"}trap cleanup EXIT@@ -53,10 +56,19 @@ const args = process.argv.slice(2);const record = (pid) =>appendFileSync(process.env.PERF_TEST_SERVER_LOG, `${JSON.stringify({ pid })}\n`);+// What each step saw, for the core-scenario cases to check.+const note = (step, extra = {}) => process.env.PERF_TEST_CALL_LOG &&+ appendFileSync(process.env.PERF_TEST_CALL_LOG, `${JSON.stringify({ step, args, ...extra })}\n`);+if (args[0] === "install") process.exit(0);-if (args[0] === "exec" && args[1] === "turbo") { console.log("fake build"); process.exit(0); }+if (args[0] === "exec" && args[1] === "turbo") {+ note("build", { api: process.env.NEXT_PUBLIC_API_URL ?? null, ws: process.env.NEXT_PUBLIC_WS_URL ?? null });+ console.log("fake build");+ process.exit(0);+}if (args[0] === "--filter" && args[2] === "start") {+ note("start", { remote: process.env.REMOTE_API_URL, api: process.env.NEXT_PUBLIC_API_URL ?? null, ws: process.env.NEXT_PUBLIC_WS_URL ?? null });const port = Number(process.env.PORT);if (process.env.PERF_SERVER === "stubborn") {// A child in the wrapper's process group that ignores SIGTERM and stops@@ -79,7 +91,16 @@ if (args[0] === "--filter" && args[2] === "start") {}if (args[0] === "exec" && args[1] === "playwright") {- const report = {+ note("playwright", { scenario: process.env.PERF_SCENARIO, ref: process.env.PERF_REF, label: process.env.PERF_LABEL });+ const core = (process.env.PERF_SCENARIO ?? "").startsWith("core-");+ // The core spec's report carries no status of its own.+ const report = core ? {+ ref: process.env.PERF_REF, label: process.env.PERF_LABEL,+ dataset: { version: "core-test", digest: process.env.PERF_TEST_DIGEST?.split(",")[process.env.PERF_LABEL === "base" ? 0 : 1] ?? "same", counts: { issues: 1 } },+ environment: { browser: "test", viewport: "1440x900", cpu_throttle: 1, cpu: "test", cores: 1, repeats: 1, inbox_rows: "20", inbox_until: "comment" },+ summary: { issue: { large: { open_content_ms: 841 } }, inbox: {} },+ samples: { issue: [], inbox: [] },+ } : {status: "ok", invalid: [], typing_elapsed_ms: 123,fixture: { version: "test", sha256: "fresh", bytes: 0 },};@@ -106,9 +127,10 @@ run_case() {fi: >"$server_log"set +e+ : >"$call_log"(cd "$repo" && PATH="$bin:$PATH" TMPDIR="$work/tmp" PERF_STOP_GRACE_MS=300 \- PERF_PLAYWRIGHT="$2" PERF_SERVER="$3" PERF_TEST_SERVER_LOG="$server_log" \- node "$compare" --base "${4:-HEAD}" --head HEAD --out "$out") >"$work/out.log" 2>&1+ PERF_PLAYWRIGHT="$2" PERF_SERVER="$3" PERF_TEST_SERVER_LOG="$server_log" PERF_TEST_CALL_LOG="$call_log" \+ node "$compare" --base "${4:-HEAD}" --head HEAD --out "$out" ${SCENARIO:+--scenario "$SCENARIO"}) >"$work/out.log" 2>&1code=$?set -ecomparison="$out/comparison.json"@@ -159,4 +181,66 @@ expect_exit 1[ ! -f "$work/out-unknown-ref/comparison.md" ] || fail "an aborted run left the previous summary in place"grep -q "comparison aborted\|error" "$comparison" || fail "the aborted run does not record why"+# Core scenarios (MUL-9539) run against a real local API instead of synthetic+# HTTP. Outside `make env-exec` there is none, and the script says so up front.+SCENARIO=core-paths+case=core-without-api-env+set +e+(cd "$repo" && PATH="$bin:$PATH" env -u MULTICA_DEV_PROFILE -u DATABASE_URL -u PORT \+ node "$compare" --base HEAD --head HEAD --out "$work/out-core-no-env" --scenario core-paths) >"$work/out.log" 2>&1+code=$?+set -e+expect_exit 2+grep -q "make env-exec" "$work/out.log" || fail "does not say how to provide the API environment"+[ "$(git -C "$repo" worktree list | wc -l | tr -d ' ')" = 1 ] || fail "built something without an API"++# A stand-in for the local API: only /health is ever asked for.+api_port="$(node -e 'const s = require("net").createServer().listen(0, "127.0.0.1", () => { console.log(s.address().port); s.close(); })')"+node -e 'require("http").createServer((q, r) => { r.statusCode = q.url === "/health" ? 200 : 404; r.end("ok"); }).listen(Number(process.argv[1]), "127.0.0.1")' "$api_port" &+api_pid=$!+for _ in $(seq 50); do curl -sf "http://127.0.0.1:$api_port/health" >/dev/null 2>&1 && break; sleep 0.1; done+# `make env-exec` also exports the API's direct URLs; the core builds must not use them.+export MULTICA_DEV_PROFILE=dev-test DATABASE_URL=postgres://localhost/perf_test PORT="$api_port"+export NEXT_PUBLIC_API_URL="http://localhost:$api_port" NEXT_PUBLIC_WS_URL="ws://localhost:$api_port/ws"++run_case core-success ok normal+expect_exit 0+expect_status ok+calls() { node -e '+ const fs = require("fs");+ const rows = fs.readFileSync(process.argv[1], "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));+ console.log(eval(process.argv[2]));' "$call_log" "$1"; }+[ "$(calls 'rows.filter((r) => r.step === "build" || r.step === "start").every((r) => r.api === "" && r.ws === "")')" = true ] \+ || fail "builds or servers did not call the API on their own origin"+[ "$(calls 'rows.filter((r) => r.step === "start").every((r) => r.remote === "http://localhost:'"$api_port"'")')" = true ] \+ || fail "servers were not pointed at the local API"+[ "$(calls 'rows.filter((r) => r.step === "playwright").every((r) => !r.args.some((a) => a.startsWith("--repeat-each")) && r.args.includes("core-paths.spec.ts") && r.scenario === "core-paths")')" = true ] \+ || fail "the core spec was not run once, with its own rounds"+[ "$(calls 'rows.filter((r) => r.step === "playwright").map((r) => r.label + ":" + (r.ref ?? "").length).join(",")')" = "base:10,head:10" ] \+ || fail "the reports were not labelled with their side and ref"+md="$work/out-core-success/comparison.md"+grep -q "Open a big issue: \`large\`" "$md" || fail "comparison.md lacks the core-path table"+grep -q "| Open → first comments visible (ms) | 841 | 841 |" "$md" || fail "comparison.md lacks the measured numbers"++run_case core-spec-failed fail-after-report normal+expect_exit 1+expect_status invalid+grep -q "process exited" "$comparison" || fail "the invalid verdict does not say the process failed"++PERF_TEST_DIGEST=one,two run_case core-different-datasets ok normal+expect_exit 1+grep -q "different datasets" "$work/out-core-different-datasets/comparison.md" || fail "different datasets were compared"++kill "$api_pid" 2>/dev/null || true+wait "$api_pid" 2>/dev/null || true+api_pid=""+case=core-api-down+set +e+(cd "$repo" && PATH="$bin:$PATH" node "$compare" --base HEAD --head HEAD --out "$work/out-core-api-down" --scenario core-paths) >"$work/out.log" 2>&1+code=$?+set -e+expect_exit 2+grep -q "not healthy" "$work/out.log" || fail "an unreachable API was not reported"+unset SCENARIO MULTICA_DEV_PROFILE DATABASE_URL PORT NEXT_PUBLIC_API_URL NEXT_PUBLIC_WS_URL+echo "perf-compare: all lifecycle and reporting cases passed"diff --git a/scripts/perf-core-report.mjs b/scripts/perf-core-report.mjsindex 1f59960584..e6b36d3b93 100644--- a/scripts/perf-core-report.mjs+++ b/scripts/perf-core-report.mjs@@ -6,25 +6,12 @@* node scripts/perf-core-report.mjs before=perf/a.json after=perf/b.json** Reports measured against different datasets are refused: their numbers do- * not describe the same work.+ * not describe the same work. `scripts/perf-compare.mjs --scenario core-paths`+ * builds and measures two refs itself and renders its summary with this module.*/import { readFileSync } from "node:fs";--const inputs = process.argv.slice(2).map((arg) => {- const at = arg.indexOf("=");- const label = at > 0 ? arg.slice(0, at) : arg;- const path = at > 0 ? arg.slice(at + 1) : arg;- return { label, report: JSON.parse(readFileSync(path, "utf8")) };-});-if (inputs.length === 0) {- console.error("usage: node scripts/perf-core-report.mjs <label>=<report.json> [...]");- process.exit(2);-}-const digests = new Set(inputs.map((i) => i.report.dataset?.digest));-if (digests.size > 1) {- console.error(`reports use different datasets: ${[...digests].join(", ")}`);- process.exit(1);-}+import { resolve } from "node:path";+import { fileURLToPath } from "node:url";const ISSUE_ROWS = [["open_content_ms", "Open → first comments visible (ms)"],@@ -50,37 +37,76 @@ const INBOX_ROWS = [["freezes", "Freezes >200ms (all switches)"],];-const fmt = (v) => (typeof v === "number" ? (Number.isInteger(v) ? String(v) : v.toFixed(1)) : "—");-const header = `| | ${inputs.map((i) => i.label).join(" | ")} |\n|---|${inputs.map(() => "---:").join("|")}|`;-const lines = [];+export class DatasetMismatchError extends Error {}-const issueKeys = [...new Set(inputs.flatMap((i) => Object.keys(i.report.summary?.issue ?? {})))];-for (const key of issueKeys) {- lines.push(`\n**Open a big issue: \`${key}\`** (median of samples)\n`, header);- for (const [field, name] of ISSUE_ROWS) {- lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary.issue[key]?.[field])).join(" | ")} |`);+/**+ * Renders reports side by side. Each input is `{ label, report }`; throws+ * DatasetMismatchError when the reports were measured on different datasets.+ */+export function renderCoreReport(inputs) {+ const digests = new Set(inputs.map((i) => i.report.dataset?.digest));+ if (digests.size > 1) {+ throw new DatasetMismatchError(`reports use different datasets: ${[...digests].join(", ")}`);}-}-for (const phase of ["first-visit", "revisit"]) {- if (!inputs.some((i) => i.report.summary?.inbox?.[phase])) continue;- lines.push(`\n**Inbox switching: ${phase}** (all switches across samples)\n`, header);- for (const [field, name] of INBOX_ROWS) {- lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary.inbox[phase]?.[field])).join(" | ")} |`);++ const fmt = (v) => (typeof v === "number" ? (Number.isInteger(v) ? String(v) : v.toFixed(1)) : "—");+ const header = `| | ${inputs.map((i) => i.label).join(" | ")} |\n|---|${inputs.map(() => "---:").join("|")}|`;+ const lines = [];++ const issueKeys = [...new Set(inputs.flatMap((i) => Object.keys(i.report.summary?.issue ?? {})))];+ for (const key of issueKeys) {+ lines.push(`\n**Open a big issue: \`${key}\`** (median of samples)\n`, header);+ for (const [field, name] of ISSUE_ROWS) {+ lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary?.issue?.[key]?.[field])).join(" | ")} |`);+ }}-}-if (inputs.some((i) => i.report.summary?.inbox?.heap_mb_after_gc)) {- lines.push(`| JS heap after 30 switches, after GC (MB) | ${inputs.map((i) => fmt(i.report.summary.inbox.heap_mb_after_gc)).join(" | ")} |`);-}-const env = inputs[0].report;-lines.push(- "",- `Dataset ${env.dataset.version} (${env.dataset.digest}): ${Object.entries(env.dataset.counts).map(([k, v]) => `${v} ${k}`).join(", ")}.`,- `Chromium ${env.environment.browser}, ${env.environment.viewport}, ${env.environment.cpu} × ${env.environment.cores}.`,- ...inputs.map(({ label, report }) => {+ for (const phase of ["first-visit", "revisit"]) {+ if (!inputs.some((i) => i.report.summary?.inbox?.[phase])) continue;+ lines.push(`\n**Inbox switching: ${phase}** (all switches across samples)\n`, header);+ for (const [field, name] of INBOX_ROWS) {+ lines.push(`| ${name} | ${inputs.map((i) => fmt(i.report.summary?.inbox?.[phase]?.[field])).join(" | ")} |`);+ }+ }+ if (inputs.some((i) => i.report.summary?.inbox?.heap_mb_after_gc)) {+ lines.push(`| JS heap after 30 switches, after GC (MB) | ${inputs.map((i) => fmt(i.report.summary?.inbox?.heap_mb_after_gc)).join(" | ")} |`);+ }+ const first = inputs.find((i) => i.report.dataset && i.report.environment)?.report;+ if (first) {+ lines.push(+ "",+ `Dataset ${first.dataset.version} (${first.dataset.digest}): ${Object.entries(first.dataset.counts ?? {}).map(([k, v]) => `${v} ${k}`).join(", ")}.`,+ `Chromium ${first.environment.browser}, ${first.environment.viewport}, ${first.environment.cpu} × ${first.environment.cores}.`,+ );+ }+ for (const { label, report } of inputs) {const e = report.environment;+ if (!e) {+ lines.push(`${label}: ref ${report.ref ?? "?"}, no environment recorded.`);+ continue;+ }const until = e.inbox_until === "title" ? "issue title is visible" : "notified comment is in view";- return `${label}: ref ${report.ref ?? "?"}, CPU ${e.cpu_throttle}×, ${e.repeats} samples` +- (report.summary?.inbox?.["first-visit"] ? `, ${e.inbox_rows} Inbox rows, switch ends when the ${until}` : "") + ".";- }),-);-console.log(lines.join("\n"));+ lines.push(`${label}: ref ${report.ref ?? "?"}, CPU ${e.cpu_throttle}×, ${e.repeats} samples` ++ (report.summary?.inbox?.["first-visit"] ? `, ${e.inbox_rows} Inbox rows, switch ends when the ${until}` : "") + ".");+ }+ return lines.join("\n");+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const inputs = process.argv.slice(2).map((arg) => {+ const at = arg.indexOf("=");+ const label = at > 0 ? arg.slice(0, at) : arg;+ const path = at > 0 ? arg.slice(at + 1) : arg;+ return { label, report: JSON.parse(readFileSync(path, "utf8")) };+ });+ if (inputs.length === 0) {+ console.error("usage: node scripts/perf-core-report.mjs <label>=<report.json> [...]");+ process.exit(2);+ }+ try {+ console.log(renderCoreReport(inputs));+ } catch (error) {+ if (!(error instanceof DatasetMismatchError)) throw error;+ console.error(error.message);+ process.exit(1);+ }+}