diff --git a/docs/en/contribute/testing/perf.mdx b/docs/en/contribute/testing/perf.mdx index a34c92abe..b5c8351b9 100644 --- a/docs/en/contribute/testing/perf.mdx +++ b/docs/en/contribute/testing/perf.mdx @@ -29,7 +29,9 @@ pnpm perf -- --only typing --profile --unminified # CPU profile and top functi Other options: `--warmup ` (default 1), `--headed`, `--no-build` (reuse the last build), `--channel ` (default `chromium`, or `OPENIDEA_PERF_CHANNEL`), `--fail-on-regression`. -Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked on every run. +`--runs` must be a positive integer, `--warmup` a nonnegative integer, and `--cpu` a finite number of at least 1. Empty or unknown `--only` entries fail before building or launching a browser. Every declared selected scenario must return exactly one result; missing budgeted metrics and nonfinite metrics fail even when CPU throttling disables timing-budget enforcement. Unminified profiling builds intentionally omit bundle-size checks. + +Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked except with `--unminified`. Latencies are measured from input to the start of the first frame that shows the result, so about 16.7 ms means "next frame". @@ -44,7 +46,7 @@ A scenario in `perf/scenarios.ts` has an `id`, a `title` and a `run(h)` that dri ## Backend: `pnpm perf:rust` -`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search` and `ide-host`, reads the Criterion results from `target/criterion`, and checks each bench's mean (in µs). +`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search`, `ide-host` and `ide-heap`, reads the Criterion results, and checks each bench's mean (in µs). ```sh pnpm perf:rust # run the benches, then check @@ -62,6 +64,16 @@ The benches live in `crates//benches/`: | `search_5k/…` | `ide-search` | literal, regex and dense-match search over 5k files | | `plugins/…` | `ide-host` | loading 50 plugins, cold activation, syntax highlights of a 2k-line file | +Expected IDs and package ownership are declared independently of collected artifacts in `perf/lib/rust.ts`. A selected package must produce every expected ID, including observe-only measurements. `--package` scopes both collection and required budgets, also with `--no-run`; unknown packages fail before Cargo starts. + +Six IDs are observe-only (required finite measurements, without an absolute budget): `syntax_2mb/outline_uncached`, `syntax_2mb/folding_uncached`, `index_100k/find_files/zzzz`, `index_100k/find_symbols/renderView`, `startup_20k/reopen_wait_idle`, and `search_excluded_subtrees/5k_dependencies`. New IDs need an explicit budget or observe-only classification. + +## Code intelligence: `pnpm eval` + +Use `pnpm eval --list` for scenario IDs and supported conditions. `--only` accepts comma-separated IDs or dot-prefix groups; every entry must match executable work. `--condition` accepts only `warm` or `cold`, and a selection incompatible with that condition is rejected before building or launching. Repetition counts follow the UI runner's integer requirements. + +The selected scenario/condition plan defines the required outcomes independently of collected results. Missing, duplicate or unexpected outcomes fail; an empty workload cannot pass. Required timing and correctness metrics must be present and finite, rather than silently skipped by the judge. + ## Budgets and baselines [`perf/budgets.json`](https://github.com/l0ng-ai/openidea/blob/main/perf/budgets.json) holds upper bounds (lower is better): diff --git a/docs/zh/contribute/testing/perf.mdx b/docs/zh/contribute/testing/perf.mdx index ab07a92a4..42e25f70c 100644 --- a/docs/zh/contribute/testing/perf.mdx +++ b/docs/zh/contribute/testing/perf.mdx @@ -29,7 +29,9 @@ pnpm perf -- --only typing --profile --unminified # CPU profile 和耗时最 其他选项:`--warmup `(默认 1)、`--headed`、`--no-build`(复用上次构建)、`--channel `(默认 `chromium`,或 `OPENIDEA_PERF_CHANNEL`)、`--fail-on-regression`。 -场景(`perf/scenarios.ts`):`typing`、`typingLarge`、`typingAngular`、`completion`、`consoleOutput`、`terminalTui`、`keyRepeat`、`scroll`、`gitLog`、`gitLogScrollbar`、`resizePanels`、`startup`、`tabs`、`agentTabs`、`popups`、`toolWindows`、`projectTree`、`leaks`。每次运行都会检查包体积(`bundle.initialJsKb`、`bundle.initialCssKb`)。 +`--runs` 必须为正整数,`--warmup` 为非负整数,`--cpu` 为不小于 1 的有限数值。`--only` 中的空项或未知场景会在构建或启动浏览器前报错。每个选中场景必须恰好返回一份结果;预算指标缺失或指标非有限值都会失败,即使 CPU 降速关闭了耗时预算检查。未压缩的性能分析构建不检查包体积。 + +场景(`perf/scenarios.ts`):`typing`、`typingLarge`、`typingAngular`、`completion`、`consoleOutput`、`terminalTui`、`keyRepeat`、`scroll`、`gitLog`、`gitLogScrollbar`、`resizePanels`、`startup`、`tabs`、`agentTabs`、`popups`、`toolWindows`、`projectTree`、`leaks`。除 `--unminified` 外,每次运行都会检查包体积(`bundle.initialJsKb`、`bundle.initialCssKb`)。 延迟是从输入到显示结果的第一帧开始的时间,因此约 16.7 ms 就表示“下一帧”。 @@ -44,7 +46,7 @@ pnpm perf -- --only typing --profile --unminified # CPU profile 和耗时最 ## 后端:`pnpm perf:rust` -`perf/rust.ts` 对 `ide-text`、`ide-language`、`ide-index`、`ide-search` 和 `ide-host` 运行 `cargo bench`,从 `target/criterion` 读取 Criterion 结果,检查每个基准的平均值(µs)。 +`perf/rust.ts` 对 `ide-text`、`ide-language`、`ide-index`、`ide-search`、`ide-host` 和 `ide-heap` 运行 `cargo bench`,读取 Criterion 结果,检查每个基准的平均值(µs)。 ```sh pnpm perf:rust # 跑基准并检查 @@ -62,6 +64,16 @@ pnpm perf:rust -- --package ide-text --save-baseline | `search_5k/…` | `ide-search` | 在 5 千个文件中做字面量、正则和密集匹配搜索 | | `plugins/…` | `ide-host` | 加载 50 个插件、冷激活、2 千行文件的语法高亮 | +预期 ID 及其所属包在 `perf/lib/rust.ts` 中独立于收集到的产物声明。选中的包必须提供全部预期 ID,包括仅观察的指标。`--package` 同时限定收集范围和必需预算,使用 `--no-run` 时也如此;未知包会在启动 Cargo 前报错。 + +六个 ID 仅观察(必须提供有限测量值,但没有绝对预算):`syntax_2mb/outline_uncached`、`syntax_2mb/folding_uncached`、`index_100k/find_files/zzzz`、`index_100k/find_symbols/renderView`、`startup_20k/reopen_wait_idle`、`search_excluded_subtrees/5k_dependencies`。新增 ID 必须明确设置预算或归类为仅观察。 + +## 代码智能:`pnpm eval` + +用 `pnpm eval --list` 查看场景 ID 及支持的条件。`--only` 接受逗号分隔的 ID 或点号前缀分组;每项都必须匹配可执行的工作。`--condition` 只接受 `warm` 或 `cold`,与该条件不兼容的选择会在构建或启动前被拒绝。重复次数遵循 UI 运行器的整数要求。 + +选中的场景/条件计划独立于收集结果定义必需的输出。缺失、重复或非预期输出都会失败,空工作集不能通过。必需的耗时和正确性指标必须存在且为有限数值,判定器不再静默跳过它们。 + ## 预算与基线 [`perf/budgets.json`](https://github.com/l0ng-ai/openidea/blob/main/perf/budgets.json) 保存上限(越低越好): diff --git a/evals/lib/cli.test.ts b/evals/lib/cli.test.ts new file mode 100644 index 000000000..d1f97d0d7 --- /dev/null +++ b/evals/lib/cli.test.ts @@ -0,0 +1,29 @@ +import { spawnSync } from "node:child_process"; +import { resolve } from "node:path"; +import { describe, expect, test } from "vitest"; + +const runner = resolve(import.meta.dirname, "../run.ts"); + +describe("eval CLI preflight (no app builds)", () => { + test.each([ + [["--condition", "hot"], /--condition must be warm or cold/], + [["--only", "java.app,unknown"], /no scenario matches unknown/], + [["--only", "java.app,"], /empty selector/], + [["--only", "java.app.usages", "--condition", "cold"], /no compatible scenario/], + [["--runs", "0"], /--runs/], + [["--runs", "Infinity"], /--runs/], + [["--runs", "1.5"], /--runs/], + [["--warmup", "NaN"], /--warmup/], + [["--warmup=-1"], /--warmup/], + ] as const)("rejects %j before build/start", (args, message) => { + const result = spawnSync(process.execPath, [runner, ...args], { + encoding: "utf8", + timeout: 15_000, + env: { ...process.env, PATH: "", OPENIDEA_SERVER: "/nonexistent/eval-preflight-server" }, + }); + expect(result.error).toBeUndefined(); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(message); + expect(result.stdout).not.toContain("Building openidea-server"); + }); +}); diff --git a/evals/lib/selection.test.ts b/evals/lib/selection.test.ts new file mode 100644 index 000000000..7b230e9c6 --- /dev/null +++ b/evals/lib/selection.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from "vitest"; +import { planSelection } from "./selection.ts"; + +const scenarios = [ + { id: "java.a.one", title: "One", conditions: ["warm", "cold"] as const }, + { id: "java.b.two", title: "Two", conditions: ["warm"] as const }, +]; + +describe("eval workload planning", () => { + test("full and deduplicated subset plans are independent of collected outcomes", () => { + expect(planSelection(scenarios, {}).expected).toHaveLength(3); + const plan = planSelection(scenarios, { only: " java.a, java.a.one ", condition: "cold" }); + expect(plan.selected).toEqual([scenarios[0]]); + expect(plan.expected).toEqual([{ scenario: "java.a.one", title: "One", condition: "cold" }]); + }); + test.each([ + { condition: "hot" }, + { only: "java.a,unknown" }, + { only: "" }, + { only: "java.a," }, + { only: "java.b", condition: "cold" }, + { only: "java.a,java.b", condition: "cold" }, + { runs: "0" }, + { runs: "NaN" }, + { runs: "Infinity" }, + { runs: "1.5" }, + { runs: "9007199254740992" }, + { warmup: "-1" }, + { warmup: "Infinity" }, + { warmup: "0.5" }, + ])("rejects invalid selection/counts %j", (args) => { + expect(() => planSelection(scenarios, args)).toThrow(); + }); + test("rejects zero work", () => { + expect(() => planSelection([], {})).toThrow(/no compatible/); + }); +}); diff --git a/evals/lib/selection.ts b/evals/lib/selection.ts new file mode 100644 index 000000000..1364ae1f5 --- /dev/null +++ b/evals/lib/selection.ts @@ -0,0 +1,42 @@ +import { countOption } from "../../perf/lib/options.ts"; +import type { Condition } from "./verdict.ts"; + +interface Scenario { + id: string; + title: string; + conditions: readonly Condition[]; +} + +export interface ExpectedOutcome { + scenario: string; + title: string; + condition: Condition; +} + +export function planSelection( + scenarios: readonly T[], + args: { only?: string; condition?: string; runs?: string; warmup?: string }, +) { + const runs = countOption("runs", args.runs ?? "3", 1); + const warmup = countOption("warmup", args.warmup ?? "1", 0); + if (args.condition !== undefined && args.condition !== "warm" && args.condition !== "cold") + throw new Error("--condition must be warm or cold"); + const condition = args.condition as Condition | undefined; + const selectors = args.only?.split(",").map((s) => s.trim()); + const matches = (s: T, selector: string) => s.id === selector || s.id.startsWith(`${selector}.`); + for (const selector of selectors ?? []) { + if (!selector) throw new Error("--only contains an empty selector"); + const matching = scenarios.filter((s) => matches(s, selector)); + if (!matching.length) throw new Error(`no scenario matches ${selector} (see --list)`); + if (!matching.some((s) => s.conditions.some((c) => !condition || c === condition))) + throw new Error(`no compatible scenario for selector ${selector} under ${condition}`); + } + const selected = scenarios.filter((s) => !selectors || selectors.some((selector) => matches(s, selector))); + const expected: ExpectedOutcome[] = selected.flatMap((s) => + s.conditions + .filter((c) => !condition || c === condition) + .map((c) => ({ scenario: s.id, title: s.title, condition: c })), + ); + if (!expected.length) throw new Error("no compatible scenarios selected"); + return { selected, expected, runs, warmup, condition }; +} diff --git a/evals/lib/verdict.test.ts b/evals/lib/verdict.test.ts index 1b76349c0..e3126c918 100644 --- a/evals/lib/verdict.test.ts +++ b/evals/lib/verdict.test.ts @@ -20,10 +20,11 @@ const outcome = (o: Partial): Outcome => ({ }); const repro = () => "pnpm eval --only usages"; +const expected = [{ scenario: "usages", title: "Show Usages", condition: "warm" as const }]; describe("judge", () => { test("within budgets and matching the golden passes", () => { - const [v] = judge([outcome({})], budgets, null, repro); + const [v] = judge([outcome({})], budgets, null, repro, expected); expect(v).toMatchObject({ id: "usages@warm", status: "pass", failures: [], repro: "pnpm eval --only usages" }); }); @@ -39,6 +40,7 @@ describe("judge", () => { budgets, null, repro, + expected, ); expect(v!.status).toBe("fail"); expect(v!.failures.map((f) => [f.kind, f.metric])).toEqual([ @@ -52,21 +54,29 @@ describe("judge", () => { test("condition budgets override scenario budgets", () => { const [v] = judge( - [outcome({ condition: "cold", metrics: { feedbackMs: 40, completeMs: 5000, recall: 1, precision: 1 } })], + [ + outcome({ + condition: "cold", + metrics: { feedbackMs: 40, firstResultMs: 300, completeMs: 5000, recall: 1, precision: 1 }, + }), + ], budgets, null, repro, + [{ ...expected[0]!, condition: "cold" }], ); expect(v!.status).toBe("pass"); }); test("timeouts and missing goldens fail", () => { - const [timedOut, noGolden] = judge( - [outcome({ error: "find.showUsages timed out after 30000 ms" }), outcome({ comparison: undefined })], + const [timedOut] = judge( + [outcome({ error: "find.showUsages timed out after 30000 ms" })], budgets, null, repro, + expected, ); + const [noGolden] = judge([outcome({ comparison: undefined })], budgets, null, repro, expected); expect(timedOut!.failures[0]!.kind).toBe("timeout"); expect(noGolden!.failures[0]!.kind).toBe("golden"); }); @@ -78,9 +88,41 @@ describe("judge", () => { budgets, baseline, repro, + expected, ); expect(v!.status).toBe("pass"); expect(v!.regressions.map((r) => r.metric)).toEqual(["completeMs"]); expect(table([v!], false)).toContain("regressed: completeMs"); }); + + test("missing, duplicate, unexpected and empty workloads fail", () => { + for (const actual of [[], [outcome({}), outcome({})], [outcome({ scenario: "other" })]]) { + expect(judge(actual, budgets, null, repro, expected).some((v) => v.status === "fail")).toBe(true); + } + expect(judge([], budgets, null, repro, []).some((v) => v.status === "fail")).toBe(true); + }); + + test.each(["feedbackMs", "firstResultMs", "completeMs", "recall", "precision"])("requires finite %s", (metric) => { + for (const value of [undefined, NaN, Infinity, -Infinity]) { + const o = outcome({}); + if (value === undefined) delete o.metrics[metric]; + else o.metrics[metric] = value; + const [v] = judge([o], budgets, null, repro, expected); + expect(v!.status).toBe("fail"); + expect(v!.failures.some((f) => f.metric === metric)).toBe(true); + } + }); + + test("requires scenario budget metrics and rejects nonfinite unbudgeted values", () => { + const custom = { ...budgets, scenarios: { usages: { readyMs: 100 } } }; + expect(judge([outcome({})], custom, null, repro, expected)[0]!.status).toBe("fail"); + const o = outcome({}); + o.metrics.extraMs = NaN; + expect(judge([o], budgets, null, repro, expected)[0]!.status).toBe("fail"); + }); + + test("a clean empty result set with a perfect comparison passes", () => { + const o = outcome({ results: { problems: [] } }); + expect(judge([o], budgets, null, repro, expected)[0]!.status).toBe("pass"); + }); }); diff --git a/evals/lib/verdict.ts b/evals/lib/verdict.ts index 7f177a626..9483a0cbd 100644 --- a/evals/lib/verdict.ts +++ b/evals/lib/verdict.ts @@ -4,6 +4,7 @@ */ import { readFileSync } from "node:fs"; import type { Comparison, ResultSet } from "./golden.ts"; +import type { ExpectedOutcome } from "./selection.ts"; export type Condition = "warm" | "cold"; @@ -97,15 +98,42 @@ export function judge( budgets: Budgets, baseline: Outcome[] | null, repro: (o: Outcome) => string, + expected: readonly ExpectedOutcome[], ): Verdict[] { const base = new Map((baseline ?? []).map((o) => [idOf(o), o.metrics])); - return outcomes.map((o) => { + const expectedIds = new Set(expected.map(idOf)); + const counts = new Map(); + for (const o of outcomes) counts.set(idOf(o), (counts.get(idOf(o)) ?? 0) + 1); + const work: Outcome[] = [...outcomes]; + for (const e of expected) { + if (!counts.has(idOf(e))) work.push({ ...e, metrics: {}, samples: {}, error: "missing expected outcome" }); + } + if (!work.length) work.push({ scenario: "workload", title: "Workload", condition: "warm", metrics: {}, samples: {} }); + return work.map((o) => { const failures: Failure[] = []; + if (!expected.length) failures.push({ kind: "error", detail: "expected workload is empty" }); + if (expectedIds.size !== expected.length) failures.push({ kind: "error", detail: "duplicate expected outcome" }); + if (!expectedIds.has(idOf(o))) failures.push({ kind: "error", detail: "unexpected outcome" }); + if ((counts.get(idOf(o)) ?? 0) > 1) failures.push({ kind: "error", detail: "duplicate outcome" }); if (o.error) failures.push({ kind: /timed out/.test(o.error) ? "timeout" : "error", detail: o.error }); if (o.degraded) failures.push({ kind: "degraded", detail: o.degraded }); if (o.results && !o.comparison && !o.error) failures.push({ kind: "golden", detail: "no golden recorded: run with --update-golden and review it" }); - for (const [metric, limit] of Object.entries(budgetsFor(budgets, o))) { + const limits = budgetsFor(budgets, o); + const required = new Set(["feedbackMs", "firstResultMs", "completeMs", ...Object.keys(limits)]); + if (o.results || o.comparison) { + required.add("recall"); + required.add("precision"); + } + for (const metric of new Set([...required, ...Object.keys(o.metrics)])) { + if (!Number.isFinite(o.metrics[metric])) + failures.push({ + kind: lowerBound(metric) ? "correctness" : "budget", + metric, + detail: `${metric} is missing or nonfinite`, + }); + } + for (const [metric, limit] of Object.entries(limits)) { const value = o.metrics[metric]; if (value === undefined || !Number.isFinite(value)) continue; const over = lowerBound(metric) ? value < limit : value > limit; diff --git a/evals/run.ts b/evals/run.ts index fa8b07d82..bbf424130 100644 --- a/evals/run.ts +++ b/evals/run.ts @@ -25,6 +25,7 @@ import { compare, readGolden, toolDrift, writeGolden, type ResultSet } from "./l import { TimeoutError } from "./lib/measure.ts"; import { fingerprint, pinnedTools, sameMachine, toolVersions, type Fingerprint } from "./lib/machine.ts"; import type { EvalScenario } from "./lib/scenario.ts"; +import { planSelection } from "./lib/selection.ts"; import { Session } from "./lib/session.ts"; import { idOf, judge, loadBudgets, table, type Condition, type Diagnostics, type Outcome } from "./lib/verdict.ts"; @@ -56,12 +57,7 @@ if (args.list) { process.exit(0); } -const runs = Math.max(1, Number(args.runs)); -const warmup = Math.max(0, Number(args.warmup)); -const only = args.only?.split(",").map((s) => s.trim()); -const conditionFilter = args.condition as Condition | undefined; -const selected = SCENARIOS.filter((s) => !only || only.some((o) => s.id === o || s.id.startsWith(`${o}.`))); -if (only && !selected.length) throw new Error(`no scenario matches ${args.only} (see --list)`); +const { runs, warmup, selected, expected, condition: conditionFilter } = planSelection(SCENARIOS, args); const goldenFile = (id: string) => join(ROOT, "evals", id.slice(0, id.indexOf(".")), "golden", `${id}.json`); @@ -296,7 +292,7 @@ async function main() { else console.warn("warning: target/eval/baseline.json is from another machine or OS: not compared"); } const repro = (o: Outcome) => `pnpm eval --only ${o.scenario} --condition ${o.condition}`; - const verdicts = judge(outcomes, loadBudgets(join(ROOT, "evals", "budgets.json")), baseline, repro); + const verdicts = judge(outcomes, loadBudgets(join(ROOT, "evals", "budgets.json")), baseline, repro, expected); const meta = { date: new Date().toISOString(), @@ -313,17 +309,17 @@ async function main() { meta, pass: verdicts.every((v) => v.status === "pass"), verdicts: verdicts.map((v) => { - const o = outcomes.find((x) => idOf(x) === v.id)!; + const o = outcomes.find((x) => idOf(x) === v.id); return { ...v, - samples: o.samples, - results: o.results, - comparison: o.comparison, - drift: o.drift, - degraded: o.degraded, - error: o.error, + samples: o?.samples, + results: o?.results, + comparison: o?.comparison, + drift: o?.drift, + degraded: o?.degraded, + error: o?.error, // Diagnostics only where something needs a look. - diagnostics: v.status === "fail" || v.regressions.length ? o.diagnostics : undefined, + diagnostics: v.status === "fail" || v.regressions.length ? o?.diagnostics : undefined, }; }), }; @@ -345,9 +341,9 @@ async function main() { for (const v of failing) { console.log(`\n${v.id} FAILED (${v.repro})`); for (const f of v.failures) console.log(` ${f.kind}: ${f.detail}`); - const o = outcomes.find((x) => idOf(x) === v.id)!; - if (o.drift?.length) console.log(` golden recorded with other tools: ${o.drift.join(", ")}`); - const slow = [...(o.diagnostics?.calls ?? [])].sort((a, b) => b.ms - a.ms).slice(0, 5); + const o = outcomes.find((x) => idOf(x) === v.id); + if (o?.drift?.length) console.log(` golden recorded with other tools: ${o.drift.join(", ")}`); + const slow = [...(o?.diagnostics?.calls ?? [])].sort((a, b) => b.ms - a.ms).slice(0, 5); if (slow.length) console.log( ` slowest commands: ${slow.map((c) => `${c.cmd} ${Math.round(c.ms)} ms${c.pending ? " (no answer)" : c.ok ? "" : " (failed)"}`).join(", ")}`, diff --git a/perf/lib/options.test.ts b/perf/lib/options.test.ts new file mode 100644 index 000000000..c068dde28 --- /dev/null +++ b/perf/lib/options.test.ts @@ -0,0 +1,47 @@ +import { spawnSync } from "node:child_process"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; +import { countOption } from "./options.ts"; + +const root = resolve(import.meta.dirname, "../.."); + +describe("benchmark CLI validation", () => { + it.each([ + ["runs", "NaN"], + ["runs", "Infinity"], + ["runs", "0"], + ["runs", "1.5"], + ["warmup", "-1"], + ["warmup", "NaN"], + ["warmup", "0.5"], + ["cpu", "NaN"], + ["cpu", "Infinity"], + ["cpu", "0"], + ])("rejects --%s %s before selecting or launching workloads", (option, value) => { + const result = spawnSync( + process.execPath, + ["perf/run.ts", "--no-build", "--only", "__unknown__", `--${option}=${value}`], + { cwd: root, encoding: "utf8", timeout: 10_000 }, + ); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`--${option} must be`); + expect(result.stdout).not.toContain("Building"); + }); + + it.each(["typing,__unknown__", "", "typing,"])("rejects invalid selection %j", (selection) => { + const result = spawnSync(process.execPath, ["perf/run.ts", "--no-build", "--only", selection], { + cwd: root, + encoding: "utf8", + timeout: 10_000, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("unknown scenario(s)"); + }); + + it("accepts integral counts and zero warmup without silently clamping", () => { + expect(countOption("runs", "5", 1)).toBe(5); + expect(countOption("warmup", "0", 0)).toBe(0); + expect(() => countOption("warmup", "", 0)).toThrow(); + expect(() => countOption("runs", "9007199254740992", 1)).toThrow(); + }); +}); diff --git a/perf/lib/options.ts b/perf/lib/options.ts new file mode 100644 index 000000000..e7355741d --- /dev/null +++ b/perf/lib/options.ts @@ -0,0 +1,8 @@ +/** CLI repetition counts must be validated before any build or process launch. */ +export function countOption(name: string, raw: string, minimum: 0 | 1): number { + const value = Number(raw); + if (!raw.trim() || !Number.isSafeInteger(value) || value < minimum) { + throw new Error(`--${name} must be an integer >= ${minimum}`); + } + return value; +} diff --git a/perf/lib/report.test.ts b/perf/lib/report.test.ts index c203b7662..5de47134c 100644 --- a/perf/lib/report.test.ts +++ b/perf/lib/report.test.ts @@ -32,6 +32,7 @@ describe("evaluate", () => { it("fails metrics over budget and budgeted metrics that are missing", () => { const r = evaluate(results, { "typing.maxMs": 33, "typing.missedFramePct": 2, "other.x": 1 }, null, { enforceBudgets: true, + expected: ["typing"], }); expect(r.rows.find((x) => x.key === "typing.maxMs")?.verdict).toBe("over-budget"); expect(r.rows.find((x) => x.key === "typing.missedFramePct")?.verdict).toBe("error"); @@ -41,18 +42,57 @@ describe("evaluate", () => { }); it("reports but does not fail budgets when not enforced", () => { - const r = evaluate(results, { "typing.maxMs": 33 }, null, { enforceBudgets: false }); + const r = evaluate(results, { "typing.maxMs": 33 }, null, { enforceBudgets: false, expected: ["typing"] }); expect(r.rows.find((x) => x.key === "typing.maxMs")?.verdict).toBe("over-budget-info"); expect(r.failures).toBe(0); }); it("compares against the baseline with relative and absolute slack", () => { const baseline = [{ id: "typing", title: "", metrics: { p95Ms: 14, maxMs: 39.5, layoutsPerKey: 2 } }]; - const r = evaluate(results, {}, baseline, { enforceBudgets: true, tolerance: 0.2, floor: 1 }); + const r = evaluate(results, {}, baseline, { + enforceBudgets: true, + expected: ["typing"], + tolerance: 0.2, + floor: 1, + }); const verdict = (k: string) => r.rows.find((x) => x.key === k)?.verdict; expect(verdict("typing.p95Ms")).toBe("regressed"); // +28 %, +4 ms expect(verdict("typing.maxMs")).toBe("ok"); // within 20 % expect(verdict("typing.layoutsPerKey")).toBe("ok"); // +50 % but only +1 (floor) expect(r.regressions).toBe(1); }); + + it("fails when a declared scenario disappears from the results", () => { + const report = evaluate(results, { "scroll.jumpMs": 50 }, null, { + enforceBudgets: true, + expected: ["typing", "scroll"], + }); + expect(report.errors).toContainEqual({ id: "scroll", error: "missing scenario result" }); + expect(report.rows.find((r) => r.key === "scroll.jumpMs")?.verdict).toBe("error"); + expect(report.failures).toBeGreaterThan(0); + }); + + it("rejects duplicate and unexpected scenario results", () => { + const report = evaluate([...results, ...results, { id: "other", title: "", metrics: { ms: 1 } }], {}, null, { + enforceBudgets: true, + expected: ["typing"], + }); + expect(report.errors).toEqual([ + { id: "typing", error: "duplicate scenario result" }, + { id: "other", error: "unexpected scenario result" }, + ]); + }); + + it("rejects an empty workload instead of returning a passing report", () => { + expect(evaluate([], {}, null, { enforceBudgets: true, expected: [] }).failures).toBeGreaterThan(0); + }); + + it("fails nonfinite metrics even without an absolute budget", () => { + const report = evaluate([{ id: "typing", title: "", metrics: { ms: Infinity } }], {}, null, { + enforceBudgets: false, + expected: ["typing"], + }); + expect(report.rows[0]?.verdict).toBe("error"); + expect(report.failures).toBe(1); + }); }); diff --git a/perf/lib/report.ts b/perf/lib/report.ts index 2ae4c66f6..97ba0ab0d 100644 --- a/perf/lib/report.ts +++ b/perf/lib/report.ts @@ -52,7 +52,7 @@ export function evaluate( results: ScenarioResult[], budgets: Record, baseline: ScenarioResult[] | null, - opts: { enforceBudgets: boolean; tolerance?: number; floor?: number }, + opts: { expected: readonly string[]; enforceBudgets: boolean; tolerance?: number; floor?: number }, ): Report { const tol = opts.tolerance ?? 0.2; const floor = opts.floor ?? 1; @@ -62,7 +62,21 @@ export function evaluate( const rows: Row[] = []; const errors: Report["errors"] = []; const seen = new Set(); + const expected = new Set(opts.expected); + const produced = new Set(); + if (!expected.size) errors.push({ id: "run", error: "empty workload" }); + if (expected.size !== opts.expected.length) errors.push({ id: "run", error: "duplicate expected scenario" }); for (const r of results) { + if (!expected.has(r.id)) { + errors.push({ id: r.id, error: "unexpected scenario result" }); + continue; + } + if (produced.has(r.id)) { + errors.push({ id: r.id, error: "duplicate scenario result" }); + continue; + } + produced.add(r.id); + if (!r.error && !Object.keys(r.metrics).length) errors.push({ id: r.id, error: "no metrics produced" }); if (r.error) errors.push({ id: r.id, error: r.error }); for (const [m, value] of Object.entries(r.metrics)) { const key = `${r.id}.${m}`; @@ -70,7 +84,7 @@ export function evaluate( const budget = budgets[key]; const before = base.get(key); let verdict: Verdict = "ok"; - if (!Number.isFinite(value)) verdict = budget === undefined ? "ok" : "error"; + if (!Number.isFinite(value)) verdict = "error"; else if (budget !== undefined && value > budget) verdict = opts.enforceBudgets ? "over-budget" : "over-budget-info"; else if (before !== undefined && value > before * (1 + tol) && value - before > floor) verdict = "regressed"; @@ -78,10 +92,12 @@ export function evaluate( rows.push({ key, value, budget, baseline: before, verdict }); } } - // A budgeted metric that was not produced (scenario failed or renamed) fails too. - const ran = new Set(results.map((r) => r.id)); + for (const id of expected) { + if (!produced.has(id)) errors.push({ id, error: "missing scenario result" }); + } + // Required metrics are scoped by the declared workload, never by returned data. for (const key of Object.keys(budgets)) { - if (!seen.has(key) && ran.has(key.slice(0, key.indexOf(".")))) { + if (!seen.has(key) && expected.has(key.slice(0, key.indexOf(".")))) { rows.push({ key, value: NaN, budget: budgets[key], verdict: "error" }); } } diff --git a/perf/lib/rust.test.ts b/perf/lib/rust.test.ts new file mode 100644 index 000000000..19510db7f --- /dev/null +++ b/perf/lib/rust.test.ts @@ -0,0 +1,175 @@ +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { collectRustMetrics, RUST_BENCHMARKS, rustBudgets, rustPaths, selectRustPackages } from "./rust.ts"; + +const roots: string[] = []; +function fixture() { + const root = mkdtempSync(join(tmpdir(), "rust-validity-")); + roots.push(root); + return root; +} +function artifact(root: string, id: string, value: unknown = 1000, directory = id) { + const dir = join(root, directory, "new"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "benchmark.json"), JSON.stringify({ full_id: id })); + writeFileSync(join(dir, "estimates.json"), JSON.stringify({ mean: { point_estimate: value } })); + return dir; +} +function complete(root: string, packages: readonly string[]) { + for (const p of packages) for (const id of RUST_BENCHMARKS[p]!) artifact(root, id); +} +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe("Rust workload contract", () => { + it("owns 40 unique IDs and exactly six observe-only metrics", () => { + const ids = Object.values(RUST_BENCHMARKS).flat(); + expect(ids).toHaveLength(40); + expect(new Set(ids).size).toBe(40); + const budgets = JSON.parse(readFileSync(resolve(import.meta.dirname, "../budgets.json"), "utf8")).rust; + const selected = rustBudgets(selectRustPackages(), budgets); + expect(Object.keys(selected)).toHaveLength(34); + expect(ids.filter((id) => !(id in budgets))).toEqual([ + "syntax_2mb/outline_uncached", + "syntax_2mb/folding_uncached", + "index_100k/find_files/zzzz", + "index_100k/find_symbols/renderView", + "startup_20k/reopen_wait_idle", + "search_excluded_subtrees/5k_dependencies", + ]); + expect(Object.keys(rustBudgets(["ide-text"], budgets))).toHaveLength(9); + const missing = { ...budgets }; + delete missing["text/open_1mb"]; + expect(() => rustBudgets(["ide-text"], missing)).toThrow(/classification/); + expect(() => rustBudgets(["ide-text"], { ...budgets, "text/new": 1 })).toThrow(/unknown/); + expect(() => rustBudgets(["ide-text"], { ...budgets, "syntax_2mb/outline_uncached": 1 })).toThrow(/observe-only/); + }); + + it("rejects unknown or empty packages and deduplicates before cargo", () => { + expect(() => selectRustPackages([])).toThrow(/empty/); + expect(() => selectRustPackages([""])).toThrow(/unknown/); + expect(() => selectRustPackages(["not-a-crate"])).toThrow(/unknown/); + expect(selectRustPackages(["ide-text", "ide-text"])).toEqual(["ide-text"]); + }); + + it("rejects unknown CLI packages without invoking cargo", () => { + const root = fixture(); + const marker = join(root, "cargo-invoked"); + writeFileSync(join(root, "cargo"), `#!/bin/sh\n: > '${marker}'\nexit 99\n`, { mode: 0o755 }); + const result = spawnSync( + process.execPath, + [resolve(import.meta.dirname, "../rust.ts"), "--package", "not-a-crate"], + { + env: { ...process.env, PATH: root, CARGO_TARGET_DIR: join(root, "target") }, + encoding: "utf8", + }, + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(/unknown Rust package/); + expect(existsSync(marker)).toBe(false); + }); + + it("resolves target and Criterion overrides relative to cargo's cwd", () => { + expect(rustPaths("/work", {})).toEqual({ target: "/work/target", criterion: "/work/target/criterion" }); + expect(rustPaths("/work", { CARGO_TARGET_DIR: "private" })).toEqual({ + target: "/work/private", + criterion: "/work/private/criterion", + }); + expect(rustPaths("/work", { CARGO_TARGET_DIR: "/private", CRITERION_HOME: "results" })).toEqual({ + target: "/private", + criterion: "/work/results", + }); + }); + + it("accepts a complete full workload and converts nanoseconds to microseconds", () => { + const root = fixture(); + complete(root, selectRustPackages()); + expect(Object.keys(collectRustMetrics(root, selectRustPackages()))).toHaveLength(40); + expect(collectRustMetrics(root, ["ide-text"])["text/open_1mb"]).toBe(1); + }); + + it("requires selected IDs independently of budgets, including observe-only IDs", () => { + const root = fixture(); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/missing/); + complete(root, ["ide-language"]); + rmSync(join(root, "syntax_2mb/outline_uncached"), { recursive: true }); + expect(() => collectRustMetrics(root, ["ide-language"])).toThrow(/outline_uncached/); + expect(() => collectRustMetrics(root, selectRustPackages())).toThrow(/missing/); + }); + + it.each([ + ["ide-language", "syntax_2mb/outline_uncached"], + ["ide-language", "syntax_2mb/folding_uncached"], + ["ide-index", "index_100k/find_files/zzzz"], + ["ide-index", "index_100k/find_symbols/renderView"], + ["ide-index", "startup_20k/reopen_wait_idle"], + ["ide-search", "search_excluded_subtrees/5k_dependencies"], + ])("requires observe-only metric %s / %s", (p, id) => { + const root = fixture(); + complete(root, [p]); + rmSync(join(root, id), { recursive: true }); + expect(() => collectRustMetrics(root, [p])).toThrow(/missing selected/); + }); + + it("ignores known unselected artifacts, including their malformed estimates", () => { + const root = fixture(); + complete(root, ["ide-text"]); + artifact(root, "heap/index_1m_objects", "bad"); + const unrelated = artifact(root, "heap/dominators_1m_random"); + writeFileSync(join(unrelated, "benchmark.json"), "{"); + expect(Object.keys(collectRustMetrics(root, ["ide-text"]))).toHaveLength(RUST_BENCHMARKS["ide-text"].length); + }); + + it("rejects duplicate IDs and unknown selected IDs even with complete expected results", () => { + const root = fixture(); + complete(root, ["ide-text"]); + artifact(root, "text/open_1mb", 1000, "duplicate"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/duplicate/); + rmSync(join(root, "duplicate"), { recursive: true }); + artifact(root, "text/renamed"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/unknown/); + }); + + it.each([null, "1000", -1, {}])("rejects invalid means: %j", (value) => { + const root = fixture(); + complete(root, ["ide-text"]); + artifact(root, "text/open_1mb", value); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/estimate/); + }); + + it("accepts zero and rejects malformed metadata, absent estimates, and invalid JSON", () => { + const root = fixture(); + complete(root, ["ide-text"]); + const dir = artifact(root, "text/open_1mb", 0); + expect(collectRustMetrics(root, ["ide-text"])["text/open_1mb"]).toBe(0); + writeFileSync(join(dir, "benchmark.json"), "{}"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/full_id/); + artifact(root, "text/open_1mb"); + rmSync(join(dir, "estimates.json")); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(); + writeFileSync(join(dir, "estimates.json"), "{"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(); + writeFileSync(join(dir, "estimates.json"), "{}"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/estimate/); + }); + + it.each(["benchmark.json", "estimates.json"])("requires fresh %s for a newly run workload", (file) => { + const root = fixture(); + complete(root, ["ide-text"]); + const dir = artifact(root, "text/open_1mb"); + utimesSync(join(dir, file), new Date(0), new Date(0)); + expect(() => collectRustMetrics(root, ["ide-text"], 1)).toThrow(/stale/); + expect(Object.keys(collectRustMetrics(root, ["ide-text"]))).toHaveLength(RUST_BENCHMARKS["ide-text"].length); + }); + it("rejects overflowing JSON numeric estimates, including observe-only metrics", () => { + const root = fixture(); + complete(root, ["ide-language"]); + const dir = artifact(root, "syntax_2mb/outline_uncached"); + writeFileSync(join(dir, "estimates.json"), '{"mean":{"point_estimate":1e309}}'); + expect(() => collectRustMetrics(root, ["ide-language"])).toThrow(/estimate/); + }); +}); diff --git a/perf/lib/rust.ts b/perf/lib/rust.ts new file mode 100644 index 000000000..3c9864e00 --- /dev/null +++ b/perf/lib/rust.ts @@ -0,0 +1,157 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative, resolve, sep } from "node:path"; + +// Package-owned expectations, independent of collected artifacts and human-owned budgets. +export const RUST_BENCHMARKS: Readonly> = { + "ide-text": [ + "text/open_1mb", + "text/apply_keystroke_1mb", + "text/apply_100_changes_1mb", + "text/diff_two_edits_1mb", + "text/diff_every_line_1mb", + "text/offset_to_pos_round_trip", + "text/pos_to_byte", + "text/text_for_save_crlf_1mb", + "text/diff_one_edit_5mb", + ], + "ide-language": [ + "syntax_2mb/outline_uncached", + "syntax_2mb/folding_uncached", + "syntax_2mb/outline_cached_hit", + "syntax_2mb/folding_cached_hit", + "syntax_2mb/selection_cached_hit", + "syntax_2mb/folding_after_keystroke_incremental", + "syntax_2mb/outline_after_keystroke_incremental", + ], + "ide-index": [ + "index_100k/find_files/ordcon", + "index_100k/find_files/src/user", + "index_100k/find_files/PaymentService", + "index_100k/find_files/zzzz", + "index_100k/find_files/a", + "index_100k/find_dirs/util", + "index_100k/find_dirs/src/ui", + "index_100k/find_dirs/a", + "index_100k/find_symbols/OCo", + "index_100k/find_symbols/invoiceRepo", + "index_100k/find_symbols/renderView", + "index_100k/find_symbols/q", + "index_100k/find_symbols_types/UsSe", + "startup_20k/reopen_wait_idle", + ], + "ide-search": [ + "search_5k/literal", + "search_5k/regex", + "search_5k/dense_limit", + "search_dense_files/24x40k_limit", + "search_excluded_subtrees/5k_dependencies", + ], + "ide-host": ["plugins/load_50", "plugins/cold_activation", "plugins/syntax_highlights_2k_lines"], + "ide-heap": ["heap/index_1m_objects", "heap/dominators_1m_random"], +}; + +const OBSERVE_ONLY: Readonly> = { + "syntax_2mb/outline_uncached": true, + "syntax_2mb/folding_uncached": true, + "index_100k/find_files/zzzz": true, + "index_100k/find_symbols/renderView": true, + "startup_20k/reopen_wait_idle": true, + "search_excluded_subtrees/5k_dependencies": true, +}; + +export function selectRustPackages(packages: readonly string[] = Object.keys(RUST_BENCHMARKS)): string[] { + if (packages.length === 0) throw new Error("empty Rust package selection"); + for (const p of packages) { + if (!Object.hasOwn(RUST_BENCHMARKS, p)) throw new Error(`unknown Rust package: ${JSON.stringify(p)}`); + } + return [...new Set(packages)]; +} + +export function rustPaths(root: string, env: { CARGO_TARGET_DIR?: string; CRITERION_HOME?: string }) { + const target = resolve(root, env.CARGO_TARGET_DIR ?? "target"); + return { target, criterion: resolve(root, env.CRITERION_HOME ?? join(target, "criterion")) }; +} + +export function rustBudgets(packages: readonly string[], budgets: Record): Record { + const selected = selectRustPackages(packages); + const ids = new Set(Object.values(RUST_BENCHMARKS).flat()); + for (const id of Object.keys(OBSERVE_ONLY)) { + if (!ids.has(id)) throw new Error(`unknown Rust observe-only classification: ${id}`); + } + for (const [id, value] of Object.entries(budgets)) { + if (!ids.has(id)) throw new Error(`unknown Rust budget ID: ${id}`); + if (Object.hasOwn(OBSERVE_ONLY, id)) throw new Error(`Rust observe-only ID has an absolute budget: ${id}`); + if (!Number.isFinite(value) || value < 0) throw new Error(`invalid Rust budget: ${id}`); + } + for (const id of ids) { + if (!Object.hasOwn(budgets, id) && !Object.hasOwn(OBSERVE_ONLY, id)) { + throw new Error(`missing Rust budget classification: ${id}`); + } + } + return Object.fromEntries( + selected + .flatMap((p) => RUST_BENCHMARKS[p]!) + .filter((id) => !Object.hasOwn(OBSERVE_ONLY, id)) + .map((id) => [`rust.${id}`, budgets[id]!]), + ); +} + +/** Read the selected workload only; fresh runs require both artifact files since `started`. */ +export function collectRustMetrics(dir: string, packages: readonly string[], started?: number): Record { + const selected = new Set(selectRustPackages(packages)); + const expected = new Set([...selected].flatMap((p) => RUST_BENCHMARKS[p]!)); + const owners = new Map(); + const groups = new Map(); + for (const [p, ids] of Object.entries(RUST_BENCHMARKS)) { + for (const id of ids) { + owners.set(id, p); + groups.set(id.split("/")[0]!, p); + } + } + const metrics: Record = {}; + function readNew(sub: string) { + // Criterion sanitizes slashes in ungrouped function names to underscores. + const top = relative(dir, sub).split(sep)[0]!; + const pathOwner = [...groups].find(([group]) => top === group || top.startsWith(`${group}_`))?.[1]; + if (pathOwner && !selected.has(pathOwner)) return; + const bench = join(sub, "new", "benchmark.json"); + const estimates = join(sub, "new", "estimates.json"); + if (!existsSync(bench)) { + if (existsSync(estimates) && (!pathOwner || selected.has(pathOwner))) { + throw new Error(`missing Criterion benchmark.json: ${sub}`); + } + return; + } + const metadata: unknown = JSON.parse(readFileSync(bench, "utf8")); + const id = metadata && typeof metadata === "object" && "full_id" in metadata ? metadata.full_id : undefined; + if (typeof id !== "string" || !id) { + throw new Error(`invalid Criterion full_id: ${bench}`); + } + const owner = owners.get(id) ?? groups.get(id.split("/")[0]!); + if (owner && !selected.has(owner)) return; + if (!expected.has(id)) throw new Error(`unknown selected Criterion ID: ${id}`); + if (Object.hasOwn(metrics, id)) throw new Error(`duplicate Criterion ID: ${id}`); + for (const file of [bench, estimates]) { + if (started !== undefined && statSync(file).mtimeMs < started) + throw new Error(`stale Criterion artifact: ${file}`); + } + const est: unknown = JSON.parse(readFileSync(estimates, "utf8")); + const mean = est && typeof est === "object" && "mean" in est ? est.mean : undefined; + const value = mean && typeof mean === "object" && "point_estimate" in mean ? mean.point_estimate : undefined; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + throw new Error(`invalid Criterion mean estimate: ${estimates}`); + } + metrics[id] = value / 1000; + } + function visit(path: string) { + if (!existsSync(path)) return; + readNew(path); + for (const entry of readdirSync(path, { withFileTypes: true })) { + if (entry.isDirectory() && !["new", "base", "report"].includes(entry.name)) visit(join(path, entry.name)); + } + } + visit(dir); + const missing = [...expected].filter((id) => !Object.hasOwn(metrics, id)); + if (missing.length) throw new Error(`missing selected Criterion IDs: ${missing.join(", ")}`); + return metrics; +} diff --git a/perf/run.ts b/perf/run.ts index 2554b0f0c..c59197b04 100644 --- a/perf/run.ts +++ b/perf/run.ts @@ -20,6 +20,7 @@ import { buildBundle, serveBundle } from "./lib/bundle.ts"; import { Harness, type Metrics, type Scenario } from "./lib/harness.ts"; import { topFunctions, type CpuProfile } from "./lib/profile.ts"; import { installInPage } from "./lib/inpage.ts"; +import { countOption } from "./lib/options.ts"; import { evaluate, loadBudgets, printReport, type ScenarioResult } from "./lib/report.ts"; import { median } from "./lib/stats.ts"; import { SCENARIOS } from "./scenarios.ts"; @@ -51,17 +52,28 @@ if (args.list) { process.exit(0); } -const runs = Math.max(1, Number(args.runs)); -const warmup = Math.max(0, Number(args.warmup)); -const cpu = Math.max(1, Number(args.cpu)); +const runs = countOption("runs", args.runs!, 1); +const warmup = countOption("warmup", args.warmup!, 0); +const cpu = Number(args.cpu); +if (!args.cpu?.trim() || !Number.isFinite(cpu) || cpu < 1) { + throw new Error("--cpu must be a finite number >= 1"); +} // Unminified builds keep function names readable in profiles; their bundle size is meaningless. const DIST = join(OUT, args.unminified ? "dist-unminified" : "dist"); -const only = args.only?.split(",").map((s) => s.trim()); -const scenarios = only ? SCENARIOS.filter((s) => only.includes(s.id)) : SCENARIOS; -if (only && scenarios.length !== only.length) { - const known = new Set(SCENARIOS.map((s) => s.id)); - throw new Error(`unknown scenario(s): ${only.filter((o) => !known.has(o)).join(", ")} (see --list)`); +const only = args.only === undefined ? undefined : [...new Set(args.only.split(",").map((s) => s.trim()))]; +const known = new Set(SCENARIOS.map((s) => s.id)); +if (known.size !== SCENARIOS.length) throw new Error("duplicate scenario ID"); +if (only?.some((id) => !known.has(id))) { + throw new Error(`unknown scenario(s): ${only.filter((id) => !known.has(id)).join(", ")} (see --list)`); } +const scenarios = only ? SCENARIOS.filter((s) => only.includes(s.id)) : SCENARIOS; +if (!scenarios.length) throw new Error("empty workload"); +const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); +for (const key of Object.keys(budgets.ui)) { + const id = key.slice(0, key.indexOf(".")); + if (id !== "bundle" && !known.has(id)) throw new Error(`budget references unknown scenario: ${key}`); +} +const expected = [...(args.unminified ? [] : ["bundle"]), ...scenarios.map((s) => s.id)]; function build() { buildBundle(ROOT, DIST, args.unminified ? ["--minify", "false"] : []); @@ -188,8 +200,9 @@ async function main() { const baseline = existsSync(baselineFile) ? (JSON.parse(readFileSync(baselineFile, "utf8")) as ScenarioResult[]) : null; - const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); + // Expectations were fixed before launch, independently of returned measurements. const report = evaluate(results, budgets.ui, baseline, { + expected, enforceBudgets: cpu === 1, tolerance: budgets.regressionTolerance, floor: budgets.regressionFloor, diff --git a/perf/rust.ts b/perf/rust.ts index a0de179a8..c34744bc9 100644 --- a/perf/rust.ts +++ b/perf/rust.ts @@ -8,15 +8,15 @@ * pnpm perf:rust -- --package ide-text --save-baseline */ import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { parseArgs } from "node:util"; import { evaluate, loadBudgets, printReport, type ScenarioResult } from "./lib/report.ts"; +import { collectRustMetrics, rustBudgets, rustPaths, selectRustPackages } from "./lib/rust.ts"; const ROOT = resolve(import.meta.dirname, ".."); -const TARGET = resolve(ROOT, process.env.CARGO_TARGET_DIR ?? "target"); +const { target: TARGET, criterion: CRITERION } = rustPaths(ROOT, process.env); const OUT = join(ROOT, "target", "perf"); -const PACKAGES = ["ide-text", "ide-language", "ide-index", "ide-search", "ide-host", "ide-heap"]; const { values: args } = parseArgs({ options: { @@ -27,50 +27,27 @@ const { values: args } = parseArgs({ }, }); -const packages = args.package ?? PACKAGES; +const packages = selectRustPackages(args.package); +const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); +const selectedBudgets = rustBudgets(packages, budgets.rust); const started = Date.now(); if (!args["no-run"]) { const r = spawnSync("cargo", ["bench", ...packages.flatMap((p) => ["-p", p]), "--benches"], { cwd: ROOT, stdio: "inherit", + env: { ...process.env, CARGO_TARGET_DIR: TARGET, CRITERION_HOME: CRITERION }, }); if (r.status !== 0) throw new Error("cargo bench failed"); } -/** Criterion results (`/new/{benchmark,estimates}.json`) → mean in µs. */ -function collect(dir: string, out: Record) { - if (!existsSync(dir)) return; - for (const entry of readdirSync(dir, { withFileTypes: true })) { - if (!entry.isDirectory() || entry.name === "report") continue; - const sub = join(dir, entry.name); - const bench = join(sub, "new", "benchmark.json"); - if (existsSync(bench) && (args["no-run"] || statSync(bench).mtimeMs >= started)) { - const { full_id } = JSON.parse(readFileSync(bench, "utf8")) as { full_id: string }; - const est = JSON.parse(readFileSync(join(sub, "new", "estimates.json"), "utf8")) as { - mean: { point_estimate: number }; - }; - out[full_id] = est.mean.point_estimate / 1000; - } - collect(sub, out); - } -} - -const metrics: Record = {}; -collect(join(TARGET, "criterion"), metrics); -if (Object.keys(metrics).length === 0) throw new Error(`no criterion results under ${join(TARGET, "criterion")}`); +const metrics = collectRustMetrics(CRITERION, packages, args["no-run"] ? undefined : started); mkdirSync(OUT, { recursive: true }); -const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); const results: ScenarioResult[] = [{ id: "rust", title: "criterion means (µs)", metrics }]; const baselineFile = join(OUT, "baseline-rust.json"); const baseline = existsSync(baselineFile) ? (JSON.parse(readFileSync(baselineFile, "utf8")) as ScenarioResult[]) : null; -// Only budgets of benches that ran: `--package` may select a subset. -const rustBudgets = Object.fromEntries( - Object.entries(budgets.rust) - .filter(([id]) => args["no-run"] || id in metrics || !args.package) - .map(([id, v]) => [`rust.${id}`, v]), -); -const report = evaluate(results, rustBudgets, baseline, { +const report = evaluate(results, selectedBudgets, baseline, { + expected: ["rust"], enforceBudgets: true, tolerance: budgets.regressionTolerance, floor: budgets.regressionFloor,