Skip to content
Merged
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
92 changes: 92 additions & 0 deletions .github/scripts/cancel-pr-ci.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
'use strict';

function belongsToPr(run, pullRequest) {
if (run.pull_requests?.length) {
return run.pull_requests.some((pr) => pr.number === pullRequest.number);
}
// GitHub can clear this association after a PR closes. Old force-pushed
// commits may no longer link to the PR either, so use the source repository
// and branch during the PR's lifetime, never just its latest HEAD SHA.
const repositoryId = pullRequest.head.repo?.id;
const created = Date.parse(run.created_at);
return Number.isInteger(repositoryId) &&
run.head_repository?.id === repositoryId &&
run.head_branch === pullRequest.head.ref &&
created >= Date.parse(pullRequest.created_at) &&
created <= Date.parse(pullRequest.closed_at);
}

async function cancelClosedPrCi({ github, context, core }) {
const pullRequest = context.payload.pull_request;
if (context.payload.action !== 'closed' || !Number.isInteger(pullRequest?.number)) {
throw new Error('A closed pull request event is required');
}

const { owner, repo } = context.repo;
const number = pullRequest.number;
const { data: current } = await github.rest.pulls.get({
owner,
repo,
pull_number: number,
});
if (current.state !== 'closed') {
core.notice(`PR #${number} has reopened; keeping its CI runs.`);
return [];
}

// Collect every page before cancelling: all revisions belong to the PR,
// including queued runs for older HEADs. A branch name alone is not identity.
const runs = await github.paginate(github.rest.actions.listWorkflowRuns, {
owner,
repo,
workflow_id: 'ci.yml',
event: 'pull_request',
branch: current.head.ref,
created: `${current.created_at}..${current.closed_at}`,
per_page: 100,
});
const cancelled = [];
const errors = [];
for (const run of runs) {
if (
run.event !== 'pull_request' ||
run.status === 'completed' ||
!belongsToPr(run, current)
) {
continue;
}
try {
await github.rest.actions.cancelWorkflowRun({ owner, repo, run_id: run.id });
cancelled.push(run.id);
core.info(`Requested cancellation of CI run ${run.id} for closed PR #${number}.`);
} catch (error) {
// The run may finish between listing and cancellation. Other conflicts
// and API failures must fail this workflow rather than report success.
let failure = error;
if (error.status === 409) {
try {
const { data: latest } = await github.rest.actions.getWorkflowRun({
owner,
repo,
run_id: run.id,
});
if (latest.status === 'completed') {
core.info(`CI run ${run.id} already completed.`);
continue;
}
} catch (lookupError) {
failure = lookupError;
}
}
errors.push(failure);
core.warning(`Could not cancel CI run ${run.id}: ${failure.message}`);
}
}
if (errors.length > 0) {
throw new AggregateError(errors, `Could not cancel ${errors.length} CI run(s) for PR #${number}`);
}
core.info(`Requested cancellation of ${cancelled.length} unfinished CI run(s) for PR #${number}.`);
return cancelled;
}

module.exports = { cancelClosedPrCi };
218 changes: 218 additions & 0 deletions .github/scripts/cancel-pr-ci.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
'use strict';

const assert = require('node:assert/strict');
const test = require('node:test');
const { cancelClosedPrCi } = require('./cancel-pr-ci.cjs');

function run(id, overrides = {}) {
return {
id,
event: 'pull_request',
status: 'in_progress',
head_branch: 'topic',
head_sha: `revision-${id}`,
head_repository: { id: 100 },
created_at: '2026-10-24T11:00:00Z',
pull_requests: [{ number: 42 }],
...overrides,
};
}

function fixture({ pages = [[]], current = {}, cancel, getRun } = {}) {
const calls = { cancelled: [], listed: [], notices: [], warnings: [] };
const listWorkflowRuns = async () => assert.fail('Use pagination to find older revisions');
const github = {
rest: {
pulls: {
get: async (args) => {
assert.deepEqual(args, { owner: 'lexmount', repo: 'moli', pull_number: 42 });
return {
data: {
number: 42,
state: 'closed',
merged: true,
created_at: '2026-10-24T10:00:00Z',
closed_at: '2026-10-24T12:00:00Z',
head: { ref: 'topic', sha: 'latest-revision', repo: { id: 100 } },
...current,
},
};
},
},
actions: {
listWorkflowRuns,
cancelWorkflowRun: async (args) => {
calls.cancelled.push(args.run_id);
assert.equal(args.owner, 'lexmount');
assert.equal(args.repo, 'moli');
if (cancel) await cancel(args.run_id);
},
getWorkflowRun: async (args) => {
assert.ok(getRun, 'Unexpected workflow status lookup');
return { data: await getRun(args.run_id) };
},
},
},
paginate: async (method, args) => {
assert.equal(method, listWorkflowRuns);
calls.listed.push(args);
return pages.flat();
},
};
const context = {
repo: { owner: 'lexmount', repo: 'moli' },
payload: { action: 'closed', pull_request: { number: 42 } },
};
const core = {
info: () => {},
notice: (message) => calls.notices.push(message),
warning: (message) => calls.warnings.push(message),
};
return { github, context, core, calls };
}

test('merging a PR cancels every unfinished revision across all pages', async () => {
const firstPage = Array.from({ length: 100 }, (_, i) =>
run(i + 1, { status: 'completed' })
);
firstPage[0] = run(1, { status: 'queued' });
const f = fixture({ pages: [firstPage, [
run(101),
run(102, { status: 'waiting' }),
run(103, { status: 'pending' }),
run(104, { status: 'requested' }),
]] });

assert.deepEqual(await cancelClosedPrCi(f), [1, 101, 102, 103, 104]);
assert.deepEqual(f.calls.cancelled, [1, 101, 102, 103, 104]);
assert.deepEqual(f.calls.listed, [{
owner: 'lexmount',
repo: 'moli',
workflow_id: 'ci.yml',
event: 'pull_request',
branch: 'topic',
created: '2026-10-24T10:00:00Z..2026-10-24T12:00:00Z',
per_page: 100,
}]);
});

test('closing an unmerged PR also cancels its queued validation', async () => {
const f = fixture({ current: { merged: false }, pages: [[run(1, { status: 'queued' })]] });
assert.deepEqual(await cancelClosedPrCi(f), [1]);
});

test('closed PRs with empty run associations still cancel older and force-pushed revisions', async () => {
const f = fixture({ pages: [[
run(1, { status: 'queued', pull_requests: [] }),
run(2, { pull_requests: [] }),
]] });
assert.deepEqual(await cancelClosedPrCi(f), [1, 2]);
});

test('empty associations must match the source repository, branch, and PR lifetime', async () => {
const f = fixture({ pages: [[
run(1, { pull_requests: [], head_repository: { id: 999 } }),
run(2, { pull_requests: [], head_branch: 'another-topic' }),
run(3, { pull_requests: [], created_at: '2026-10-24T09:59:59Z' }),
run(4, { pull_requests: [], created_at: '2026-10-24T12:00:01Z' }),
run(5, { pull_requests: [], created_at: undefined }),
run(6, { pull_requests: [], head_repository: undefined }),
]] });
assert.deepEqual(await cancelClosedPrCi(f), []);
assert.deepEqual(f.calls.cancelled, []);
});

test('closing a fork PR matches the fork repository rather than a same-named local branch', async () => {
const f = fixture({
current: { head: { ref: 'topic', repo: { id: 999 } } },
pages: [[
run(1, { pull_requests: [], head_repository: { id: 999 } }),
run(2, { pull_requests: [] }),
]],
});
assert.deepEqual(await cancelClosedPrCi(f), [1]);
});

test('preserves completed runs, other PRs with the same branch, and main or manual runs', async () => {
const f = fixture({ pages: [[
run(1, { status: 'completed' }),
run(2, { pull_requests: [{ number: 43 }] }),
run(3, { event: 'push' }),
run(4, { event: 'workflow_dispatch' }),
run(5, { pull_requests: [], head_repository: undefined }),
run(6, { pull_requests: undefined, head_repository: undefined }),
run(7, { pull_requests: [{ number: 43 }, { number: 42 }] }),
]] });
assert.deepEqual(await cancelClosedPrCi(f), [7]);
assert.deepEqual(f.calls.cancelled, [7]);
});

test('a delayed close event does not cancel a reopened PR', async () => {
const f = fixture({ current: { state: 'open' }, pages: [[run(1)]] });
assert.deepEqual(await cancelClosedPrCi(f), []);
assert.deepEqual(f.calls.listed, []);
assert.deepEqual(f.calls.cancelled, []);
assert.match(f.calls.notices[0], /reopened/);
});

test('ignores a completion race and still cancels the other revisions', async () => {
const f = fixture({
pages: [[run(1), run(2)]],
cancel: async (id) => {
if (id === 1) throw Object.assign(new Error('Run completed'), { status: 409 });
},
getRun: async (id) => {
assert.equal(id, 1);
return { status: 'completed' };
},
});
assert.deepEqual(await cancelClosedPrCi(f), [2]);
assert.deepEqual(f.calls.cancelled, [1, 2]);
assert.deepEqual(f.calls.warnings, []);
});

test('a conflict for a still-running revision fails without leaving later runs untouched', async () => {
const f = fixture({
pages: [[run(1), run(2)]],
cancel: async (id) => {
if (id === 1) throw Object.assign(new Error('Conflict'), { status: 409 });
},
getRun: async () => ({ status: 'in_progress' }),
});
await assert.rejects(cancelClosedPrCi(f), /Could not cancel 1 CI run/);
assert.deepEqual(f.calls.cancelled, [1, 2]);
});

test('permission errors fail the workflow while other revisions are still cancelled', async () => {
const f = fixture({
pages: [[run(1), run(2)]],
cancel: async (id) => {
if (id === 1) throw Object.assign(new Error('Forbidden'), { status: 403 });
},
});
await assert.rejects(cancelClosedPrCi(f), /Could not cancel 1 CI run/);
assert.deepEqual(f.calls.cancelled, [1, 2]);
assert.match(f.calls.warnings[0], /Forbidden/);
});

test('a failed status lookup after a cancellation conflict still attempts the other runs', async () => {
const f = fixture({
pages: [[run(1), run(2)]],
cancel: async (id) => {
if (id === 1) throw Object.assign(new Error('Conflict'), { status: 409 });
},
getRun: async () => { throw new Error('Lookup failed'); },
});
await assert.rejects(cancelClosedPrCi(f), /Could not cancel 1 CI run/);
assert.deepEqual(f.calls.cancelled, [1, 2]);
assert.match(f.calls.warnings[0], /Lookup failed/);
});

test('requires a closed PR event before using the Actions API', async () => {
for (const payload of [{ action: 'synchronize', pull_request: { number: 42 } }, { action: 'closed' }]) {
const f = fixture();
f.context.payload = payload;
await assert.rejects(cancelClosedPrCi(f), /closed pull request event is required/);
assert.deepEqual(f.calls.cancelled, []);
}
});
34 changes: 21 additions & 13 deletions .github/workflows/cancel-pr-ci.yml
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
name: Cancel closed PR CI

on:
pull_request:
pull_request_target:
types: [closed]

# Concurrency groups are shared across workflows in the repository. Starting
# this lightweight run cancels the matching validation run without scheduling
# the full CI suite for a pull request that can no longer be merged.
concurrency:
group: ci-${{ github.event.pull_request.number }}
cancel-in-progress: true

permissions: {}
# Run trusted default-branch code so closing an unmerged or fork PR can also
# cancel its validation. CI revisions otherwise run independently.
permissions:
actions: write
contents: read
pull-requests: read

jobs:
cancel:
name: Cancel superseded validation
name: Cancel closed PR validation
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Record cancellation
run: |
echo "Cancelled validation for closed PR #${{ github.event.pull_request.number }}."
- name: Checkout trusted cancellation helper
uses: actions/checkout@v4
with:
persist-credentials: false
ref: ${{ github.event.repository.default_branch }}

- name: Cancel unfinished PR CI runs
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
with:
script: |
const { cancelClosedPrCi } = require('./.github/scripts/cancel-pr-ci.cjs');
await cancelClosedPrCi({ github, context, core });
3 changes: 3 additions & 0 deletions moli-cdp-smoke/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ as infrastructure trouble or Chromium instability requires evidence and does
not change its exit status.
The workflow has no PR-wide cancellation group: pushing a new revision must
not cancel an older run before its Chromium suite and diagnostics finish.
Once a PR is merged or closed, the trusted `Cancel closed PR CI` workflow
requests cancellation of every unfinished CI run associated with that PR,
including queued runs for older revisions.

Each worker records the actual discovery version, engine, executable command,
and PID for its managed browser and any nested browser launches. Chromium
Expand Down
11 changes: 11 additions & 0 deletions moli-cdp-smoke/tests/test_ci_execution_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@


WORKFLOW = Path(__file__).resolve().parents[2] / ".github" / "workflows" / "ci.yml"
CANCEL_WORKFLOW = WORKFLOW.with_name("cancel-pr-ci.yml")


class CiExecutionPolicyTests(unittest.TestCase):
Expand All @@ -14,6 +15,16 @@ def test_new_revisions_do_not_cancel_older_ci_runs(self) -> None:
self.assertIsNone(re.search(r"^concurrency:", workflow, re.MULTILINE),
"Every revision must complete independently, including queued Chrome runs")

def test_closed_prs_cancel_runs_using_the_trusted_default_branch(self) -> None:
workflow = CANCEL_WORKFLOW.read_text()
self.assertRegex(workflow, r"pull_request_target:\s+types: \[closed\]")
self.assertIn("actions: write", workflow)
self.assertIn("pull-requests: read", workflow)
self.assertIn("persist-credentials: false", workflow)
self.assertIn("ref: ${{ github.event.repository.default_branch }}", workflow)
self.assertIn("require('./.github/scripts/cancel-pr-ci.cjs')", workflow)
self.assertIn("await cancelClosedPrCi({ github, context, core })", workflow)

def test_both_browser_jobs_require_full_runs_and_diagnostic_uploads(self) -> None:
workflow = WORKFLOW.read_text()
for name, engine in (("cdp-smoke", "moli"), ("cdp-smoke-chromium", "chromium")):
Expand Down
Loading