Repository navigation
Description
In a project with importHelpers or JSX, the language server rebuilds the whole program after every edit, so diagnostics after an ordinary edit take about 2.5x as long as tsgo's. Follow-up to #932: diagnostics after an edit was the one row there that stayed slower than tsgo. There is a fix in a PR on my fork, christianvuerings#10.
| time from edit to diagnostics, median of 5 sessions | tsrs mainfc384313 |
+ fix3e4b33da |
tsgo 7.1.0-beta |
|---|---|---|---|
| public reproduction, one character typed | 178.3 ms | 16.3 ms | 69.6 ms |
| public reproduction, text replaced, imports unchanged | 180.6 ms | 16.5 ms | 69.7 ms |
| our web monorepo, test file (15,117 files), a statement added | 358.9 ms | 40.9 ms | 143.5 ms |
| our web monorepo, component (6,782 files), a statement added | 177.3 ms | 23.6 ms | 78.1 ms |
| our web monorepo, typing one character at a time | 352.6 ms | 37.5 ms | 145.1 ms |
| an import added (still a full rebuild) | 352.2 ms | 350.9 ms | 145.0 ms |
Quiet 64-vCPU Linux x86_64 machine, 5 interleaved sessions per cell, time from didChange to the pull diagnostics response.
Why
Program::reuse_programrefuses to replace a file in place when it has a synthetic import (thetslibimport, the JSX runtime import), as Go does. UnderimportHelpersor JSX every module has one, so every edit pays for a full rebuild.- tsrs already has the option to keep those imports (
reuse_synthetic_imports, for--watch). The language server can't use it as is, because the imports' parent is the full build's version of the file, which it frees. - The full rebuild itself is also slower than tsgo's: the file loader works in rounds, one dependency level each, and with project references most pool threads sit idle at the end of each round.
The fix
3e4b33da gives the reused program its own synthetic imports for each file it replaced, parented to its version of the file and allocated with it, and turns reuse_synthetic_imports on in the language server. One commit, 5 files, +103/-23.
Same answers, against tsrs main on our web monorepo:
- Full-repo build: all 358,710 emitted files byte-identical.
- Language server: 1,004 of 1,004 responses identical; an editing session recording every answer: 1,581 of 1,581, also with freed memory poisoned.
- Command line: 600 of 600 outputs identical; fourslash: 4,149 passing, as on
main.
Still open: an edit that changes a file's imports still rebuilds the program, about 2.4x tsgo.
Reproduce
npm i typescript@7.1.0-beta tsrs@0.23.0-ts7.1.0-beta
node gen.mjs ws
node bench.mjs ws -- node_modules/@typescript/typescript-linux-x64/lib/tsc --lsp --stdio
node bench.mjs ws -- node_modules/@tsrs/linux-x64-gnu/tsrs --lsp --stdiogen.mjs writes 120 composite library projects in 6 layers, 5,000 node_modules packages, importHelpers, preserveSymlinks and moduleResolution: bundler (12,405 files in the edited project's program). bench.mjs drives the server over LSP and times each edit.
gen.mjs, bench.mjs and their README
README.md
# Diagnostics after an edit in a workspace of composite projects
A generated workspace and a driver for one number: after an edit, the time until the language server answers the
pull diagnostics request. They compare `tsrs --lsp --stdio` with the TypeScript 7 language server it ports
(`tsc --lsp --stdio` from `typescript@7.1.0-beta`, tsgo). Nothing here is specific to any machine or repository.
## What they show
In a project with `importHelpers: true` (or `jsx: react-jsx`), every module has a synthetic import: the helpers
module `tslib`, the JSX runtime module. Both servers rebuild the whole program after every edit of such a file,
because replacing one file in the program in place (`ReuseProgram`) is ruled out for files with synthetic imports.
In tsrs 0.23.0 that rebuild takes about twice as long as in tsgo.
## Run it
Requirements: Node.js 20 or newer, Linux or macOS.
```sh
mkdir edit-diagnostics && cd edit-diagnostics
# copy gen.mjs and bench.mjs here
npm i typescript@7.1.0-beta tsrs@0.23.0-ts7.1.0-beta
node gen.mjs ws # 120 library projects x 61 files, 6 layers, 5,000 node_modules packages
node bench.mjs ws -- node_modules/@typescript/typescript-linux-x64/lib/tsc --lsp --stdio
node bench.mjs ws -- node_modules/@tsrs/linux-x64-gnu/tsrs --lsp --stdio
node bench.mjs ws -- /path/to/tsrs/target/release/tsrs --lsp --stdio # a local build; set TSRS_LIB_PATH
```
The platform binaries are named so that the npm launcher is not timed; use the directory of your platform. A local
tsrs build finds the library files through `TSRS_LIB_PATH` (for example `node_modules/@tsrs/linux-x64-gnu`).
`bench.mjs` opens `packages/app/src/main.ts`, waits for its first pull diagnostics, then edits the file 30 times in
each of three ways and pulls diagnostics after every edit:
- `replace`: the whole text is replaced by the original text plus a trailing comment. The imports do not change.
- `insert`: one character is typed into a trailing comment (an incremental change). The imports do not change.
- `import`: an import of a module that does not exist is added at the top, and removed again by the next edit. The
imports change, so no server can keep the program.
For each way it prints the median of the round trip (`didChange` sent to the `textDocument/diagnostic` response),
the server's own `Program update for ... completed in` log line of that edit, its
`handled method 'textDocument/diagnostic'` line, and the server's CPU time per edit. Options: `--edits N`,
`--kinds replace,insert,import`, `--file <path>`, `--json out.json` (every sample), `--log server.log`.
## Generator parameters
`node gen.mjs <dir> [--name value ...]`. The same parameters always give the same files.
| parameter | default | meaning |
| --- | ---: | --- |
| `--projects` | 120 | library projects |
| `--files` | 60 | source files per library, plus its `index.ts` that re-exports them |
| `--depth` | 6 | layers of the reference graph; a library imports libraries of the next layer, the app references layer 1 |
| `--chain` | 0 | inside each library, file i imports file i-1 for the first N files (a deeper import graph) |
| `--imports` | 3 | next-layer libraries each library file imports |
| `--packages` | 5000 | `node_modules` packages (one `.d.ts` each) imported by the app |
| `--app-files` | 20 | files of the app project besides `main.ts` |
| `--extra-references` | 0 | referenced projects with one file nothing imports (more references, same program) |
| `--style` | `paths` | `paths`: imports go through a tsconfig path mapping to the sources; `packages`: through workspace symlinks in `node_modules` and the declaration output, mapped back to the sources by the project references |
| `--miss` | 0 | path-mapping candidates that do not exist, listed before the one that does |
| `--import-helpers` | `true` | `importHelpers`; with `false` the files have no synthetic import |
| `--jsx` | `false` | `main.tsx` with `jsx: react-jsx`, the other synthetic import |
| `--preserve-symlinks` | `true` | `preserveSymlinks` |
The default workspace has 12,405 files in the edited project's program (12,341 generated files plus `tslib` and the
default libraries) and 120 project references (20 direct).
## Measured
A 64-vCPU Linux x86_64 machine with nothing else running (other processes used under 1 core during every
session). 5 sessions per server, the servers interleaved, each session the median of 30 edits; the table has the
median of the 5 session medians, and the lowest and highest session in brackets. Edit to diagnostics as the client
sees it:
| edit | tsgo 7.1.0-beta | tsrs 0.23.0 |
| --- | ---: | ---: |
| `replace` | 74.3 ms [73.4, 76.3] | 154.0 ms [152.7, 154.7] |
| `insert` | 73.8 ms [71.1, 75.2] | 151.8 ms [151.2, 152.6] |
| `import` | 72.2 ms [71.8, 76.2] | 151.1 ms [149.6, 151.8] |
| server CPU per edit, `insert` | 1,463 ms | 1,148 ms |
| first diagnostics after opening the file | 186 ms | 232 ms |
A local build of tsrs main (`fc384313`, the 0.23.0 source) measures the same as the npm binary: 156.1, 153.4 and
153.4 ms.gen.mjs
#!/usr/bin/env node
// gen.mjs <dir> [--name value ...]
//
// Generates a workspace of composite TypeScript projects in which every edit of a source file makes the
// language server build the edited project's Program again from scratch (see README.md). Deterministic: the
// same parameters always give the same files. Nothing is random and nothing is read from the environment.
//
// Shape: one application project (packages/app, the file to edit is packages/app/src/main.ts) that references
// library projects arranged in layers. A library in layer k imports libraries of layer k+1. Every library has an
// index.ts that re-exports all its files, so the application's program contains every file of every library.
//
// Parameters (defaults in brackets):
// --projects N library projects [120]
// --files N source files per library, not counting its index.ts [60]
// --depth N layers of the reference graph; the application references layer 1 only [6]
// --chain N inside each library, file i imports file i-1 for the first N files, which makes the
// import graph N levels deeper (one more loader round per level in tsrs) [0]
// --imports N imports of next-layer libraries per library file [3]
// --packages N node_modules packages (one declaration file each) imported by the application [5000]
// --app-files N files of the application project besides main.ts [20]
// --extra-references N referenced projects with one file that nothing imports: more project references and
// tsconfig files without more program files [0]
// --style paths|packages how a project imports another: "paths" is a tsconfig path mapping to the source file
// (@ws/lib-1-000/src/index), "packages" is the package name through a node_modules
// symlink and the declaration output, which the project reference maps back to the
// source [paths]
// --miss N with --style paths: N path-mapping candidates that do not exist, listed before the
// one that does [0]
// --import-helpers B compilerOptions.importHelpers; with true every module gets a synthetic tslib import,
// so no edit can reuse the old program [true]
// --jsx B main is main.tsx compiled with "jsx": "react-jsx" (a synthetic JSX runtime import,
// the other way to rule out reuse) [false]
// --preserve-symlinks B compilerOptions.preserveSymlinks [true]
import fs from 'node:fs';
import path from 'node:path';
const argv = process.argv.slice(2);
const dir = argv[0];
if (!dir || dir.startsWith('--')) {
console.error(
'usage: gen.mjs <dir> [--projects N] [--files N] [--depth N] [--chain N] [--imports N]',
);
console.error(
' [--packages N] [--app-files N] [--extra-references N] [--style paths|packages] [--miss N]',
);
console.error(
' [--import-helpers true|false] [--jsx true|false] [--preserve-symlinks true|false]',
);
process.exit(1);
}
const opt = {
projects: 120,
files: 60,
depth: 6,
chain: 0,
imports: 3,
packages: 5000,
'app-files': 20,
'extra-references': 0,
style: 'paths',
miss: 0,
'import-helpers': true,
jsx: false,
'preserve-symlinks': true,
};
for (let i = 1; i < argv.length; i += 2) {
const name = argv[i].replace(/^--/, '');
if (!(name in opt)) throw new Error(`unknown parameter ${argv[i]}`);
const value = argv[i + 1];
opt[name] =
typeof opt[name] === 'number'
? Number(value)
: typeof opt[name] === 'boolean'
? value === 'true'
: value;
}
if (!['paths', 'packages'].includes(opt.style))
throw new Error('--style must be paths or packages');
const depth = Math.max(1, Math.min(opt.depth, opt.projects));
let written = 0;
const write = (p, s) => {
fs.mkdirSync(path.dirname(path.join(dir, p)), { recursive: true });
fs.writeFileSync(path.join(dir, p), s);
written++;
};
const json = (v) => JSON.stringify(v, null, 2) + '\n';
const pad = (i, n = 3) => String(i).padStart(n, '0');
// Libraries by layer: layer 1 is referenced by the application, the last layer imports nothing.
const layers = Array.from({ length: depth }, () => []);
for (let p = 0; p < opt.projects; p++)
layers[p % depth].push(`lib-${(p % depth) + 1}-${pad(Math.floor(p / depth))}`);
const extras = Array.from({ length: opt['extra-references'] }, (_, i) => `extra-${pad(i, 4)}`);
const id = (name) => name.replace(/-/g, '_');
// The specifier under which `from` imports the index of project `name`.
const specifier = (name) => (opt.style === 'paths' ? `@ws/${name}/src/index` : `@ws/${name}`);
write(
'package.json',
json({ name: 'edit-diagnostics-repro', private: true, workspaces: ['packages/*'] }),
);
const compilerOptions = {
target: 'es2022',
module: 'esnext',
moduleResolution: 'bundler',
strict: true,
composite: true,
declaration: true,
skipLibCheck: true,
importHelpers: opt['import-helpers'],
preserveSymlinks: opt['preserve-symlinks'],
};
if (opt.jsx) compilerOptions.jsx = 'react-jsx';
if (opt.style === 'paths')
compilerOptions.paths = {
'@ws/*': [...Array.from({ length: opt.miss }, (_, i) => `./missing-${i}/*`), './packages/*'],
};
write('tsconfig.base.json', json({ compilerOptions }));
write(
'tsconfig.json',
json({
files: [],
references: ['app', ...layers.flat(), ...extras].map((p) => ({ path: `packages/${p}` })),
}),
);
// The helpers module that importHelpers resolves for every module.
write(
'node_modules/tslib/package.json',
json({ name: 'tslib', version: '2.8.1', types: 'tslib.d.ts' }),
);
write(
'node_modules/tslib/tslib.d.ts',
`export declare function __awaiter(thisArg: unknown, args: unknown, P: unknown, generator: unknown): unknown;
export declare function __rest(source: unknown, keys: readonly string[]): unknown;
export declare function __spreadArray(to: unknown[], from: unknown[], pack?: boolean): unknown[];
`,
);
if (opt.jsx) {
write(
'node_modules/react/package.json',
json({ name: 'react', version: '19.0.0', types: 'index.d.ts' }),
);
write(
'node_modules/react/index.d.ts',
'export declare function useState<T>(initial: T): [T, (next: T) => void];\n',
);
write(
'node_modules/react/jsx-runtime.d.ts',
`export declare function jsx(type: unknown, props: unknown, key?: unknown): JSX.Element;
export declare function jsxs(type: unknown, props: unknown, key?: unknown): JSX.Element;
export declare const Fragment: unique symbol;
export declare namespace JSX {
interface Element { readonly type: unknown; readonly props: unknown }
interface IntrinsicElements { [name: string]: Record<string, unknown> }
}
`,
);
}
for (let i = 0; i < opt.packages; i++) {
const name = `pkg-${pad(i, 4)}`;
write(`node_modules/${name}/package.json`, json({ name, version: '1.0.0', types: 'index.d.ts' }));
write(
`node_modules/${name}/index.d.ts`,
`export declare function ${id(name)}(input: number): number;\n`,
);
}
function project(name, references) {
write(
`packages/${name}/tsconfig.json`,
json({
extends: '../../tsconfig.base.json',
compilerOptions: { rootDir: 'src', outDir: 'dist' },
include: ['src'],
references: references.map((r) => ({ path: `../${r}` })),
}),
);
write(
`packages/${name}/package.json`,
json({ name: `@ws/${name}`, version: '1.0.0', types: 'dist/index.d.ts' }),
);
if (opt.style === 'packages') {
fs.mkdirSync(path.join(dir, 'node_modules/@ws'), { recursive: true });
fs.symlinkSync(`../../packages/${name}`, path.join(dir, 'node_modules/@ws', name));
}
}
// Libraries.
layers.forEach((names, layer) => {
const next = layers[layer + 1] ?? [];
names.forEach((name, n) => {
// The next-layer libraries this one imports: `imports` of them, spread over the layer.
const deps = [];
for (let k = 0; k < Math.min(opt.imports, next.length); k++)
deps.push(next[(n + k) % next.length]);
project(name, deps);
const exports = [];
for (let f = 0; f < opt.files; f++) {
const fn = `${id(name)}_f${pad(f, 4)}`;
const lines = [];
const terms = [String(f)];
deps.forEach((dep, k) => {
const depFn = `${id(dep)}_f${pad((f + k) % opt.files, 4)}`;
lines.push(`import { ${depFn} } from '${specifier(dep)}';`);
terms.push(`${depFn}(input)`);
});
if (f > 0 && f <= opt.chain) {
const prev = `${id(name)}_f${pad(f - 1, 4)}`;
lines.push(`import { ${prev} } from './f${pad(f - 1, 4)}';`);
terms.push(`${prev}(input)`);
}
write(
`packages/${name}/src/f${pad(f, 4)}.ts`,
`${lines.join('\n')}${lines.length ? '\n\n' : ''}export function ${fn}(input: number): number {\n return input + ${terms.join(' + ')};\n}\n`,
);
exports.push(`export * from './f${pad(f, 4)}';`);
}
write(`packages/${name}/src/index.ts`, exports.join('\n') + '\n');
});
});
for (const name of extras) {
project(name, []);
write(`packages/${name}/src/index.ts`, `export const ${id(name)} = 1;\n`);
}
// The application: main imports every layer-1 library; the other files import the node_modules packages.
project('app', [...layers[0], ...extras]);
const appFiles = opt['app-files'];
for (let a = 0; a < appFiles; a++) {
const lines = [];
const terms = [String(a)];
for (let i = a; i < opt.packages; i += appFiles) {
const name = `pkg-${pad(i, 4)}`;
lines.push(`import { ${id(name)} } from '${name}';`);
terms.push(`${id(name)}(input)`);
}
write(
`packages/app/src/a${pad(a, 4)}.ts`,
`${lines.join('\n')}${lines.length ? '\n\n' : ''}export function app_a${pad(a, 4)}(input: number): number {\n return input + ${terms.join(' + ')};\n}\n`,
);
}
{
const lines = [];
const terms = ['0'];
for (const name of layers[0]) {
lines.push(`import { ${id(name)}_f0000 } from '${specifier(name)}';`);
terms.push(`${id(name)}_f0000(input)`);
}
for (let a = 0; a < appFiles; a++) {
lines.push(`import { app_a${pad(a, 4)} } from './a${pad(a, 4)}';`);
terms.push(`app_a${pad(a, 4)}(input)`);
}
const body = `export function main(input: number): number {\n return ${terms.join(' +\n ')};\n}\n`;
if (opt.jsx)
write(
'packages/app/src/main.tsx',
`${lines.join('\n')}\n\n${body}\nexport function View(props: { readonly input: number }) {\n return <p>{main(props.input)}</p>;\n}\n`,
);
else write('packages/app/src/main.ts', `${lines.join('\n')}\n\n${body}`);
}
const libraryFiles = opt.projects * (opt.files + 1);
const programFiles = libraryFiles + appFiles + 1 + opt.packages;
console.log(
JSON.stringify({
dir: path.resolve(dir),
parameters: { ...opt, depth },
file: `packages/app/src/main.${opt.jsx ? 'tsx' : 'ts'}`,
projectReferences: {
direct: layers[0].length + extras.length,
all: opt.projects + extras.length,
},
expectedProgramFiles: `${programFiles} plus tslib${opt.jsx ? ', the JSX runtime' : ''} and the default library files`,
filesWritten: written,
}),
);bench.mjs
#!/usr/bin/env node
// bench.mjs <workspace> [--file packages/app/src/main.ts] [--edits 30] [--kinds replace,insert,import]
// [--json out.json] [--log server.log] -- <language server command...>
//
// Starts the language server in <workspace>, opens one file, waits for its first pull diagnostics, then edits
// the file --edits times in three ways and pulls diagnostics after every edit:
// replace the whole text is replaced by the original text plus a trailing comment
// insert one character is inserted into a trailing comment (an incremental change)
// import an import of a missing module is added at the top, then removed again (the imports change)
// For each way it prints the median of
// - the round trip measured here: textDocument/didChange sent -> textDocument/diagnostic response received,
// - the server's own "Program update for <tsconfig> completed in <time>" log line of that edit,
// - the server's own "handled method 'textDocument/diagnostic' (<id>) in <time>" log line.
// The two servers (TypeScript 7 `tsc --lsp --stdio` and `tsrs --lsp --stdio`) print the same log lines.
// The server writes the log block of an edit asynchronously, so blocks are paired with edits by order: every
// diagnostics request that follows a change produces exactly one "Cloning snapshot" block.
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
const argv = process.argv.slice(2);
const split = argv.indexOf('--');
if (split < 1 || split === argv.length - 1) {
console.error(
'usage: bench.mjs <workspace> [--file f] [--edits n] [--kinds replace,insert,import] [--json out.json] [--log file] -- <server command...>',
);
process.exit(1);
}
const root = path.resolve(argv[0]);
const cmd = argv.slice(split + 1);
const flag = (name, fallback) => {
const i = argv.indexOf(name);
return i > 0 && i < split ? argv[i + 1] : fallback;
};
const relFile = flag(
'--file',
fs.existsSync(path.join(root, 'packages/app/src/main.tsx'))
? 'packages/app/src/main.tsx'
: 'packages/app/src/main.ts',
);
const EDITS = Number(flag('--edits', 30));
const KINDS = flag('--kinds', 'replace,insert,import').split(',');
const jsonOut = flag('--json', '');
const logFile = flag('--log', '');
const uri = 'file://' + path.join(root, relFile);
const base = fs.readFileSync(path.join(root, relFile), 'utf8');
// Durations as Go's time.Duration and Rust's Duration debug format print them: 121.8ms, 414.5µs, 1.2s.
const UNIT = { ns: 1e-6, µs: 1e-3, us: 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
const durMs = (s) =>
[...s.matchAll(/([\d.]+)(ns|µs|us|ms|s|m|h)/g)].reduce(
(a, m) => a + Number(m[1]) * UNIT[m[2]],
0,
);
const DUR = '((?:[\\d.]+(?:ns|µs|us|ms|s|m|h))+)';
const RE_PROGRAM = new RegExp(`Program update for (.+) completed in ${DUR}`, 'g');
const RE_HANDLED = new RegExp(`handled method 'textDocument/diagnostic' \\((\\d+)\\) in ${DUR}`);
const proc = spawn(cmd[0], cmd.slice(1), { cwd: root, stdio: ['pipe', 'pipe', 'ignore'] });
proc.on('error', (e) => {
console.error(`cannot start ${cmd[0]}: ${e.message}`);
process.exit(1);
});
let exited = false;
proc.on('exit', () => {
exited = true;
for (const res of pending.values()) res({ error: { code: 'server exited' } });
});
const clones = []; // one entry per "Cloning snapshot" block caused by a diagnostics request
const handledMs = new Map();
const handledWaiters = new Map();
let programFiles = null,
projectName = null;
function onLog(message) {
if (logFile) fs.appendFileSync(logFile, message + '\n');
let m;
if (message.includes('======== Cloning snapshot')) {
if (/Reason: RequestedLanguageService/.test(message))
clones.push([...message.matchAll(RE_PROGRAM)].reduce((a, p) => a + durMs(p[2]), 0) || null);
} else if ((m = RE_HANDLED.exec(message))) {
handledMs.set(Number(m[1]), durMs(m[2]));
handledWaiters.get(Number(m[1]))?.();
} else if ((m = /Project '(.+)'\n\tFiles \((\d+)\)/.exec(message))) {
// The server can load more than one project (a solution tsconfig above the file has no files): keep the largest.
if (programFiles == null || Number(m[2]) > programFiles) {
projectName = m[1];
programFiles = Number(m[2]);
}
}
}
let buf = Buffer.alloc(0),
nextId = 0;
const pending = new Map();
proc.stdout.on('data', (d) => {
buf = Buffer.concat([buf, d]);
for (;;) {
const h = buf.indexOf('\r\n\r\n');
if (h < 0) return;
const len = Number(/Content-Length: (\d+)/i.exec(buf.subarray(0, h).toString())[1]);
if (buf.length < h + 4 + len) return;
const msg = JSON.parse(buf.subarray(h + 4, h + 4 + len).toString());
buf = buf.subarray(h + 4 + len);
if (msg.method === 'window/logMessage') onLog(msg.params.message);
if (msg.id != null && msg.method)
// A request from the server (workspace/configuration and the like): answer with nothing configured.
send({
jsonrpc: '2.0',
id: msg.id,
result:
msg.method === 'workspace/configuration'
? (msg.params.items || []).map(() => null)
: null,
});
else if (msg.id != null && pending.has(msg.id)) {
pending.get(msg.id)(msg);
pending.delete(msg.id);
}
}
});
function send(m) {
if (exited) return;
const b = Buffer.from(JSON.stringify(m));
proc.stdin.write(`Content-Length: ${b.length}\r\n\r\n`);
proc.stdin.write(b);
}
const notify = (method, params) => send({ jsonrpc: '2.0', method, params });
function request(method, params) {
const id = ++nextId;
return new Promise((res) => {
if (exited) return res({ id, error: { code: 'server exited' } });
pending.set(id, (m) => res({ ...m, id }));
send({ jsonrpc: '2.0', id, method, params });
});
}
// The "handled method" line of a request arrives right after its response; waiting for it (at most 400 ms)
// keeps the server work of one edit out of the next edit's measurement.
const handled = (id) =>
handledMs.has(id)
? Promise.resolve()
: new Promise((res) => {
const t = setTimeout(res, 400);
handledWaiters.set(id, () => {
clearTimeout(t);
res();
});
});
function cpuSeconds() {
try {
const s = fs.readFileSync(`/proc/${proc.pid}/stat`, 'utf8');
const f = s.slice(s.lastIndexOf(')') + 2).split(' ');
return (Number(f[11]) + Number(f[12])) / 100; // 100 clock ticks per second on Linux
} catch {
return null; // not Linux
}
}
let version = 1,
text = base,
diagSeq = 0;
function change(contentChanges, newText) {
text = newText;
notify('textDocument/didChange', { textDocument: { uri, version: ++version }, contentChanges });
}
async function diagnostics() {
const seq = diagSeq++;
const res = await request('textDocument/diagnostic', { textDocument: { uri } });
if (res.error) throw new Error(`textDocument/diagnostic failed: ${JSON.stringify(res.error)}`);
return { seq, id: res.id, count: (res.result?.items || []).length };
}
const init = await request('initialize', {
processId: process.pid,
rootUri: 'file://' + root,
workspaceFolders: [{ uri: 'file://' + root, name: path.basename(root) }],
capabilities: {
textDocument: { diagnostic: {} },
workspace: { configuration: true, workspaceFolders: true },
},
});
if (init.error) throw new Error(`initialize failed: ${JSON.stringify(init.error)}`);
notify('initialized', {});
const t0 = performance.now();
notify('textDocument/didOpen', {
textDocument: {
uri,
languageId: relFile.endsWith('x') ? 'typescriptreact' : 'typescript',
version,
text: base,
},
});
const first = await diagnostics();
const firstMs = performance.now() - t0;
await handled(first.id);
const kinds = {
// The whole text again, with a different trailing comment each time.
replace: (i) => {
const next = `${base}\n// edit ${i}\n`;
change([{ text: next }], next);
},
// One more character at the end of a trailing comment.
insert: (i) => {
if (i === 0) return (change([{ text: `${base}\n// c` }], `${base}\n// c`), false);
const lines = text.split('\n');
const position = { line: lines.length - 1, character: lines.at(-1).length };
change([{ range: { start: position, end: position }, text: 'x' }], text + 'x');
},
// An import of a module that does not exist, added at the top and removed again by the next edit. The file's
// imports change every time, so no server can reuse the program: this is the full rebuild.
import: (i) => {
const next = i % 2 === 0 ? `import './no-such-module';\n${base}` : base;
change([{ text: next }], next);
},
};
const samples = {};
for (const [kind, edit] of Object.entries(kinds).filter(([k]) => KINDS.includes(k))) {
const rows = (samples[kind] = { clientMs: [], seq: [], id: [], diagnostics: [] });
const cpu0 = cpuSeconds();
let timed = 0;
for (let i = 0; timed < EDITS; i++) {
const t = performance.now();
const untimed = edit(i) === false; // the insert kind first puts its comment in place
const d = await diagnostics();
const ms = performance.now() - t;
await handled(d.id);
if (untimed) continue;
timed++;
rows.clientMs.push(ms);
rows.seq.push(d.seq);
rows.id.push(d.id);
rows.diagnostics.push(d.count);
}
const cpu1 = cpuSeconds();
rows.serverCpuMsPerEdit = cpu0 == null ? null : ((cpu1 - cpu0) * 1000) / EDITS;
change([{ text: base }], base);
await handled((await diagnostics()).id);
}
// Give the last asynchronous log blocks time to arrive, then pair block k with diagnostics request k.
for (let i = 0; i < 40 && clones.length < diagSeq; i++) await new Promise((r) => setTimeout(r, 50));
const paired = clones.length === diagSeq;
const median = (a) => {
const s = a.filter((v) => v != null).sort((x, y) => x - y);
if (!s.length) return null;
return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
const f1 = (v) => (v == null ? 'n/a' : v.toFixed(1));
console.log(
`server ${init.result?.serverInfo?.name ?? '?'} ${init.result?.serverInfo?.version ?? ''} (${cmd.join(' ')})`,
);
console.log(`file ${relFile}`);
console.log(`program ${programFiles ?? '?'} files, ${projectName ?? '?'}`);
console.log(`first diagnostics ${f1(firstMs)} ms (loads the project)`);
const report = {
cmd,
workspace: root,
file: relFile,
serverInfo: init.result?.serverInfo ?? null,
programFiles,
firstDiagnosticsMs: firstMs,
edits: EDITS,
paired,
// CPU seconds of the server and of this driver for the whole run (Linux only), for noise accounting.
serverCpuS: cpuSeconds(),
driverCpuS: (process.cpuUsage().user + process.cpuUsage().system) / 1e6,
kinds: {},
};
for (const [kind, rows] of Object.entries(samples)) {
rows.programUpdateMs = rows.seq.map((s) => (paired ? clones[s] : null));
rows.handledMs = rows.id.map((id) => handledMs.get(id) ?? null);
const row = {
clientMs: median(rows.clientMs),
programUpdateMs: median(rows.programUpdateMs),
handledMs: median(rows.handledMs),
serverCpuMsPerEdit: rows.serverCpuMsPerEdit,
};
report.kinds[kind] = { median: row, samples: rows };
console.log(
`${kind.padEnd(8)} median of ${EDITS} edits: edit to diagnostics ${f1(row.clientMs)} ms` +
` | server "Program update" ${f1(row.programUpdateMs)} ms | server "handled method" ${f1(row.handledMs)} ms` +
` | server CPU per edit ${f1(row.serverCpuMsPerEdit)} ms`,
);
}
if (!paired)
console.log(
`note: ${clones.length} snapshot clone blocks for ${diagSeq} diagnostics requests, server times not attributed`,
);
if (jsonOut) fs.writeFileSync(jsonOut, JSON.stringify(report, null, 1));
await Promise.race([request('shutdown'), new Promise((r) => setTimeout(r, 3000))]);
notify('exit');
proc.stdin.end();
setTimeout(() => {
proc.kill('SIGKILL');
process.exit(0);
}, 500);Written with Claude Code on behalf of Christian Vuerings.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
oxc-captain commentedon Nov 9, 2026
Triage failed unexpectedly (attempt 1 of 3).
Run: https://github.com/oxc-project/tsrs/actions/runs/42637968192
I can retry if a new comment provides more information or asks me to try again.
Error:
christianvuerings commentedon Nov 9, 2026
fyi @maschwenk