Parcourir la source

feat: run basic performance automatically and full suite on demand

saladday il y a 2 mois
Parent
commit
712824eb76

+ 13 - 5
.github/workflows/performance.yml

@@ -8,16 +8,22 @@ on:
         required: true
         required: true
         default: main
         default: main
         type: string
         type: string
+      suite:
+        description: Performance suite (full includes startup and long history)
+        required: true
+        default: full
+        type: choice
+        options: [full, basic]
 permissions:
 permissions:
   contents: read
   contents: read
 concurrency:
 concurrency:
-  group: performance-${{ github.ref }}
+  group: performance-${{ github.event_name }}-${{ inputs.suite || 'basic' }}-${{ github.ref }}
   cancel-in-progress: true
   cancel-in-progress: true
 jobs:
 jobs:
   performance:
   performance:
-    name: performance
+    name: performance (${{ inputs.suite || 'basic' }})
     runs-on: macos-15
     runs-on: macos-15
-    timeout-minutes: 45
+    timeout-minutes: ${{ inputs.suite == 'full' && 45 || 15 }}
     steps:
     steps:
       - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
       - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
         with:
@@ -60,12 +66,14 @@ jobs:
         working-directory: benchmark
         working-directory: benchmark
         run: bun install --frozen-lockfile
         run: bun install --frozen-lockfile
       - name: Compare on this runner
       - name: Compare on this runner
-        run: node candidate/scripts/perf/run.mjs --base baseline --head candidate --benchmark benchmark --out "$RUNNER_TEMP/performance"
+        env:
+          PERF_SUITE: ${{ inputs.suite || 'basic' }}
+        run: node candidate/scripts/perf/run.mjs --base baseline --head candidate --benchmark benchmark --suite "$PERF_SUITE" --out "$RUNNER_TEMP/performance"
       - name: Upload performance evidence
       - name: Upload performance evidence
         if: ${{ always() }}
         if: ${{ always() }}
         uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
         uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
         with:
         with:
-          name: performance-${{ github.run_attempt }}
+          name: performance-${{ inputs.suite || 'basic' }}-${{ github.run_attempt }}
           path: ${{ runner.temp }}/performance/
           path: ${{ runner.temp }}/performance/
           include-hidden-files: true
           include-hidden-files: true
           retention-days: 14
           retention-days: 14

+ 1 - 1
CONTRIBUTING.md

@@ -55,7 +55,7 @@ Test files are declared in `test/vitest-suites.json`, grouped by the gate that r
 
 
 Review added or removed files before running `node scripts/source-inventory.mjs --write`. Updating the inventory must not bypass checks for private protocols, internal addresses, credentials, or third-party licensing. Before a source release, also scan the complete Git history with Gitleaks; see the [release process](docs/releasing.md).
 Review added or removed files before running `node scripts/source-inventory.mjs --write`. Updating the inventory must not bypass checks for private protocols, internal addresses, credentials, or third-party licensing. Before a source release, also scan the complete Git history with Gitleaks; see the [release process](docs/releasing.md).
 
 
-PRs also run the [performance comparison](docs/performance-ci.md): a pinned upstream benchmark plus startup and long-history fixtures, comparing base/head on the same runner. Raw evidence and machine configuration accompany the check.
+PRs also run the [performance comparison](docs/performance-ci.md): the pinned 100-round upstream benchmark automatically, with startup and long-history fixtures available through the manual full suite. Both compare base/head on the same runner. Raw evidence and machine configuration accompany the check.
 
 
 ## Capability boundaries
 ## Capability boundaries
 
 

+ 16 - 6
docs/performance-ci.md

@@ -1,8 +1,14 @@
 # Performance CI
 # Performance CI
 
 
-Every PR runs `performance`: the base and head SHAs build separately, then run
-serially on one `macos-15` runner with Node 22.23.2 and Bun 1.4.2. Manual dispatch
-accepts a baseline ref. Build and installation time are excluded.
+Every PR automatically runs `performance (basic)`: only the original 100-round
+scenario. Performance optimization PRs can run the full suite manually. Both
+revisions build separately, then run serially on one `macos-15` runner with Node
+22.23.2 and Bun 1.4.2. Build and installation time are excluded.
+
+| Mode | Trigger | Scenarios | Job timeout |
+| --- | --- | --- | --- |
+| `basic` | Every PR; optional manual run | `upstream-100` | 15 minutes |
+| `full` | Manual only | Startup, `upstream-100`, `history-300` | 45 minutes |
 
 
 | Scenario | Input | Purpose |
 | Scenario | Input | Purpose |
 | --- | --- | --- |
 | --- | --- | --- |
@@ -42,7 +48,7 @@ needs another clean measurement; it is neither a confirmed regression nor a pass
 Tune budgets from repeated same-revision measurements. Review changes to
 Tune budgets from repeated same-revision measurements. Review changes to
 scenarios, comparison logic or limits as changes to the performance contract.
 scenarios, comparison logic or limits as changes to the performance contract.
 The workflow does not change branch protection; maintainers can add
 The workflow does not change branch protection; maintainers can add
-`performance` as a required check after runner calibration.
+`performance (basic)` as a required check after runner calibration.
 
 
 The Job Summary contains machine/method and comparison tables. The 14-day
 The Job Summary contains machine/method and comparison tables. The 14-day
 artifact includes JSON results, configuration, commit and fixture hashes,
 artifact includes JSON results, configuration, commit and fixture hashes,
@@ -60,7 +66,11 @@ node scripts/perf/run.mjs --base /path/to/base --head /path/to/head \
   --benchmark /path/to/pinned-benchmark --out /tmp/new-performance-output
   --benchmark /path/to/pinned-benchmark --out /tmp/new-performance-output
 ```
 ```
 
 
-The output directory must be new. Use `--scenario startup` for focused checks;
-the PR workflow always runs every declared scenario. It uses read-only
+The output directory must be new. The CLI defaults to `--suite basic`; pass
+`--suite full` explicitly for the complete suite or `--scenario startup` for a
+focused local check. Once the workflow is merged into the default branch, open
+**Actions → Performance → Run workflow**, choose the PR branch, set the baseline
+ref, and select `full` for long-history testing. Manual runs use a separate
+concurrency group and do not cancel automatic PR checks. The workflow uses read-only
 permissions and `pull_request`, without comments or secrets. See GitHub's
 permissions and `pull_request`, without comments or secrets. See GitHub's
 [event security guidance](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target).
 [event security guidance](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target).

+ 4 - 0
scripts/perf/config.json

@@ -5,6 +5,10 @@
   "repetitions": 3,
   "repetitions": 3,
   "intervalMs": 100,
   "intervalMs": 100,
   "maxSpread": 0.3,
   "maxSpread": 0.3,
+  "suites": {
+    "basic": ["upstream-100"],
+    "full": ["startup", "upstream-100", "history-300"]
+  },
   "thresholds": {
   "thresholds": {
     "durationMs": {
     "durationMs": {
       "relative": 0.25,
       "relative": 0.25,

+ 1 - 1
scripts/perf/driver.ts

@@ -25,7 +25,7 @@ const proxy = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(request) {
     requests++;
     requests++;
     const start = performance.now();
     const start = performance.now();
     let error: string | undefined;
     let error: string | undefined;
-    try { validateRequest(JSON.parse(new TextDecoder().decode(bytes)), scenario.responses, requests, workspace); }
+    try { validateRequest(JSON.parse(new TextDecoder().decode(bytes)), scenario.responses, requests, workspace, cfg.prompt); }
     catch (failure) { error = String(failure); auditFailure ??= error; }
     catch (failure) { error = String(failure); auditFailure ??= error; }
     appendFileSync(join(input.directory, 'requests.jsonl'), JSON.stringify({ request: requests,
     appendFileSync(join(input.directory, 'requests.jsonl'), JSON.stringify({ request: requests,
       bytes: bytes.byteLength, validationMs: performance.now() - start, ok: !error, ...(error ? { error } : {}) }) + '\n');
       bytes: bytes.byteLength, validationMs: performance.now() - start, ok: !error, ...(error ? { error } : {}) }) + '\n');

+ 22 - 1
scripts/perf/report.mjs

@@ -4,6 +4,17 @@ import { realpathSync } from 'node:fs';
 const textContent = content => typeof content === 'string' ? content : Array.isArray(content)
 const textContent = content => typeof content === 'string' ? content : Array.isArray(content)
   ? content.filter(b => b.type === 'text').map(b => b.text).join('') : '';
   ? content.filter(b => b.type === 'text').map(b => b.text).join('') : '';
 
 
+export function selectScenarios(config, { suite = 'basic', scenario } = {}) {
+  assert.ok(Object.hasOwn(config.suites, suite), 'Unknown performance suite');
+  const ids = scenario ? [scenario] : config.suites[suite];
+  assert.ok(ids.length > 0 && new Set(ids).size === ids.length, 'Invalid scenario selection');
+  return ids.map(id => {
+    const selected = config.scenarios.find(item => item.id === id);
+    assert.ok(selected, `Unknown scenario: ${id}`);
+    return selected;
+  });
+}
+
 export function validateToolOutput(content, command, workspace) {
 export function validateToolOutput(content, command, workspace) {
   const text = textContent(content).trim();
   const text = textContent(content).trim();
   if (command.startsWith('echo ')) assert.equal(text, command.slice(5), 'Echo result changed');
   if (command.startsWith('echo ')) assert.equal(text, command.slice(5), 'Echo result changed');
@@ -12,10 +23,19 @@ export function validateToolOutput(content, command, workspace) {
   else throw new Error('Unknown benchmark command');
   else throw new Error('Unknown benchmark command');
 }
 }
 
 
-export function validateRequest(body, responses, requestNumber, workspace) {
+export function validateRequest(body, responses, requestNumber, workspace, prompt) {
   const rounds = requestNumber - 1;
   const rounds = requestNumber - 1;
   assert.ok(rounds >= 0 && rounds < responses.length - 1, 'Unexpected request');
   assert.ok(rounds >= 0 && rounds < responses.length - 1, 'Unexpected request');
   assert.ok(Array.isArray(body.messages), 'Request messages missing');
   assert.ok(Array.isArray(body.messages), 'Request messages missing');
+  assert.ok(typeof prompt === 'string' && prompt.length > 0, 'Expected task missing');
+  const conversation = body.messages.filter(m => m.role !== 'system' && m.role !== 'developer');
+  assert.equal(conversation.length, 1 + rounds * 2, 'Request conversation length changed');
+  assert.equal(conversation[0]?.role, 'user', 'Initial user task missing');
+  assert.ok(textContent(conversation[0].content).includes(prompt), 'Initial user task changed');
+  for (let i = 0; i < rounds; i++) {
+    assert.equal(conversation[i * 2 + 1].role, 'assistant', 'Request conversation order changed');
+    assert.equal(conversation[i * 2 + 2].role, 'tool', 'Request conversation order changed');
+  }
   const assistant = body.messages.filter(m => m.role === 'assistant');
   const assistant = body.messages.filter(m => m.role === 'assistant');
   const tools = body.messages.filter(m => m.role === 'tool');
   const tools = body.messages.filter(m => m.role === 'tool');
   assert.equal(assistant.length, rounds, 'Request lost assistant history');
   assert.equal(assistant.length, rounds, 'Request lost assistant history');
@@ -109,6 +129,7 @@ export function renderReport(report) {
     `| Benchmark | [${report.benchmarkRevision}](${report.benchmarkRepository}/tree/${report.benchmarkRevision}) |`,
     `| Benchmark | [${report.benchmarkRevision}](${report.benchmarkRepository}/tree/${report.benchmarkRevision}) |`,
     `| Machine | ${report.host.cpuModel}; ${report.host.cpus} CPUs; ${Math.round(report.host.totalMemBytes / 2 ** 30)} GiB; ${report.host.platform} ${report.host.osRelease}; ${report.host.arch} |`,
     `| Machine | ${report.host.cpuModel}; ${report.host.cpus} CPUs; ${Math.round(report.host.totalMemBytes / 2 ** 30)} GiB; ${report.host.platform} ${report.host.osRelease}; ${report.host.arch} |`,
     `| Runtime | Node ${report.nodeVersion}; Bun ${report.bunVersion} |`,
     `| Runtime | Node ${report.nodeVersion}; Bun ${report.bunVersion} |`,
+    `| Suite | ${report.suite}; ${report.selectedScenarios.join(', ')} |`,
     `| Method | One warmup per revision/scenario; three alternating serial pairs; 100 ms process-tree rusage sampling |`,
     `| Method | One warmup per revision/scenario; three alternating serial pairs; 100 ms process-tree rusage sampling |`,
     '', '| Scenario | Metric | Base median | Candidate median | Change | Result |',
     '', '| Scenario | Metric | Base median | Candidate median | Change | Result |',
     '| --- | --- | ---: | ---: | ---: | --- |'];
     '| --- | --- | ---: | ---: | ---: | --- |'];

+ 4 - 4
scripts/perf/run.mjs

@@ -5,13 +5,14 @@ import { resolve, join } from 'node:path';
 import { fileURLToPath } from 'node:url';
 import { fileURLToPath } from 'node:url';
 import { parseArgs } from 'node:util';
 import { parseArgs } from 'node:util';
 import { createHash } from 'node:crypto';
 import { createHash } from 'node:crypto';
-import { compareRuns, renderReport } from './report.mjs';
+import { compareRuns, renderReport, selectScenarios } from './report.mjs';
 
 
 const control = fileURLToPath(new URL('../../', import.meta.url));
 const control = fileURLToPath(new URL('../../', import.meta.url));
 const config = JSON.parse(readFileSync(new URL('./config.json', import.meta.url), 'utf8'));
 const config = JSON.parse(readFileSync(new URL('./config.json', import.meta.url), 'utf8'));
 const { values } = parseArgs({ options: {
 const { values } = parseArgs({ options: {
   base: { type: 'string' }, head: { type: 'string' }, benchmark: { type: 'string' },
   base: { type: 'string' }, head: { type: 'string' }, benchmark: { type: 'string' },
   out: { type: 'string' }, scenario: { type: 'string' },
   out: { type: 'string' }, scenario: { type: 'string' },
+  suite: { type: 'string', default: 'basic' },
 }, strict: true });
 }, strict: true });
 for (const name of ['base', 'head', 'benchmark', 'out']) {
 for (const name of ['base', 'head', 'benchmark', 'out']) {
   if (!values[name]) throw new Error(`Missing --${name}`);
   if (!values[name]) throw new Error(`Missing --${name}`);
@@ -24,15 +25,14 @@ const git = (directory, ...args) => execFileSync('git', ['-C', directory, ...arg
 if (git(benchmark, 'rev-parse', 'HEAD') !== config.benchmarkRevision) throw new Error('Wrong benchmark revision');
 if (git(benchmark, 'rev-parse', 'HEAD') !== config.benchmarkRevision) throw new Error('Wrong benchmark revision');
 if (git(benchmark, 'status', '--porcelain', '--untracked-files=no')) throw new Error('Benchmark has tracked edits');
 if (git(benchmark, 'status', '--porcelain', '--untracked-files=no')) throw new Error('Benchmark has tracked edits');
 const bun = execFileSync('which', ['bun'], { encoding: 'utf8' }).trim();
 const bun = execFileSync('which', ['bun'], { encoding: 'utf8' }).trim();
-const scenarios = config.scenarios.filter(s => !values.scenario || s.id === values.scenario);
-if (!scenarios.length) throw new Error('Unknown scenario');
+const scenarios = selectScenarios(config, values);
 mkdirSync(out, { recursive: true });
 mkdirSync(out, { recursive: true });
 const report = {
 const report = {
   status: 'RUNNING', baseRevision: git(base, 'rev-parse', 'HEAD'), headRevision: git(head, 'rev-parse', 'HEAD'),
   status: 'RUNNING', baseRevision: git(base, 'rev-parse', 'HEAD'), headRevision: git(head, 'rev-parse', 'HEAD'),
   benchmarkRepository: config.benchmarkRepository, benchmarkRevision: config.benchmarkRevision,
   benchmarkRepository: config.benchmarkRepository, benchmarkRevision: config.benchmarkRevision,
   nodeVersion: process.version, bunVersion: execFileSync(bun, ['--version'], { encoding: 'utf8' }).trim(),
   nodeVersion: process.version, bunVersion: execFileSync(bun, ['--version'], { encoding: 'utf8' }).trim(),
   host: { cpuModel: cpus()[0]?.model, cpus: cpus().length, totalMemBytes: totalmem(), platform: platform(), osRelease: release(), arch: arch() },
   host: { cpuModel: cpus()[0]?.model, cpus: cpus().length, totalMemBytes: totalmem(), platform: platform(), osRelease: release(), arch: arch() },
-  config, selectedScenarios: scenarios.map(s => s.id), results: [],
+  config, suite: values.scenario ? 'focused' : values.suite, selectedScenarios: scenarios.map(s => s.id), results: [],
   builds: Object.fromEntries([['base', base], ['head', head]].map(([name, directory]) => [name, {
   builds: Object.fromEntries([['base', base], ['head', head]].map(([name, directory]) => [name, {
     path: directory, entrySha256: createHash('sha256').update(readFileSync(join(directory, 'dist/cli.js'))).digest('hex'),
     path: directory, entrySha256: createHash('sha256').update(readFileSync(join(directory, 'dist/cli.js'))).digest('hex'),
   }])),
   }])),

+ 24 - 5
test/source-sync.test.mjs

@@ -18,7 +18,22 @@ import { cliBuildVersion, cliExternalModules, cliReleaseTargets, versionFromTag
 import { releaseManifest } from '../scripts/package-cli-release.mjs';
 import { releaseManifest } from '../scripts/package-cli-release.mjs';
 import { validateReleaseReports } from '../scripts/publish-cli-release.mjs';
 import { validateReleaseReports } from '../scripts/publish-cli-release.mjs';
 import { compareVersions, releaseCli } from '../scripts/release-cli.mjs';
 import { compareVersions, releaseCli } from '../scripts/release-cli.mjs';
-import { compareRuns, validateRun, validateRequest, validateToolOutput, median } from '../scripts/perf/report.mjs';
+import { compareRuns, validateRun, validateRequest, validateToolOutput, median, selectScenarios } from '../scripts/perf/report.mjs';
+
+test('performance defaults to the 100-round suite; long history requires explicit selection', () => {
+  const config = JSON.parse(readFileSync(new URL('../scripts/perf/config.json', import.meta.url), 'utf8'));
+  assert.deepEqual(selectScenarios(config).map(s => s.id), ['upstream-100']);
+  assert.deepEqual(selectScenarios(config, { suite: 'full' }).map(s => s.id), ['startup', 'upstream-100', 'history-300']);
+  assert.deepEqual(selectScenarios(config, { scenario: 'startup' }).map(s => s.id), ['startup']);
+  assert.throws(() => selectScenarios(config, { suite: 'typo' }));
+  assert.throws(() => selectScenarios(config, { scenario: 'typo' }));
+  const workflow = parseYaml(readFileSync(new URL('../.github/workflows/performance.yml', import.meta.url), 'utf8'));
+  assert.equal(workflow.on.workflow_dispatch.inputs.suite.default, 'full');
+  assert.deepEqual(workflow.on.workflow_dispatch.inputs.suite.options, ['full', 'basic']);
+  const compare = workflow.jobs.performance.steps.find(s => s.name === 'Compare on this runner');
+  assert.equal(compare.env.PERF_SUITE, "${{ inputs.suite || 'basic' }}");
+  assert.match(compare.run, /--suite "\$PERF_SUITE"/);
+});
 
 
 test('performance request audit rejects truncated wire history and empty tool results', () => {
 test('performance request audit rejects truncated wire history and empty tool results', () => {
   const responses = [
   const responses = [
@@ -28,13 +43,17 @@ test('performance request audit rejects truncated wire history and empty tool re
   const messages = [{ role: 'user', content: 'task' },
   const messages = [{ role: 'user', content: 'task' },
     { role: 'assistant', content: 'full history', tool_calls: [{ id: 'call_long_run_1', function: { name: 'bash', arguments: '{"command":"ls"}' } }] },
     { role: 'assistant', content: 'full history', tool_calls: [{ id: 'call_long_run_1', function: { name: 'bash', arguments: '{"command":"ls"}' } }] },
     { role: 'tool', tool_call_id: 'call_long_run_1', content: 'README.txt\n' }];
     { role: 'tool', tool_call_id: 'call_long_run_1', content: 'README.txt\n' }];
-  assert.doesNotThrow(() => validateRequest({ messages }, responses, 2, process.cwd()));
-  assert.throws(() => validateRequest({ messages: messages.slice(0, 1) }, responses, 2, process.cwd()), /lost assistant history/);
+  assert.doesNotThrow(() => validateRequest({ messages }, responses, 2, process.cwd(), 'task'));
+  assert.throws(() => validateRequest({ messages: messages.slice(0, 1) }, responses, 2, process.cwd(), 'task'), /conversation length/);
+  assert.throws(() => validateRequest({ messages: [] }, responses, 1, process.cwd(), 'task'), /conversation length/);
+  assert.throws(() => validateRequest({ messages: [messages[0], messages[2], messages[1]] }, responses, 2, process.cwd(), 'task'), /order changed/);
+  assert.throws(() => validateRequest({ messages: [{ role: 'user', content: 'wrong' }] }, responses, 1, process.cwd(), 'task'), /task changed/);
+  assert.doesNotThrow(() => validateRequest({ messages: [messages[0]] }, responses, 1, process.cwd(), 'task'));
   const changed = structuredClone(messages);
   const changed = structuredClone(messages);
   changed[1].content = 'shortened';
   changed[1].content = 'shortened';
-  assert.throws(() => validateRequest({ messages: changed }, responses, 2, process.cwd()), /body changed/);
+  assert.throws(() => validateRequest({ messages: changed }, responses, 2, process.cwd(), 'task'), /body changed/);
   changed[1].content = 'full history'; changed[2].content = '';
   changed[1].content = 'full history'; changed[2].content = '';
-  assert.throws(() => validateRequest({ messages: changed }, responses, 2, process.cwd()), /lost fixture/);
+  assert.throws(() => validateRequest({ messages: changed }, responses, 2, process.cwd(), 'task'), /lost fixture/);
   assert.throws(() => validateToolOutput([], 'ls', process.cwd()), /lost fixture/);
   assert.throws(() => validateToolOutput([], 'ls', process.cwd()), /lost fixture/);
   assert.throws(() => validateToolOutput('wrong', 'echo expected', process.cwd()), /Echo/);
   assert.throws(() => validateToolOutput('wrong', 'echo expected', process.cwd()), /Echo/);
   assert.throws(() => validateToolOutput('/wrong', 'pwd', process.cwd()), /directory/);
   assert.throws(() => validateToolOutput('/wrong', 'pwd', process.cwd()), /directory/);