run.mjs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { execFileSync, spawnSync } from 'node:child_process';
  2. import { readFileSync, writeFileSync, mkdirSync, appendFileSync, existsSync } from 'node:fs';
  3. import { cpus, totalmem, platform, release, arch } from 'node:os';
  4. import { resolve, join } from 'node:path';
  5. import { fileURLToPath } from 'node:url';
  6. import { parseArgs } from 'node:util';
  7. import { createHash } from 'node:crypto';
  8. import { compareRuns, renderReport, selectScenarios } from './report.mjs';
  9. const control = fileURLToPath(new URL('../../', import.meta.url));
  10. const config = JSON.parse(readFileSync(new URL('./config.json', import.meta.url), 'utf8'));
  11. const { values } = parseArgs({ options: {
  12. base: { type: 'string' }, head: { type: 'string' }, benchmark: { type: 'string' },
  13. out: { type: 'string' }, scenario: { type: 'string' },
  14. suite: { type: 'string', default: 'basic' },
  15. }, strict: true });
  16. for (const name of ['base', 'head', 'benchmark', 'out']) {
  17. if (!values[name]) throw new Error(`Missing --${name}`);
  18. }
  19. const base = resolve(values.base), head = resolve(values.head);
  20. const benchmark = resolve(values.benchmark), out = resolve(values.out);
  21. if (existsSync(out)) throw new Error('Output directory must be new; old results cannot be reused');
  22. if (platform() !== 'darwin') throw new Error('This benchmark requires macOS process-tree rusage');
  23. const git = (directory, ...args) => execFileSync('git', ['-C', directory, ...args], { encoding: 'utf8' }).trim();
  24. if (git(benchmark, 'rev-parse', 'HEAD') !== config.benchmarkRevision) throw new Error('Wrong benchmark revision');
  25. if (git(benchmark, 'status', '--porcelain', '--untracked-files=no')) throw new Error('Benchmark has tracked edits');
  26. const bun = execFileSync('which', ['bun'], { encoding: 'utf8' }).trim();
  27. const scenarios = selectScenarios(config, values);
  28. mkdirSync(out, { recursive: true });
  29. const report = {
  30. status: 'RUNNING', baseRevision: git(base, 'rev-parse', 'HEAD'), headRevision: git(head, 'rev-parse', 'HEAD'),
  31. benchmarkRepository: config.benchmarkRepository, benchmarkRevision: config.benchmarkRevision,
  32. nodeVersion: process.version, bunVersion: execFileSync(bun, ['--version'], { encoding: 'utf8' }).trim(),
  33. host: { cpuModel: cpus()[0]?.model, cpus: cpus().length, totalMemBytes: totalmem(), platform: platform(), osRelease: release(), arch: arch() },
  34. config, suite: values.scenario ? 'focused' : values.suite, selectedScenarios: scenarios.map(s => s.id), results: [],
  35. builds: Object.fromEntries([['base', base], ['head', head]].map(([name, directory]) => [name, {
  36. path: directory, entrySha256: createHash('sha256').update(readFileSync(join(directory, 'dist/cli.js'))).digest('hex'),
  37. }])),
  38. };
  39. function save() {
  40. writeFileSync(join(out, 'comparison.json'), JSON.stringify(report, null, 2) + '\n');
  41. writeFileSync(join(out, 'comparison.md'), renderReport(report));
  42. }
  43. // Children receive synthetic state and an explicit environment, never local provider credentials.
  44. const environment = { PATH: process.env.PATH, HOME: join(out, 'home'), TMPDIR: process.env.TMPDIR ?? '/tmp',
  45. LANG: 'en_US.UTF-8', TERM: 'dumb', CI: '1', NO_COLOR: '1' };
  46. mkdirSync(environment.HOME, { recursive: true });
  47. function run(build, scenario, script, name, profile = false) {
  48. const directory = join(out, scenario.id, name);
  49. mkdirSync(directory, { recursive: true });
  50. const input = { benchmark, control, build, script, scenario, directory, profile,
  51. intervalMs: config.intervalMs, node: process.execPath };
  52. const inputPath = join(directory, 'input.json');
  53. writeFileSync(inputPath, JSON.stringify(input));
  54. const result = spawnSync(bun, [join(control, 'scripts/perf/driver.ts'), inputPath], {
  55. cwd: benchmark, env: environment, encoding: 'utf8', timeout: scenario.timeoutMs + 45000, maxBuffer: 16 * 1024 * 1024,
  56. });
  57. writeFileSync(join(directory, 'driver.log'), (result.stdout ?? '') + (result.stderr ?? ''));
  58. if (result.error || result.status !== 0) throw new Error(`${scenario.id}/${name} failed; see driver.log (${result.error?.message ?? result.status})`);
  59. return { ...JSON.parse(readFileSync(join(directory, 'result.json'), 'utf8')), directory };
  60. }
  61. save();
  62. try {
  63. for (const scenario of scenarios) {
  64. const script = join(out, `${scenario.id}.json`);
  65. execFileSync(bun, [join(benchmark, 'scripts/perf/gen-long-run.ts'), '--turns', String(scenario.turns),
  66. '--body-kb', String(scenario.bodyKb), '--tool', 'bash', '--chunk-size', String(scenario.chunkSize),
  67. '--chunk-delay-ms', '0', '--out', script], { cwd: benchmark, env: environment });
  68. const scriptData = JSON.parse(readFileSync(script, 'utf8'));
  69. const textUnits = scriptData.responses.slice(0, scenario.turns).reduce((sum, entry) => sum + entry.message.content.length, 0);
  70. if (scenario.minimumTextUnits && textUnits < scenario.minimumTextUnits) throw new Error('Long-history fixture no longer exceeds token cache capacity');
  71. const result = { id: scenario.id, textUnits, scenarioSha256: createHash('sha256').update(readFileSync(script)).digest('hex'), warmups: [], pairs: [] };
  72. report.results.push(result);
  73. save();
  74. for (let i = 0; i < config.warmups; i++) for (const [side, directory] of [['base', base], ['head', head]]) {
  75. console.log(`[perf] ${scenario.id}: ${side} warmup`);
  76. result.warmups.push({ side, ...run(directory, scenario, script, `${side}-warmup-${i}`) });
  77. save();
  78. }
  79. for (let pair = 0; pair < config.repetitions; pair++) {
  80. const item = { pair, order: pair % 2 ? ['head', 'base'] : ['base', 'head'] };
  81. result.pairs.push(item);
  82. for (const side of item.order) {
  83. console.log(`[perf] ${scenario.id}: pair ${pair + 1}, ${side}`);
  84. item[side] = run(side === 'base' ? base : head, scenario, script, `${side}-${pair}`);
  85. save();
  86. }
  87. }
  88. result.comparison = compareRuns(result.pairs.map(p => p.base.metrics), result.pairs.map(p => p.head.metrics), config);
  89. save();
  90. if (result.comparison.some(row => row.status === 'REGRESSION')) {
  91. console.log(`[perf] ${scenario.id}: separate diagnostic CPU profile`);
  92. try { result.diagnostic = run(head, scenario, script, 'head-profile', true); }
  93. catch (error) { result.diagnosticError = error.message; }
  94. save();
  95. }
  96. }
  97. const statuses = report.results.flatMap(r => r.comparison.map(row => row.status));
  98. report.status = statuses.includes('REGRESSION') ? 'REGRESSION' : statuses.includes('INCONCLUSIVE') ? 'INCONCLUSIVE' : 'PASS';
  99. process.exitCode = report.status === 'PASS' ? 0 : report.status === 'REGRESSION' ? 1 : 2;
  100. } catch (error) {
  101. report.status = 'ERROR';
  102. report.error = error.message;
  103. process.exitCode = 1;
  104. } finally {
  105. save();
  106. const markdown = readFileSync(join(out, 'comparison.md'), 'utf8');
  107. console.log(markdown);
  108. if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown);
  109. }