Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions .github/scripts/benchmark-comment.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ function mergeCPUReport(body, existing, head) {
return body;
}

async function publishCPUReport(github, repo, run, report) {
async function findCurrentPull(github, repo, run) {
const { head_repository: source, head_branch: branch, head_sha: sha, pull_requests: linked } = run;
if (!source?.owner?.login || !branch || !sha) return false;
if (!source?.owner?.login || !branch || !sha) return null;

// Fork runs can omit pull_requests. Resolve the target from GitHub's
// repository, branch and SHA metadata, avoiding ambiguous matches.
Expand All @@ -25,15 +25,26 @@ async function publishCPUReport(github, repo, run, report) {
});
const matches = pulls.filter(pr => matchesHead(pr) &&
(!linked?.length || linked.some(ref => ref.number === pr.number)));
if (matches.length !== 1) return false;
return matches.length === 1 ? matches[0] : null;
}

const issue_number = matches[0].number;
async function publishCPUReport(github, repo, run, report) {
const pull = await findCurrentPull(github, repo, run);
if (!pull) return false;
const { head_repository: source, head_branch: branch, head_sha: sha } = run;
const matchesHead = pr => pr.state === 'open' && pr.head.sha === sha &&
pr.head.repo?.id === source.id && pr.head.ref === branch;
const issue_number = pull.number;
const comments = await github.paginate(github.rest.issues.listComments, { ...repo, issue_number });
const existing = comments.find(c => c.user?.login === 'github-actions[bot]' && c.body?.startsWith(marker));
const { data: current } = await github.rest.pulls.get({ ...repo, pull_number: issue_number });
if (!matchesHead(current)) return false;

const body = mergeCPUReport(report, existing?.body, sha);
let body = mergeCPUReport(report, existing?.body, sha);
if (Number.isSafeInteger(run.id) && run.id > 0 && Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0) {
body = body.replace(marker, `${marker}\n<!-- dagger-benchmark-run:${run.id}:${run.run_attempt} -->`);
}
if (existing?.body === body) return true;
if (existing) {
await github.rest.issues.updateComment({ ...repo, comment_id: existing.id, body });
} else {
Expand All @@ -42,4 +53,4 @@ async function publishCPUReport(github, repo, run, report) {
return true;
}

module.exports = { mergeCPUReport, publishCPUReport };
module.exports = { mergeCPUReport, findCurrentPull, publishCPUReport };
18 changes: 18 additions & 0 deletions .github/scripts/benchmark-comment.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,21 @@ test('skips stale, closed and ambiguous PRs', async () => {
assert.deepEqual(writes, []);
}
});

test('identical CPU results do not rewrite the bot comment', async () => {
const body = mergeCPUReport(report, null, 'abc');
const { github, writes } = mockGitHub({ comments: [{ id: 9, user: { login: 'github-actions[bot]' }, body }] });
assert.equal(await publishCPUReport(github, repo, run, report), true);
assert.deepEqual(writes, []);
});

test('published reports identify the run attempt and remain idempotent', async () => {
const identified = { ...run, id: 123, run_attempt: 2 };
const first = mockGitHub();
assert.equal(await publishCPUReport(first.github, repo, identified, report), true);
const body = first.writes[0][1].body;
assert.ok(body.includes('<!-- dagger-benchmark-run:123:2 -->'));
const second = mockGitHub({ comments: [{ id: 9, user: { login: 'github-actions[bot]' }, body }] });
assert.equal(await publishCPUReport(second.github, repo, identified, report), true);
assert.deepEqual(second.writes, []);
});
76 changes: 76 additions & 0 deletions .github/scripts/benchmark-run.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const { findCurrentPull } = require('./benchmark-comment.cjs');
const { marker } = require('./benchmark-report.cjs');

const workflowPath = '.github/workflows/CI.yml';
const summaryJob = 'Benchmarks (combined summary)';

// Query GitHub's run metadata, never a caller-supplied artifact/source location.
// A completed benchmark summary need not mean the rest of CI has finished.
async function resolveBenchmarkRun(github, repo, runId) {
if (!/^[1-9]\d*$/.test(String(runId)) || !Number.isSafeInteger(Number(runId))) {
throw new Error('Expected a positive workflow run ID');
}
const { data: run } = await github.rest.actions.getWorkflowRun({ ...repo, run_id: Number(runId) });
if (run.path !== workflowPath || run.event !== 'pull_request' || run.conclusion === 'cancelled') return null;
if (!await findCurrentPull(github, repo, run)) return null;
const { data } = await github.rest.actions.listJobsForWorkflowRun({
...repo, run_id: run.id, filter: 'latest', per_page: 100,
});
// Fail closed if CI outgrows this bound instead of trusting a partial list.
if (data.total_count > 100) throw new Error('CI job listing exceeds the recovery bound');
const summary = data.jobs.find(job => job.name === summaryJob);
if (!summary || summary.status !== 'completed' || ['cancelled', 'skipped'].includes(summary.conclusion)) return null;
const { data: artifacts } = await github.rest.actions.listWorkflowRunArtifacts({
...repo, run_id: run.id, per_page: 100,
});
if (artifacts.total_count > 100) throw new Error('CI artifact listing exceeds the recovery bound');
if (!artifacts.artifacts.some(artifact => !artifact.expired &&
/^benchmark-results-(default|distributed|distributed-threads|mpi|mpi-threads)-(array|linalg|sparse|stencil)$/.test(artifact.name))) return null;
return run;
}

// At most 100 recent runs/open PRs and 10 candidate inspections per tick.
// Rotate the inspection window so an unfinished old run cannot starve peers.
// Older runs and busy threads remain recoverable through explicit dispatch.
async function discoverBenchmarkRun(github, repo, now = Date.now()) {
const { data: { workflow_runs: runs } } = await github.rest.actions.listWorkflowRuns({
...repo, workflow_id: 'CI.yml', event: 'pull_request', per_page: 100,
});
const { data: pulls } = await github.rest.pulls.list({ ...repo, state: 'open', per_page: 100 });
const seenHeads = new Set();
const candidates = runs.filter(run => run.path === workflowPath && run.event === 'pull_request' &&
run.conclusion !== 'cancelled' && run.head_repository?.id &&
pulls.filter(pr => pr.state === 'open' && pr.head.sha === run.head_sha &&
pr.head.repo?.id === run.head_repository.id && pr.head.ref === run.head_branch).length === 1)
.sort((a, b) => b.id - a.id)
.filter(run => {
const key = JSON.stringify([run.head_repository.id, run.head_branch, run.head_sha]);
if (seenHeads.has(key)) return false;
seenHeads.add(key);
return true;
})
.sort((a, b) => a.id - b.id);
if (!candidates.length) return null;
const limit = Math.min(10, candidates.length);
const start = Math.floor(now / 300000) % candidates.length;
for (let index = 0; index < limit; index++) {
const candidate = candidates[(start + index) % candidates.length];
const pull = pulls.find(pr => pr.head.sha === candidate.head_sha &&
pr.head.repo?.id === candidate.head_repository.id && pr.head.ref === candidate.head_branch);
const { data: comments } = await github.rest.issues.listComments({
...repo, issue_number: pull.number, per_page: 100,
});
// Do not repeatedly select an identical published run or trust a partial
// comment inventory. The explicit dispatch path has no discovery window.
if (comments.length === 100 || comments.some(comment =>
comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(marker) &&
comment.body.includes(`<!-- dagger-benchmark-head:${candidate.head_sha} -->`) &&
comment.body.includes(`<!-- dagger-benchmark-run:${candidate.id}:${candidate.run_attempt} -->`) &&
comment.body.includes(`](${candidate.html_url})`))) continue;
const ready = await resolveBenchmarkRun(github, repo, candidate.id);
if (ready) return ready;
}
return null;
}

module.exports = { resolveBenchmarkRun, discoverBenchmarkRun };
153 changes: 153 additions & 0 deletions .github/scripts/benchmark-run.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { resolveBenchmarkRun, discoverBenchmarkRun } = require('./benchmark-run.cjs');

const repo = { owner: 'JuliaParallel', repo: 'Dagger.jl' };
const run = {
id: 46687686156, run_attempt: 1, path: '.github/workflows/CI.yml', event: 'pull_request',
status: 'in_progress', conclusion: null, head_sha: 'abc', head_branch: 'fix',
html_url: 'https://github.com/JuliaParallel/Dagger.jl/actions/runs/46687686156',
head_repository: { id: 42, owner: { login: 'author' } }, pull_requests: [],
};
const pull = { number: 858, state: 'open', head: { sha: 'abc', ref: 'fix', repo: { id: 42 } } };
const summary = { name: 'Benchmarks (combined summary)', status: 'completed', conclusion: 'success' };
function mock({ currentRun = run, pulls = [pull], jobs = [summary], count = jobs.length, artifacts = [{ name: 'benchmark-results-default-array', expired: false }] } = {}) {
const calls = [];
const rest = {
actions: {
listWorkflowRunArtifacts: async params => ({ data: { total_count: artifacts.length, artifacts } }),
getWorkflowRun: async params => { calls.push(['run', params]); return { data: currentRun }; },
listJobsForWorkflowRun: async params => { calls.push(['jobs', params]); return { data: { total_count: count, jobs } }; },
},
pulls: { list: async params => { calls.push(['pulls', params]); return pulls; } },
};
return { github: { rest, paginate: (fn, params) => fn(params) }, calls };
}

test('benchmark completion is sufficient while unrelated macOS remains queued', async () => {
const { github, calls } = mock({ jobs: [summary, { name: 'macOS', status: 'queued' }] });
assert.equal(await resolveBenchmarkRun(github, repo, String(run.id)), run);
assert.deepEqual(calls.find(([name]) => name === 'jobs')[1], { ...repo, run_id: run.id, filter: 'latest', per_page: 100 });
});

test('a failed benchmark summary can publish its actual failures', async () => {
const { github } = mock({ jobs: [{ ...summary, conclusion: 'failure' }] });
assert.equal(await resolveBenchmarkRun(github, repo, run.id), run);
});

test('incomplete, skipped or cancelled summaries cannot publish', async () => {
for (const jobs of [[], [{ ...summary, status: 'in_progress' }],
[{ ...summary, conclusion: 'cancelled' }], [{ ...summary, conclusion: 'skipped' }]]) {
assert.equal(await resolveBenchmarkRun(mock({ jobs }).github, repo, run.id), null);
}
});

test('wrong workflows, non-PR runs and cancelled runs stop before artifact/job lookup', async () => {
for (const patch of [{ path: '.github/workflows/other.yml' }, { event: 'push' }, { conclusion: 'cancelled' }]) {
const { github, calls } = mock({ currentRun: { ...run, ...patch } });
assert.equal(await resolveBenchmarkRun(github, repo, run.id), null);
assert.deepEqual(calls.map(([name]) => name), ['run']);
}
});

test('closed, moved, foreign and ambiguous PR heads cannot select artifacts', async () => {
for (const pulls of [[], [{ ...pull, state: 'closed' }],
[{ ...pull, head: { ...pull.head, sha: 'new' } }],
[{ ...pull, head: { ...pull.head, repo: { id: 77 } } }], [pull, { ...pull, number: 859 }]]) {
const { github, calls } = mock({ pulls });
assert.equal(await resolveBenchmarkRun(github, repo, run.id), null);
assert.ok(!calls.some(([name]) => name === 'jobs'));
}
});

test('invalid run IDs and truncated job inventories fail closed', async () => {
for (const id of ['0', '-1', '1.5', 'x', '1;echo wrong', '9007199254740992']) {
const { github, calls } = mock();
await assert.rejects(resolveBenchmarkRun(github, repo, id), /positive workflow run ID/);
assert.equal(calls.length, 0);
}
await assert.rejects(resolveBenchmarkRun(mock({ count: 101 }).github, repo, run.id), /listing exceeds/);
});

test('expired, absent and unrelated artifacts are not ready results', async () => {
for (const artifacts of [[], [{ name: 'benchmark-results-default-array', expired: true }], [{ name: 'other', expired: false }]]) {
assert.equal(await resolveBenchmarkRun(mock({ artifacts }).github, repo, run.id), null);
}
});

function recoveryMock({ runs = [run], pulls = [pull], comments = [], ready = new Set([run.id]) } = {}) {
const { github, calls } = mock({ pulls });
github.rest.pulls.list = async () => ({ data: pulls });
github.paginate = async (fn, params) => { const result = await fn(params); return result.data ?? result; };
github.rest.actions.listWorkflowRuns = async params => {
assert.deepEqual(params, { ...repo, workflow_id: 'CI.yml', event: 'pull_request', per_page: 100 });
return { data: { workflow_runs: runs } };
};
github.rest.actions.getWorkflowRun = async ({ run_id }) => {
calls.push(['run', run_id]); return { data: runs.find(candidate => candidate.id === run_id) };
};
github.rest.actions.listJobsForWorkflowRun = async ({ run_id }) => ({ data: {
total_count: 1, jobs: [{ ...summary, status: ready.has(run_id) ? 'completed' : 'in_progress' }],
} });
github.rest.issues = { listComments: async params => {
calls.push(['comments', params]); return { data: comments };
} };
return { github, calls };
}

test('scheduled recovery selects benchmark-ready CI while other jobs remain running', async () => {
const { github, calls } = recoveryMock();
assert.equal(await discoverBenchmarkRun(github, repo, 0), run);
assert.equal(calls.filter(([name]) => name === 'run').length, 1);
});

test('scheduled discovery skips already-published bot reports and full comment pages', async () => {
for (const comments of [Array(100).fill({}), [{ user: { login: 'github-actions[bot]' },
body: `<!-- dagger-benchmarks -->\n<!-- dagger-benchmark-head:abc -->\n<!-- dagger-benchmark-run:46687686156:1 -->\n[Full results](${run.html_url})` }]]) {
const { github, calls } = recoveryMock({ comments });
assert.equal(await discoverBenchmarkRun(github, repo, 0), null);
assert.ok(!calls.some(([name]) => name === 'run'));
}
});

test('a contributor cannot suppress recovery by spoofing a report marker', async () => {
const { github } = recoveryMock({ comments: [{ user: { login: 'contributor' },
body: `<!-- dagger-benchmarks -->\n<!-- dagger-benchmark-head:abc -->\n<!-- dagger-benchmark-run:46687686156:1 -->\n[Full results](${run.html_url})` }] });
assert.equal(await discoverBenchmarkRun(github, repo, 0), run);
});

test('discovery is bounded and rotates past unfinished runs', async () => {
const runs = Array.from({ length: 15 }, (_, index) => ({ ...run, id: 100 + index,
head_sha: `sha-${index}`, head_branch: `fix-${index}`,
html_url: `https://github.com/JuliaParallel/Dagger.jl/actions/runs/${100 + index}` }));
const pulls = runs.map((candidate, index) => ({ ...pull, number: 900 + index,
head: { ...pull.head, sha: candidate.head_sha, ref: candidate.head_branch } }));
const { github, calls } = recoveryMock({ runs, pulls, ready: new Set([110]) });
assert.equal(await discoverBenchmarkRun(github, repo, 0), null);
assert.equal(calls.filter(([name]) => name === 'run').length, 10);
assert.equal((await discoverBenchmarkRun(github, repo, 300000)).id, 110);
});

test('discovery filters cancelled, moved and foreign heads before inspection', async () => {
const runs = [{ ...run, conclusion: 'cancelled' }, { ...run, head_sha: 'old' },
{ ...run, head_repository: { id: 80 } }];
const { github, calls } = recoveryMock({ runs });
assert.equal(await discoverBenchmarkRun(github, repo, 0), null);
assert.equal(calls.length, 0);
});


test('scheduled recovery never replaces a newer same-head report with an older run', async () => {
const newer = { ...run, id: run.id + 1, html_url: run.html_url + '1' };
const { github, calls } = recoveryMock({ runs: [run, newer], ready: new Set([newer.id]) });
assert.equal((await discoverBenchmarkRun(github, repo, 0)).id, newer.id);
assert.deepEqual(calls.filter(([name]) => name === 'run').map(([, id]) => id), [newer.id]);
});


test('a new attempt of the same run is not suppressed by its previous report', async () => {
const repeated = { ...run, run_attempt: 2 };
const { github } = recoveryMock({ runs: [repeated], comments: [{ user: { login: 'github-actions[bot]' },
body: `<!-- dagger-benchmarks -->\n<!-- dagger-benchmark-head:abc -->\n<!-- dagger-benchmark-run:${run.id}:1 -->\n[Full results](${run.html_url})` }] });
assert.equal((await discoverBenchmarkRun(github, repo, 0)).run_attempt, 2);
});
Loading
Loading