diff --git a/.github/scripts/publish-benchmark.cjs b/.github/scripts/publish-benchmark.cjs index 84f0d475..289e9f6a 100644 --- a/.github/scripts/publish-benchmark.cjs +++ b/.github/scripts/publish-benchmark.cjs @@ -4,7 +4,15 @@ const marker = '' const branch = 'benchmark-reports' module.exports = async ({ github, context, core }) => { - const { comparePairs, formatComparison } = await import('../../benchmarks/comparison.js') + const { + comparePairs, + formatComparison, + formatComparisonSuite, + formatComparisonOverview, + unsupportedReasons, + } = await import('../../benchmarks/comparison.js') + const { validateThreshold, DEFAULT_THRESHOLD_PERCENT, MIN_BLOCKS } = + await import('../../benchmarks/statistics.js') const repo = context.repo const run = context.payload.workflow_run let pulls = run.pull_requests @@ -15,6 +23,9 @@ module.exports = async ({ github, context, core }) => { }) } const report = JSON.parse(await readFile('benchmark-data/comparison.json', 'utf8')) + if (report.status !== undefined && report.status !== 'completed') { + throw new Error('Benchmark comparison is incomplete') + } const prs = [] for (const pull of pulls) { const { data: pr } = await github.rest.pulls.get({ ...repo, pull_number: pull.number }) @@ -32,57 +43,85 @@ module.exports = async ({ github, context, core }) => { return } - // Artifacts are untrusted data. Validate numeric inputs and escape display text. - const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 && value <= 100_000 - if ( - !positiveInteger(report.size) || - !positiveInteger(report.samples) || - !Number.isSafeInteger(report.warmup) || - report.warmup < 0 || - report.warmup > 100_000 || - !Array.isArray(report.pairs) || - !report.pairs.length || - report.pairs.length > 100 - ) { - throw new Error('Invalid benchmark configuration') + const reports = Object.hasOwn(report, 'benchmarks') ? report.benchmarks : [report] + if (!Array.isArray(reports) || reports.length < 1 || reports.length > 100) { + throw new Error('Invalid benchmark suite') } - for (const pair of report.pairs) { + for (const result of reports) { + if ( + result.base?.commit !== report.base.commit || + result.candidate?.commit !== report.candidate.commit + ) { + throw new Error('Benchmark commit identities do not match the suite') + } + // Artifacts are untrusted data. Validate numeric inputs and escape display text. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 && value <= 100_000 if ( - !Array.isArray(pair.order) || - pair.order.length !== 2 || - [...pair.order].sort().join(',') !== 'base,candidate' + !positiveInteger(result.size) || + !positiveInteger(result.samples) || + !Number.isSafeInteger(result.warmup) || + result.warmup < 0 || + result.warmup > 100_000 || + !Array.isArray(result.pairs) || + !result.pairs.length || + result.pairs.length > 100 ) { - throw new Error('Invalid benchmark execution order') + throw new Error('Invalid benchmark configuration') } - for (const name of ['base', 'candidate']) { - for (const metric of ['medianGenerationSyncMs', 'medianTotalToIdleMs']) { - if (!Number.isFinite(pair[name]?.[metric]) || pair[name][metric] < 0) { - throw new Error('Invalid benchmark timing') + for (const pair of result.pairs) { + if ( + !Array.isArray(pair.order) || + pair.order.length !== 2 || + [...pair.order].sort().join(',') !== 'base,candidate' + ) { + throw new Error('Invalid benchmark execution order') + } + for (const name of ['base', 'candidate']) { + if (name === 'base' && pair.base?.status === 'unsupported') { + if (typeof pair.base.reason !== 'string' || !pair.base.reason.trim()) { + throw new Error('Invalid unsupported baseline reason') + } + continue + } + if (pair[name]?.status === 'unsupported') throw new Error('Candidate benchmark unsupported') + for (const metric of ['medianGenerationSyncMs', 'medianTotalToIdleMs']) { + if (!Number.isFinite(pair[name]?.[metric]) || pair[name][metric] < 0) { + throw new Error('Invalid benchmark timing') + } } } } - } - const text = (value) => - String(value) - .slice(0, 120) - .replace(/[\\`*_[\]<>|#\r\n]/g, ' ') - report.title = text(report.title) - report.browserVersion = text(report.browserVersion) - report.cpuSlowdown = 20 - report.candidate.dirty = false - report.comparison = comparePairs(report.pairs) - if ( - report.comparison.some( - (row) => - !Number.isFinite(row.differenceMs) || - (row.changePercent !== null && !Number.isFinite(row.changePercent)) + const text = (value) => + String(value) + .slice(0, 120) + .replace(/[\\`*_[\]<>|#\r\n]/g, ' ') + for (const pair of result.pairs) { + if (pair.base.status === 'unsupported') pair.base.reason = text(pair.base.reason) + } + result.title = text(result.title) + result.browserVersion = text(result.browserVersion) + result.cpuSlowdown ??= 20 + if (!Number.isFinite(result.cpuSlowdown) || result.cpuSlowdown < 1) { + throw new Error('Invalid CPU slowdown') + } + result.candidate.dirty = false + result.thresholdPercent = validateThreshold( + result.thresholdPercent ?? DEFAULT_THRESHOLD_PERCENT ) - ) { - throw new Error('Invalid benchmark comparison') + result.comparison = comparePairs(result.pairs, { thresholdPercent: result.thresholdPercent }) + if ( + result.comparison.some( + (row) => + (row.differenceMs !== null && !Number.isFinite(row.differenceMs)) || + (row.changePercent !== null && !Number.isFinite(row.changePercent)) + ) + ) { + throw new Error('Invalid benchmark comparison') + } } const path = `runs/${run.id}-${run.run_attempt || 1}` - const markdown = `${formatComparison(report)}\n[JSON data](comparison.json) · [Workflow run](${run.html_url})\n` + const markdown = `${Object.hasOwn(report, 'benchmarks') ? formatComparisonSuite(report) : formatComparison(report)}\n[JSON data](comparison.json) · [Workflow run](${run.html_url})\n` let parent let baseTree try { @@ -124,20 +163,26 @@ module.exports = async ({ github, context, core }) => { } const url = `${context.serverUrl}/${repo.owner}/${repo.repo}/blob/${commit.sha}/${path}/report.md` - const change = (metric) => { - const value = report.comparison.find((row) => row.metric === metric).changePercent - return value === null ? 'n/a' : `${value > 0 ? '+' : ''}${value.toFixed(2)}%` - } const body = [ marker, '### Benchmark comparison', '', - '| Timing | Change |', - '| --- | ---: |', - `| Synchronous generation | ${change('medianGenerationSyncMs')} |`, - `| Total time to idle | ${change('medianTotalToIdleMs')} |`, + formatComparisonOverview(reports), + '', + ...reports.map( + (result) => + `${result.title}: ±${result.thresholdPercent}% practical band; ${result.pairs.length} pairs, ${result.warmup} warmups and ${result.samples} samples per run.` + ), + '', + ...reports.flatMap((result) => + unsupportedReasons(result).map( + (reason) => `${result.title}: N/A — unsupported by baseline: ${reason}` + ) + ), + '', + `Runs with fewer than ${MIN_BLOCKS} balanced blocks (${MIN_BLOCKS * 2} pairs) are preliminary; no confidence interval or performance conclusion is available.`, '', - 'Negative means faster. Informational results; small changes can be measurement noise.', + 'Negative means faster. Intervals and verdicts use balanced launch blocks, not inner samples. Inconclusive is not evidence of no change. Results are informational.', '', `[Full report](${url}) · [Workflow run](${run.html_url})`, '', diff --git a/.github/scripts/publish-benchmark.test.cjs b/.github/scripts/publish-benchmark.test.cjs index dc40e792..7c691770 100644 --- a/.github/scripts/publish-benchmark.test.cjs +++ b/.github/scripts/publish-benchmark.test.cjs @@ -19,7 +19,13 @@ after(async () => { await rm(directory, { recursive: true, force: true }) }) -const fixture = async ({ existing = false, stale = false, invalid = false } = {}) => { +const fixture = async ({ + existing = false, + stale = false, + invalid = false, + suite = false, + mutate, +} = {}) => { const calls = [] const report = { title: 'Element generation benchmark', @@ -38,7 +44,22 @@ const fixture = async ({ existing = false, stale = false, invalid = false } = {} ], comparison: [{ changePercent: 999 }], // Recomputed rather than trusted. } - await writeFile('benchmark-data/comparison.json', JSON.stringify(report)) + const data = suite + ? { + base: report.base, + candidate: report.candidate, + benchmarks: [ + { ...report, benchmark: 'element-creation' }, + { + ...structuredClone(report), + benchmark: 'component-creation', + title: 'Component generation benchmark', + }, + ], + } + : report + mutate?.(data) + await writeFile('benchmark-data/comparison.json', JSON.stringify(data)) const method = (name, data) => async (args) => { calls.push({ name, args }) return { data } @@ -137,3 +158,159 @@ test('skips stale results and rejects invalid timings before publication', async await assert.rejects(publish(invalid), /Invalid benchmark timing/) assert.ok(!invalid.calls.some((call) => call.name === 'createTree')) }) + +test('publishes every benchmark with individual comparisons and run configuration', async () => { + const mock = await fixture({ suite: true }) + await publish(mock) + const body = mock.calls.find((call) => call.name === 'createComment').args.body + assert.match(body, /Benchmark \| Generation change \| Time to idle change/) + assert.match(body, /Element generation benchmark \| -20\.00% · Preliminary \| \+10\.00%/) + assert.match(body, /Component generation benchmark \| -20\.00% · Preliminary \| \+10\.00%/) + assert.match(body, /1 pairs, 5 warmups and 20 samples/) + const tree = mock.calls.find((call) => call.name === 'createTree').args.tree + assert.match(tree[0].content, /## Element generation benchmark: comparison/) + assert.match(tree[0].content, /## Component generation benchmark: comparison/) + const saved = JSON.parse(tree[1].content) + assert.equal(saved.benchmarks.length, 2) + assert.ok(Math.abs(saved.benchmarks[1].comparison[0].changePercent + 20) < 1e-10) +}) + +test('rejects invalid suite entries before writing reports or comments', async () => { + for (const [mutate, expected] of [ + [ + (report) => { + report.status = 'running' + }, + /comparison is incomplete/, + ], + [ + (report) => { + report.status = 'failed' + }, + /comparison is incomplete/, + ], + [ + (report) => { + report.benchmarks = [] + }, + /Invalid benchmark suite/, + ], + [ + (report) => { + report.benchmarks[1].pairs[0].candidate.medianTotalToIdleMs = -1 + }, + /Invalid benchmark timing/, + ], + [ + (report) => { + report.benchmarks[1].candidate.commit = 'different' + }, + /commit identities/, + ], + ]) { + const mock = await fixture({ suite: true, mutate }) + await assert.rejects(publish(mock), expected) + assert.ok( + !mock.calls.some((call) => + ['createTree', 'createComment', 'updateComment'].includes(call.name) + ) + ) + } +}) + +test('escapes suite titles before rendering comment tables and report sections', async () => { + const mock = await fixture({ + suite: true, + mutate: (report) => { + report.benchmarks[1].title = '