report.mjs 7.8 KB

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