Visual Studio Code, rebuilt in Rust
Rust
docs(performance): add the budgets and the gate that checks a bench run
rokarturc9b2728a4316
diff --git a/docs/performance.md b/docs/performance.mdnew file mode 100644index 00000000000..6d2323f85a9--- /dev/null+++ b/docs/performance.md@@ -0,0 +1,94 @@+# Performance++"Fast" is a property the project checks, not a hope. This file has the budgets the port holds today, the rules that keep hot paths fast, how to measure, and the gates that fail on a regression. [ARCHITECTURE.md](../ARCHITECTURE.md) has the map of the code.++The targets are two editors. VS Code 1.148.0 is the floor: the port must not be worse on a budget, and one budget is ([idle CPU](#whole-app-measured-from-outside)). Zed is the bar for a native editor: the port must be at the same level or better. That comparison has no measurement yet ([Zed](#zed)).++## Budgets++### Whole app, measured from outside++`port/tools/bench` starts the packaged release app on the VS Code checkout (21,627 files) and measures from outside the process. The budgets are the medians of `port/results/benchmark.md`, kept in `port/budgets.json` with a noise margin per metric.++| Metric | Budget | Margin | VS Code 1.148.0 |+|---|---|---|---|+| Window with the folder (`window_s`) | 0.66 s | 30% | 0.67 s |+| Ready, CPU settled (`ready_s`) | 2.89 s | 30% | 5.13 s |+| CPU time until ready (`cpu_s`) | 2.42 s | 25% | 7.75 s |+| Idle CPU, 60 to 90 s after launch (`idle_pct`) | 0.5% of a core | 50% | 0.2% |+| Quit (`quit_s`) | 0.13 s | 50% | 0.23 s |+| Peak footprint, all processes (`peak_footprint_mib`) | 488 MiB | 10% | 1042 MiB |+| Peak RSS, all processes (`peak_rss_mib`) | 755 MiB | 10% | 1753 MiB |+| Footprint at 90 s (`footprint_mib`) | 223 MiB | 10% | 584 MiB |+| Of that, the extension host (`exthost_mib`) | 78 MiB | 10% | 108 MiB |++The margins come from the spread of the samples in `port/results/benchmark.md`. Times vary with the load of the machine, memory does not. The medians come from a machine with a load of 22 to 62, so a quiet machine has room under the time budgets. Idle CPU is the one budget where VS Code is ahead.++### Frame times, measured inside tests++| Budget | Gate | Check |+|---|---|---|+| Typing in a 50,000-line TypeScript file | Under 16 ms per edit at p95 | `app/src/syntax.rs::typing_latency_on_a_large_file` |+| Comment and trim whitespace on that file | Under 16 ms | the same test |+| Scroll frame: Explorer, editor, Extensions, Settings | Under 8 ms at the median and at p95 | `app/src/workbench/scroll_frame_time.rs` |+| A change inside one part draws only that part | Render counts | `app/src/workbench/part_view/tests.rs` |++16 ms is one frame at 60 Hz. 8 ms is one frame at 120 Hz. The gate values are constants in the tests, so the test is the one place to change them.++### No budget yet++Terminal throughput, terminal typing latency, time to open a large file, search time and memory with many editors open have no number and no gate. A budget for one of them starts with a measurement in `port/notes.md`.++### Zed++There is no measurement against Zed. Two things are missing:++- `port/tools/bench` gives each app VS Code's arguments (`--disable-workspace-trust`, `--extensions-dir`). Zed does not take them, so the tool needs the arguments per app.+- Zed is not installed on the machine that runs the benchmark.++With both, one run of `port/tools/bench` with the two apps gives the medians of each. `port/tools/bench-check.ts <run.tsv> <app> <reference>` then fails where the port is behind the reference in that run. The `against` object of `port/budgets.json` holds a ratio per reference and metric for a difference that is a decision. Frame times need a second method, because the headless tests of the port do not run Zed: the same scroll input in both windows and a sample of the main thread of each.++## Rules for hot paths++A hot path is code that runs for each frame, each key or each scroll event: `render` functions, `app/src/workbench/keyboard.rs::key_context`, list rows, the editor's lines in view, tokenization.++1. No I/O on the main thread in a hot path. No file read, no `stat`, no process start, no lock that another thread holds across I/O. Do the work on the background executor or a thread, and bring the result back with `cx.spawn`.+2. Work in proportion to what is in view, not to what exists. A list lays out the rows in view. The editor shapes the lines in view. The minimap and the overview ruler read their own viewport.+3. Compute once where the state changes, not each time it is read. A regex is compiled once. A value derived from settings is kept until the settings change. A folder listing is kept until its modification time changes (`app/src/explorer.rs::FileTree`).+4. Notify the smallest view. `cx.notify()` on the `Workbench` draws every part. A scroll, a cursor blink or a late answer for one editor notifies its part view (`app/src/workbench/part_view.rs::notify_editor_view`). Notify only after a real change.+5. No allocation storm per frame. Do not build a `Vec` or a `String` per row or per token for data that did not change. Keep it with the state.+6. Tokenize and parse in slices. Long work on a document yields, runs in the background, or uses the cheap path upstream uses.+7. Measure before and after. A change to a hot path comes with the numbers of its gate from before and after the change, from the same machine in the same hour.++Each rule has a regression behind it. `port/notes.md` ("Benchmarks", "Scheduling differences") has the cases: 14 regexes compiled per row made a settings scroll frame take 37 ms. A folder read on each `key_context` call made an Explorer frame take 36 ms where 13 ms was possible. A notify of the `Workbench` for an inlay hint answer drew every part on 78 of 87 scroll frames.++## How to measure++Measure a release build. The debug profile builds the port's crates without optimization (`native/Cargo.toml`), so a debug build is much slower and points at the wrong places.++- The whole app: `port/tools/bench`. Its header has the method. `port/results/benchmark.md` has the full command and how to read the numbers.+- Frame times without a window: the ignored tests of [Budgets](#frame-times-measured-inside-tests), with `cargo test --release -p app -- --ignored <name> --nocapture`. They draw a real workbench without a GPU.+- A benchmark of one GPUI path with Criterion: the skill in `.agents/skills/gpui-bench` has the rules. The main one: no `test-support` feature in a benchmark, or it measures test code.+- Where the time goes: `sample <pid>` or Instruments (Time Profiler, `xctrace record --template 'Time Profiler'`) on the release app. For "who caused this draw", add `#[track_caller]` logging to `notify` for the run.+- Startup phases: `Developer: Startup Performance` in the app shows the `code/...` marks of `app/src/perf.rs`.++The machine is shared, and its load changes a time by about 30%. Check the load before a timing run. `port/tools/bench-check.ts` prints a note when the load of the run was over 10: a time over its budget is then no result, and the run must be done again. A memory number is a result at any load.++## The gates++| Gate | Command | Fails when |+|---|---|---|+| Whole-app budgets | `port/tools/bench > run.tsv`, then `bun port/tools/bench-check.ts run.tsv` | A median is over its budget by more than its margin |+| Typing | `cargo test --release -p app -- --ignored typing_latency_on_a_large_file --nocapture` | p95 per edit is 16 ms or more |+| Scroll frames | `cargo test --release -p app -- --ignored scroll_frame_time --nocapture --test-threads=1` | A median or p95 is 8 ms or more |+| Render counts | `cargo test -p app part_view` | A part draws that did not change |++`port/tools/bench-check.ts` reads the output of `port/tools/bench` and `port/budgets.json`. It prints each metric with its limit and exits 1 on a failure. `port/tools/bench-check.test.ts` shows it red on a planted regression.++Where the gates run:++- On the Studio, by hand, before a release and after a change to a hot path. The three timing gates need a release build and a quiet machine.+- In a CI run only the render counts can run, with the other tests. They count draws, so they do not depend on the speed of the runner.+- Timing gates do not run on GitHub runners. A shared runner varies by more than the margins. A gate that fails at random gets ignored.++A budget changes only with a measurement. To lower one after an improvement, run the bench, put the new medians in `port/budgets.json` and in `port/results/benchmark.md`, in one commit. To raise one, the commit says what was bought with the cost.diff --git a/port/budgets.json b/port/budgets.jsonnew file mode 100644index 00000000000..188a3c8c0ac--- /dev/null+++ b/port/budgets.json@@ -0,0 +1,16 @@+{+ "measured": "port/results/benchmark.md: the packaged release app on a Mac Studio (M1 Max, 32 GB), the VS Code 1.148.0 checkout open, median of 5 runs of port/tools/bench",+ "max_load": 10,+ "metrics": {+ "window_s": { "budget": 0.66, "margin": 0.3 },+ "ready_s": { "budget": 2.89, "margin": 0.3 },+ "cpu_s": { "budget": 2.42, "margin": 0.25 },+ "idle_pct": { "budget": 0.5, "margin": 0.5 },+ "quit_s": { "budget": 0.13, "margin": 0.5 },+ "peak_footprint_mib": { "budget": 488, "margin": 0.1 },+ "peak_rss_mib": { "budget": 755, "margin": 0.1 },+ "footprint_mib": { "budget": 223, "margin": 0.1 },+ "exthost_mib": { "budget": 78, "margin": 0.1 }+ },+ "against": {}+}diff --git a/port/tools/bench-check.test.ts b/port/tools/bench-check.test.tsnew file mode 100644index 00000000000..5cb83dc1fda--- /dev/null+++ b/port/tools/bench-check.test.ts@@ -0,0 +1,42 @@+import { expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++// The medians of port/results/benchmark.md, which port/budgets.json holds as the budgets.+const held = { window_s: 0.66, ready_s: 2.89, cpu_s: 2.42, idle_pct: 0.5, exthost_mib: 78, quit_s: 0.13, peak_footprint_mib: 488, peak_rss_mib: 755, footprint_mib: 223, load: 3 };++function check(runs: Record<string, Record<string, number>>, ...args: string[]) {+ const dir = mkdtempSync(join(tmpdir(), 'bench-check-test-'));+ const rows = Object.entries(runs).flatMap(([app, metrics]) => Object.entries(metrics).map(([metric, median]) => `${app}\t${metric}\t${median}\t${median} `));+ writeFileSync(join(dir, 'run.tsv'), ['app\tmetric\tmedian\tsamples', ...rows].join('\n'));+ const run = Bun.spawnSync(['bun', join(import.meta.dir, 'bench-check.ts'), join(dir, 'run.tsv'), ...args]);+ rmSync(dir, { recursive: true });+ return { code: run.exitCode, out: run.stdout.toString() };+}++test('the run the budgets were taken from passes', () => {+ const { code, out } = check({ vsrustium: held });+ expect(out).toContain('every metric is within its budget');+ expect(code).toBe(0);+});++test('noise inside the margin passes, a regression past it fails', () => {+ expect(check({ vsrustium: { ...held, window_s: 0.8 } }).code).toBe(0);+ const slow = check({ vsrustium: { ...held, window_s: 1.2, footprint_mib: 260 } });+ expect(slow.out).toContain('FAIL window_s: 1.2 is over the budget 0.66 by more than 30%');+ expect(slow.out).toContain('FAIL footprint_mib: 260 is over the budget 223 by more than 10%');+ expect(slow.code).toBe(1);+});++test('a run without the app fails instead of passing empty', () => {+ expect(check({ other: held }).code).toBe(1);+});++test('with a reference app of the same run, a metric behind it fails', () => {+ const level = check({ vsrustium: held, zed: held }, 'vsrustium', 'zed');+ expect(level.code).toBe(0);+ const behind = check({ vsrustium: held, zed: { ...held, footprint_mib: 150 } }, 'vsrustium', 'zed');+ expect(behind.out).toContain('FAIL footprint_mib: 223 is behind zed (150) by more than the allowed x1 +10%');+ expect(behind.code).toBe(1);+});diff --git a/port/tools/bench-check.ts b/port/tools/bench-check.tsnew file mode 100644index 00000000000..80a5a1f6b26--- /dev/null+++ b/port/tools/bench-check.ts@@ -0,0 +1,58 @@+#!/usr/bin/env bun+// The performance gate (docs/performance.md): compares one run of port/tools/bench with the budgets of+// port/budgets.json and exits 1 when a median is over its budget by more than the metric's noise margin.+// port/tools/bench > run.tsv && bun port/tools/bench-check.ts run.tsv [app] [reference app]+// `app` is the bench name of the port (default vsrustium). With a reference app of the same run (zed), each+// median must also stay within the reference's median times the ratio budgets.json allows for it (1 when it names+// none: as good as the reference). Both apps ran in turns on one machine, so its load cancels out.+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const [runFile, app = 'vsrustium', reference] = process.argv.slice(2);+if (!runFile) {+ console.error('usage: bun port/tools/bench-check.ts <run.tsv> [app] [reference app]');+ process.exit(2);+}+const budgets = JSON.parse(readFileSync(process.env.BUDGETS ?? join(import.meta.dir, '../budgets.json'), 'utf8'));+const medians = new Map<string, number>();+for (const line of readFileSync(runFile, 'utf8').split('\n').slice(1)) {+ const [name, metric, median] = line.split('\t');+ if (median) {+ medians.set(`${name} ${metric}`, Number(median));+ }+}++const failures: string[] = [];+for (const [metric, { budget, margin }] of Object.entries<{ budget: number; margin: number }>(budgets.metrics)) {+ const measured = medians.get(`${app} ${metric}`);+ if (measured === undefined) {+ failures.push(`${metric}: the run has no row for ${app}`);+ continue;+ }+ const limit = budget * (1 + margin);+ const verdict = measured > limit ? 'OVER' : 'ok';+ console.log(`${verdict}\t${metric}\t${measured}\tbudget ${budget} +${margin * 100}% = ${limit.toFixed(2)}`);+ if (measured > limit) {+ failures.push(`${metric}: ${measured} is over the budget ${budget} by more than ${margin * 100}%`);+ }+ const other = reference && medians.get(`${reference} ${metric}`);+ if (!other) {+ continue;+ }+ const ratio = budgets.against?.[reference]?.[metric] ?? 1;+ const ceiling = other * ratio * (1 + margin);+ const behind = measured > ceiling ? 'BEHIND' : 'ok';+ console.log(`${behind}\t${metric}\t${measured}\t${reference} ${other} x${ratio} +${margin * 100}% = ${ceiling.toFixed(2)}`);+ if (measured > ceiling) {+ failures.push(`${metric}: ${measured} is behind ${reference} (${other}) by more than the allowed x${ratio} +${margin * 100}%`);+ }+}+const load = medians.get(`${app} load`);+if (load !== undefined && load > budgets.max_load) {+ console.log(`note: the 1-minute load was ${load} (over ${budgets.max_load}). A time over its budget at this load is no result: run again on a quiet machine.`);+}+for (const failure of failures) {+ console.log(`FAIL ${failure}`);+}+console.log(failures.length === 0 ? 'bench-check: every metric is within its budget' : `bench-check: ${failures.length} over budget`);+process.exit(failures.length > 0 ? 1 : 0);