report.mjs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import assert from 'node:assert/strict';
  2. import { realpathSync } from 'node:fs';
  3. const textContent = content => typeof content === 'string' ? content : Array.isArray(content)
  4. ? content.filter(b => b.type === 'text').map(b => b.text).join('') : '';
  5. export function selectScenarios(config, { suite = 'basic', scenario } = {}) {
  6. assert.ok(Object.hasOwn(config.suites, suite), 'Unknown performance suite');
  7. const ids = scenario ? [scenario] : config.suites[suite];
  8. assert.ok(ids.length > 0 && new Set(ids).size === ids.length, 'Invalid scenario selection');
  9. return ids.map(id => {
  10. const selected = config.scenarios.find(item => item.id === id);
  11. assert.ok(selected, `Unknown scenario: ${id}`);
  12. return selected;
  13. });
  14. }
  15. export function validateToolOutput(content, command, workspace) {
  16. const text = textContent(content).trim();
  17. if (command.startsWith('echo ')) assert.equal(text, command.slice(5), 'Echo result changed');
  18. else if (command === 'pwd') assert.equal(text, realpathSync(workspace), 'Working directory result changed');
  19. else if (command === 'ls' || command === 'ls -la') assert.match(text, /(?:^|\s)README\.txt(?:\s|$)/, 'Directory listing lost fixture');
  20. else throw new Error('Unknown benchmark command');
  21. }
  22. export function validateRequest(body, responses, requestNumber, workspace, prompt) {
  23. const rounds = requestNumber - 1;
  24. assert.ok(rounds >= 0 && rounds < responses.length - 1, 'Unexpected request');
  25. assert.ok(Array.isArray(body.messages), 'Request messages missing');
  26. assert.ok(typeof prompt === 'string' && prompt.length > 0, 'Expected task missing');
  27. const conversation = body.messages.filter(m => m.role !== 'system' && m.role !== 'developer');
  28. assert.equal(conversation.length, 1 + rounds * 2, 'Request conversation length changed');
  29. assert.equal(conversation[0]?.role, 'user', 'Initial user task missing');
  30. assert.ok(textContent(conversation[0].content).includes(prompt), 'Initial user task changed');
  31. for (let i = 0; i < rounds; i++) {
  32. assert.equal(conversation[i * 2 + 1].role, 'assistant', 'Request conversation order changed');
  33. assert.equal(conversation[i * 2 + 2].role, 'tool', 'Request conversation order changed');
  34. }
  35. const assistant = body.messages.filter(m => m.role === 'assistant');
  36. const tools = body.messages.filter(m => m.role === 'tool');
  37. assert.equal(assistant.length, rounds, 'Request lost assistant history');
  38. assert.equal(tools.length, rounds, 'Request lost tool history');
  39. for (let i = 0; i < rounds; i++) {
  40. const expected = responses[i].message;
  41. assert.equal(textContent(assistant[i].content), expected.content, 'Request history body changed');
  42. assert.equal(assistant[i].tool_calls?.length, 1, 'Request tool calls changed');
  43. const call = assistant[i].tool_calls[0];
  44. assert.equal(call.id, expected.tool_calls[0].id, 'Request call identity changed');
  45. assert.equal(call.function.name, 'bash', 'Request tool changed');
  46. const args = typeof call.function.arguments === 'string' ? JSON.parse(call.function.arguments) : call.function.arguments;
  47. assert.deepEqual(args, expected.tool_calls[0].function.arguments, 'Request command changed');
  48. assert.equal(tools[i].tool_call_id, call.id, 'Request tool result identity changed');
  49. validateToolOutput(tools[i].content, args.command, workspace);
  50. }
  51. }
  52. export function median(values) {
  53. assert.ok(values.length > 0 && values.every(Number.isFinite), 'Nonempty finite samples required');
  54. const sorted = [...values].sort((a, b) => a - b);
  55. const middle = Math.floor(sorted.length / 2);
  56. return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
  57. }
  58. export function validateRun(meta, messages, scenario, expectedFinal, expectedResponses, workspace) {
  59. assert.equal(meta.schemaVersion, 1, 'Unknown upstream run schema');
  60. assert.equal(meta.status, 'ok', 'Benchmark did not complete');
  61. assert.equal(meta.exit?.code, 0, 'CLI failed');
  62. assert.equal(meta.mock?.requests, scenario.turns + 1, 'Unexpected model request count');
  63. assert.equal(meta.sampling?.backend, 'rusage', 'macOS rusage sampler is required');
  64. assert.equal(meta.sampling?.withTree, true, 'Process-tree sampling is required');
  65. assert.ok(meta.summary?.count >= 3, 'Insufficient samples');
  66. const calls = messages.flatMap(m => m.role === 'assistant' ? m.content.filter(b => b.type === 'toolCall') : []);
  67. const assistant = messages.filter(m => m.role === 'assistant');
  68. const results = messages.filter(m => m.role === 'toolResult');
  69. assert.equal(calls.length, scenario.turns, 'Missing or extra tool calls');
  70. assert.equal(results.length, scenario.turns, 'Missing or extra tool results');
  71. const ids = new Set();
  72. for (let i = 0; i < scenario.turns; i++) {
  73. assert.equal(calls[i].id, `call_long_run_${i + 1}`, 'Unexpected tool sequence');
  74. assert.equal(calls[i].name, 'bash', 'Unexpected tool');
  75. if (expectedResponses) {
  76. assert.deepEqual(calls[i].arguments, expectedResponses[i].message.tool_calls[0].function.arguments, 'Tool command changed');
  77. assert.equal(assistant[i].content.filter(b => b.type === 'text').map(b => b.text).join(''), expectedResponses[i].message.content, 'History body changed');
  78. }
  79. assert.equal(results[i].toolCallId, calls[i].id, 'Tool result does not match call');
  80. assert.equal(results[i].isError, false, 'Tool execution failed');
  81. if (expectedResponses && workspace) validateToolOutput(results[i].content, calls[i].arguments.command, workspace);
  82. assert.ok(!ids.has(results[i].toolCallId), 'Duplicate tool result');
  83. ids.add(results[i].toolCallId);
  84. }
  85. const last = messages.filter(m => m.role === 'assistant').at(-1);
  86. const final = last?.content.filter(b => b.type === 'text').map(b => b.text).join('');
  87. assert.equal(final, expectedFinal, 'Final response changed');
  88. const metrics = {
  89. durationMs: meta.duration?.endToEndMs,
  90. cpuSeconds: meta.cost?.cpuSeconds,
  91. rssBytes: meta.peaks?.treeRssBytes,
  92. };
  93. for (const [name, value] of Object.entries(metrics)) {
  94. assert.ok(Number.isFinite(value) && value > 0, `Invalid ${name}`);
  95. }
  96. return metrics;
  97. }
  98. export function compareRuns(base, head, config) {
  99. assert.equal(base.length, config.repetitions, 'Incomplete baseline repetitions');
  100. assert.equal(head.length, config.repetitions, 'Incomplete candidate repetitions');
  101. return Object.entries(config.thresholds).map(([metric, threshold]) => {
  102. const before = base.map(r => r[metric]);
  103. const after = head.map(r => r[metric]);
  104. assert.ok([...before, ...after].every(v => Number.isFinite(v) && v > 0), `Invalid ${metric}`);
  105. const baseline = median(before), candidate = median(after);
  106. const spread = values => (Math.max(...values) - Math.min(...values)) / median(values);
  107. const unstable = spread(before) > config.maxSpread || spread(after) > config.maxSpread;
  108. const delta = candidate - baseline;
  109. const regression = delta > Math.max(baseline * threshold.relative, threshold.absolute)
  110. && after.every((v, i) => v > before[i]);
  111. return { metric, baseline, candidate, change: delta / baseline,
  112. baseSpread: spread(before), headSpread: spread(after),
  113. status: unstable ? 'INCONCLUSIVE' : regression ? 'REGRESSION' : 'PASS' };
  114. });
  115. }
  116. export function renderReport(report) {
  117. const lines = ['# Performance comparison', '',
  118. `Status: **${report.status}**`, '',
  119. '| Item | Value |', '| --- | --- |',
  120. `| Base | \`${report.baseRevision}\` |`, `| Candidate | \`${report.headRevision}\` |`,
  121. `| Benchmark | [${report.benchmarkRevision}](${report.benchmarkRepository}/tree/${report.benchmarkRevision}) |`,
  122. `| 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} |`,
  123. `| Runtime | Node ${report.nodeVersion}; Bun ${report.bunVersion} |`,
  124. `| Suite | ${report.suite}; ${report.selectedScenarios.join(', ')} |`,
  125. `| Method | One warmup per revision/scenario; three alternating serial pairs; 100 ms process-tree rusage sampling |`,
  126. '', '| Scenario | Metric | Base median | Candidate median | Change | Result |',
  127. '| --- | --- | ---: | ---: | ---: | --- |'];
  128. for (const scenario of report.results) for (const row of scenario.comparison ?? []) {
  129. const scale = row.metric === 'rssBytes' ? 2 ** 20 : row.metric === 'durationMs' ? 1000 : 1;
  130. const unit = row.metric === 'rssBytes' ? 'MiB' : row.metric === 'durationMs' ? 's' : 'core-s';
  131. lines.push(`| ${scenario.id} | ${row.metric} | ${(row.baseline / scale).toFixed(2)} ${unit} | ${(row.candidate / scale).toFixed(2)} ${unit} | ${(row.change * 100).toFixed(1)}% | ${row.status} |`);
  132. }
  133. if (report.error) lines.push('', `Failure: ${String(report.error).replaceAll('\n', ' ').replaceAll('`', "'")}`);
  134. lines.push('', 'Raw run.json, samples.csv, CLI/mock logs, synthetic histories and any diagnostic CPU profile are attached. Warmups and diagnostic runs are excluded from comparisons.',
  135. '', 'This is a mock throughput check, not live-model acceptance. RSS is sampled. INCONCLUSIVE means excessive spread and fails the check; do not treat it as evidence of a regression or a pass.');
  136. return lines.join('\n') + '\n';
  137. }