From 011cc8efb4b753a15489bdd0253e20fdb1cf99f8 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 20:23:10 -0700 Subject: [PATCH 1/2] Allow trusted benchmark comment recovery before CI finishes The combined benchmark report can finish while unrelated macOS jobs remain queued. Add an explicit CI run-ID dispatch path that checks benchmark readiness and the current open PR before rendering with default-branch code. Keep rendering read-only and publication separate; recheck cancellation, run attempt and exact PR head before writing, and leave identical bot comments untouched. Validation: existing report/comment tests plus run-resolution regressions pass 16/16. The queued-macOS fixture selects the completed benchmark summary; cancelled, stale, foreign, ambiguous and incomplete inputs fail closed. No hosted workflow dispatch was run. Written by an AI agent on jpsamaroo's review feedback. --- .github/scripts/benchmark-comment.cjs | 18 ++++-- .github/scripts/benchmark-comment.test.cjs | 7 +++ .github/scripts/benchmark-run.cjs | 25 ++++++++ .github/scripts/benchmark-run.test.cjs | 68 ++++++++++++++++++++ .github/workflows/BenchmarkComments.yml | 72 +++++++++++++++++++--- .github/workflows/CI.yml | 2 +- AGENTS.md | 9 +++ 7 files changed, 186 insertions(+), 15 deletions(-) create mode 100644 .github/scripts/benchmark-run.cjs create mode 100644 .github/scripts/benchmark-run.test.cjs diff --git a/.github/scripts/benchmark-comment.cjs b/.github/scripts/benchmark-comment.cjs index ec992ae79..54f559acf 100644 --- a/.github/scripts/benchmark-comment.cjs +++ b/.github/scripts/benchmark-comment.cjs @@ -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. @@ -25,15 +25,23 @@ 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); + if (existing?.body === body) return true; if (existing) { await github.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); } else { @@ -42,4 +50,4 @@ async function publishCPUReport(github, repo, run, report) { return true; } -module.exports = { mergeCPUReport, publishCPUReport }; +module.exports = { mergeCPUReport, findCurrentPull, publishCPUReport }; diff --git a/.github/scripts/benchmark-comment.test.cjs b/.github/scripts/benchmark-comment.test.cjs index a36f95f38..2da562621 100644 --- a/.github/scripts/benchmark-comment.test.cjs +++ b/.github/scripts/benchmark-comment.test.cjs @@ -77,3 +77,10 @@ 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, []); +}); diff --git a/.github/scripts/benchmark-run.cjs b/.github/scripts/benchmark-run.cjs new file mode 100644 index 000000000..e49e5f76f --- /dev/null +++ b/.github/scripts/benchmark-run.cjs @@ -0,0 +1,25 @@ +const { findCurrentPull } = require('./benchmark-comment.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; + return run; +} + +module.exports = { resolveBenchmarkRun }; diff --git a/.github/scripts/benchmark-run.test.cjs b/.github/scripts/benchmark-run.test.cjs new file mode 100644 index 000000000..eb5a33346 --- /dev/null +++ b/.github/scripts/benchmark-run.test.cjs @@ -0,0 +1,68 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { resolveBenchmarkRun } = require('./benchmark-run.cjs'); + +const repo = { owner: 'JuliaParallel', repo: 'Dagger.jl' }; +const run = { + id: 46687686156, path: '.github/workflows/CI.yml', event: 'pull_request', + status: 'in_progress', conclusion: null, head_sha: 'abc', head_branch: 'fix', + 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 } = {}) { + const calls = []; + const rest = { + actions: { + 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/); +}); diff --git a/.github/workflows/BenchmarkComments.yml b/.github/workflows/BenchmarkComments.yml index 630828696..195a34ecd 100644 --- a/.github/workflows/BenchmarkComments.yml +++ b/.github/workflows/BenchmarkComments.yml @@ -1,6 +1,12 @@ name: Benchmark comments on: + workflow_dispatch: + inputs: + run_id: + description: CI run whose benchmark jobs have finished + required: true + type: string workflow_run: workflows: [CI] types: [completed] @@ -8,12 +14,46 @@ on: permissions: {} concurrency: - group: ${{ github.workflow }}-${{ github.event.workflow_run.head_sha }} + group: ${{ github.workflow }}-${{ github.event.workflow_run.id || inputs.run_id }} cancel-in-progress: false jobs: + resolve: + if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.path == '.github/workflows/CI.yml' && github.event.workflow_run.conclusion != 'cancelled') + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: read + contents: read + pull-requests: read + outputs: + run_id: ${{ steps.run.outputs.run_id }} + head: ${{ steps.run.outputs.head }} + attempt: ${{ steps.run.outputs.attempt }} + url: ${{ steps.run.outputs.url }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Validate benchmark readiness and current PR + id: run + uses: actions/github-script@v9 + env: + CI_RUN_ID: ${{ github.event.workflow_run.id || inputs.run_id }} + with: + script: | + const { resolveBenchmarkRun } = require('./.github/scripts/benchmark-run.cjs'); + const run = await resolveBenchmarkRun(github, context.repo, process.env.CI_RUN_ID); + if (!run) return core.info('No ready benchmark report for an open current-head PR.'); + core.setOutput('run_id', String(run.id)); + core.setOutput('head', run.head_sha); + core.setOutput('attempt', String(run.run_attempt)); + core.setOutput('url', run.html_url); + render: - if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.path == '.github/workflows/CI.yml' && github.event.workflow_run.conclusion != 'cancelled' + needs: resolve + if: needs.resolve.outputs.run_id != '' runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -22,48 +62,62 @@ jobs: outputs: body: ${{ steps.report.outputs.body }} steps: - # workflow_run's SHA belongs to the default branch. Run only its renderer. + # Never check out the PR, including for a manually selected CI run. - uses: actions/checkout@v7 with: - ref: ${{ github.sha }} + ref: ${{ github.event.repository.default_branch }} persist-credentials: false - uses: actions/download-artifact@v8 with: github-token: ${{ github.token }} - run-id: ${{ github.event.workflow_run.id }} + run-id: ${{ needs.resolve.outputs.run_id }} pattern: benchmark-results-* path: ${{ runner.temp }}/dagger-benchmark-results - name: Render benchmark JSON id: report uses: actions/github-script@v9 + env: + CI_RUN_URL: ${{ needs.resolve.outputs.url }} with: script: | const { buildReport } = require('./.github/scripts/benchmark-report.cjs'); const root = require('node:path').join(process.env.RUNNER_TEMP, 'dagger-benchmark-results'); - const body = buildReport(root, context.payload.workflow_run.html_url, { requireResults: true }); + const body = buildReport(root, process.env.CI_RUN_URL, { requireResults: true }); if (body) core.setOutput('body', body); publish: - needs: render + needs: [resolve, render] if: needs.render.outputs.body != '' runs-on: ubuntu-latest timeout-minutes: 5 + concurrency: + group: benchmark-comment-${{ needs.resolve.outputs.head }} + cancel-in-progress: false permissions: + actions: read contents: read pull-requests: write steps: # The write-token job receives rendered text and runs default-branch code. - uses: actions/checkout@v7 with: - ref: ${{ github.sha }} + ref: ${{ github.event.repository.default_branch }} persist-credentials: false - name: Update PR benchmark comment uses: actions/github-script@v9 env: + CI_RUN_ID: ${{ needs.resolve.outputs.run_id }} + CI_RUN_ATTEMPT: ${{ needs.resolve.outputs.attempt }} BENCHMARK_REPORT: ${{ needs.render.outputs.body }} with: script: | const { publishCPUReport } = require('./.github/scripts/benchmark-comment.cjs'); + const { data: run } = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: Number(process.env.CI_RUN_ID), + }); + if (run.conclusion === 'cancelled' || String(run.run_attempt) !== process.env.CI_RUN_ATTEMPT) { + return core.info('CI run was cancelled or restarted while rendering.'); + } const published = await publishCPUReport( - github, context.repo, context.payload.workflow_run, process.env.BENCHMARK_REPORT); + github, context.repo, run, process.env.BENCHMARK_REPORT); if (!published) core.info('No open PR matches the benchmark run.'); diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index a21f04c7c..4c3669d11 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -407,7 +407,7 @@ jobs: with: persist-credentials: false - name: Test benchmark report rendering - run: node --test .github/scripts/benchmark-report.test.cjs .github/scripts/benchmark-comment.test.cjs + run: node --test .github/scripts/benchmark-report.test.cjs .github/scripts/benchmark-comment.test.cjs .github/scripts/benchmark-run.test.cjs - name: Download benchmark results if: always() continue-on-error: true diff --git a/AGENTS.md b/AGENTS.md index 966591995..17c74aa21 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1325,3 +1325,12 @@ this section verbatim). Each entry is one bullet starting with `- `. coincidence. Test those fields with different values. Keep the Float64 case on capable hardware and run the same behavioral assertion with a supported initializer elsewhere; a vendor-wide skip loses coverage on devices that support it. + +120. **A workflow-completion trigger waits for unrelated jobs too.** + Benchmark artifacts and their combined summary can be complete while CI + still waits for a macOS runner. A `workflow_run: completed` comment job + cannot publish them yet. Recovery should validate the CI run and completed + benchmark summary, render artifacts with default-branch code and a read + token, then recheck the open PR's exact repository/branch/head before the + separate write-token job posts. Keep artifact contents out of executable + code, skip cancelled runs, and do not rewrite identical bot comments. From db941ecb920af1446f982f2b2f03ba672b33c3a2 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Tue, 1 Dec 2026 20:26:04 -0700 Subject: [PATCH 2/2] Recover benchmark comments with bounded trusted discovery Check recent current-head CI runs every five minutes so a finished benchmark matrix can be reported while unrelated tests still wait. Inspect at most ten rotated candidates from the latest hundred runs and open PRs, choose only the newest run per head, and reuse the same readiness, artifact and exact-head publication checks. Track the run attempt so an earlier report cannot hide rerun results. Skip reported runs and full comment pages; explicit dispatch covers older or busy cases. No PR code is checked out or executed. Validation: all 25 existing/new Node tests pass, including queued macOS, invalid/cancelled/stale heads, absent/expired artifacts, bounded rotating discovery, newest-run selection, rerun attempts and identical-comment no-op. Workflow YAML/security structure and all inline JavaScript parse checks pass. No actual workflow dispatch, schedule or comment write was performed. Written by an AI agent on jpsamaroo's review feedback. --- .github/scripts/benchmark-comment.cjs | 5 +- .github/scripts/benchmark-comment.test.cjs | 11 +++ .github/scripts/benchmark-run.cjs | 53 ++++++++++++- .github/scripts/benchmark-run.test.cjs | 91 +++++++++++++++++++++- .github/workflows/BenchmarkComments.yml | 13 +++- AGENTS.md | 2 + 6 files changed, 166 insertions(+), 9 deletions(-) diff --git a/.github/scripts/benchmark-comment.cjs b/.github/scripts/benchmark-comment.cjs index 54f559acf..0f94bcc56 100644 --- a/.github/scripts/benchmark-comment.cjs +++ b/.github/scripts/benchmark-comment.cjs @@ -40,7 +40,10 @@ async function publishCPUReport(github, repo, run, report) { 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`); + } if (existing?.body === body) return true; if (existing) { await github.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); diff --git a/.github/scripts/benchmark-comment.test.cjs b/.github/scripts/benchmark-comment.test.cjs index 2da562621..bf327f8e4 100644 --- a/.github/scripts/benchmark-comment.test.cjs +++ b/.github/scripts/benchmark-comment.test.cjs @@ -84,3 +84,14 @@ test('identical CPU results do not rewrite the bot comment', async () => { 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('')); + 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, []); +}); diff --git a/.github/scripts/benchmark-run.cjs b/.github/scripts/benchmark-run.cjs index e49e5f76f..61261a100 100644 --- a/.github/scripts/benchmark-run.cjs +++ b/.github/scripts/benchmark-run.cjs @@ -1,4 +1,5 @@ const { findCurrentPull } = require('./benchmark-comment.cjs'); +const { marker } = require('./benchmark-report.cjs'); const workflowPath = '.github/workflows/CI.yml'; const summaryJob = 'Benchmarks (combined summary)'; @@ -19,7 +20,57 @@ async function resolveBenchmarkRun(github, repo, runId) { 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; } -module.exports = { resolveBenchmarkRun }; +// 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(``) && + comment.body.includes(``) && + 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 }; diff --git a/.github/scripts/benchmark-run.test.cjs b/.github/scripts/benchmark-run.test.cjs index eb5a33346..189a2f5e0 100644 --- a/.github/scripts/benchmark-run.test.cjs +++ b/.github/scripts/benchmark-run.test.cjs @@ -1,19 +1,21 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const { resolveBenchmarkRun } = require('./benchmark-run.cjs'); +const { resolveBenchmarkRun, discoverBenchmarkRun } = require('./benchmark-run.cjs'); const repo = { owner: 'JuliaParallel', repo: 'Dagger.jl' }; const run = { - id: 46687686156, path: '.github/workflows/CI.yml', event: 'pull_request', + 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 } = {}) { +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 } }; }, }, @@ -66,3 +68,86 @@ test('invalid run IDs and truncated job inventories fail closed', async () => { } 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: `\n\n\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: `\n\n\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: `\n\n\n[Full results](${run.html_url})` }] }); + assert.equal((await discoverBenchmarkRun(github, repo, 0)).run_attempt, 2); +}); diff --git a/.github/workflows/BenchmarkComments.yml b/.github/workflows/BenchmarkComments.yml index 195a34ecd..4ffe24ee9 100644 --- a/.github/workflows/BenchmarkComments.yml +++ b/.github/workflows/BenchmarkComments.yml @@ -1,6 +1,9 @@ name: Benchmark comments on: + schedule: + # Bounded recovery for CI runs whose benchmark matrix finished first. + - cron: '*/5 * * * *' workflow_dispatch: inputs: run_id: @@ -14,12 +17,12 @@ on: permissions: {} concurrency: - group: ${{ github.workflow }}-${{ github.event.workflow_run.id || inputs.run_id }} + group: ${{ github.workflow }}-${{ github.event.workflow_run.id || inputs.run_id || 'recovery' }} cancel-in-progress: false jobs: resolve: - if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.path == '.github/workflows/CI.yml' && github.event.workflow_run.conclusion != 'cancelled') + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || (github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.path == '.github/workflows/CI.yml' && github.event.workflow_run.conclusion != 'cancelled') runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -43,8 +46,10 @@ jobs: CI_RUN_ID: ${{ github.event.workflow_run.id || inputs.run_id }} with: script: | - const { resolveBenchmarkRun } = require('./.github/scripts/benchmark-run.cjs'); - const run = await resolveBenchmarkRun(github, context.repo, process.env.CI_RUN_ID); + const { resolveBenchmarkRun, discoverBenchmarkRun } = require('./.github/scripts/benchmark-run.cjs'); + const run = context.eventName === 'schedule' + ? await discoverBenchmarkRun(github, context.repo) + : await resolveBenchmarkRun(github, context.repo, process.env.CI_RUN_ID); if (!run) return core.info('No ready benchmark report for an open current-head PR.'); core.setOutput('run_id', String(run.id)); core.setOutput('head', run.head_sha); diff --git a/AGENTS.md b/AGENTS.md index 17c74aa21..6d928e777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1334,3 +1334,5 @@ this section verbatim). Each entry is one bullet starting with `- `. token, then recheck the open PR's exact repository/branch/head before the separate write-token job posts. Keep artifact contents out of executable code, skip cancelled runs, and do not rewrite identical bot comments. + A rerun retains its run ID and head: track the run attempt as well when + deciding whether that report was already published.