Skip to content

Commit 0444041

Browse files
ci(readiness): scope concurrency to bound PR refreshes (#2423)
* ci(readiness): scope concurrency to bound PR refreshes Squad PR Readiness used a workflow-level concurrency group keyed by head repository and branch. Every workflow_run delivery joins that group before any job's if: is evaluated. So skipped runs (fork and push runs of Squad CI, cancelled requests) cancelled real checklist refreshes, and PRs from one head branch to different bases cancelled each other. Split the writer into two jobs. bind joins no group and exposes the binding as job outputs. readiness runs only for a bound PR and joins squad-pr-readiness-<PR number> with cancel-in-progress. The bind job is named readiness-bind and added to SELF_CHECK_NAMES, because workflow_run check runs land on the dev tip, which is the head of any PR from dev. The split tests now check each job's checkout, require dependent jobs to wait for the binding, and simulate which group each delivery joins. Closes #2420 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(readiness): skip stale bound snapshots The bind job checks the PR head outside the posting job's concurrency group. A delivery could therefore bind head A, reach the posting job after head B was pushed and refreshed, and overwrite B's checklist with A's: scripts/pr-readiness.mjs queried CI for A without comparing it with the live PR head. run() now compares PR_HEAD_SHA with the live PR head when it first reads the PR, before any CI query, and again just before it writes. On a mismatch it logs one line naming both SHAs, writes nothing and exits 0. If the PR cannot be read before writing, it fails without writing. The posting job's group is now keyed by PR number and head SHA. Keyed by PR alone, such a late job could cancel the current head's refresh (cancel-in-progress) or replace it while pending, then skip as stale, so no checklist was posted for the current head. Refreshes of one head still share a group, so the newer one wins. Tests cover out-of-order completion: a late run, a head that moves while the checks run, an unreadable head, and a matching head that still writes. The concurrency simulation checks that a late run bound to an older head joins a different group from the current head's refresh. Closes #2420 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent e85b4d5 commit 0444041

4 files changed

Lines changed: 448 additions & 38 deletions

File tree

‎.github/workflows/squad-pr-readiness.yml‎

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ name: Squad PR Readiness
1515
# anything is written. See scripts/workflow-run-pr-binding.mjs.
1616
# - Squad CI runs carry no claim, so only GitHub's own
1717
# workflow_run.pull_requests (same-repository PRs) are bound, as before.
18+
#
19+
# Concurrency: only bound runs deduplicate, one group per PR head. A
20+
# workflow-level group is joined by every delivery before any job's `if:` is
21+
# evaluated, so a skipped run (a fork or push run of Squad CI, a failed request)
22+
# could cancel a real refresh, and PRs from one head branch to different bases
23+
# would share a key. So `bind` joins no group, and `readiness` joins one keyed
24+
# by the bound PR number and head SHA. It is skipped when nothing was bound.
25+
# `bind` checks the head outside any group, so a delivery can bind head A and
26+
# start `readiness` after head B's refresh started. Keyed by head, it cannot
27+
# cancel or replace B's refresh, and scripts/pr-readiness.mjs writes nothing
28+
# once the PR head is no longer A.
1829
on:
1930
workflow_run:
2031
workflows: ["Squad CI", "Squad PR Readiness Request"]
@@ -27,12 +38,12 @@ permissions:
2738
statuses: read
2839
checks: read
2940

30-
concurrency:
31-
group: ${{ github.workflow }}-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }}
32-
cancel-in-progress: true
33-
3441
jobs:
35-
readiness:
42+
bind:
43+
# workflow_run check runs land on the default-branch tip, the head commit of
44+
# any PR from dev (dev to main). scripts/pr-readiness.mjs lists this name and
45+
# `readiness` in SELF_CHECK_NAMES, so that PR's "CI passing" ignores them.
46+
name: readiness-bind
3647
runs-on: ubuntu-latest
3748
timeout-minutes: 5
3849
# Skip Dependabot, push runs of Squad CI, Squad CI runs with no
@@ -44,13 +55,19 @@ jobs:
4455
&& github.event.workflow_run.pull_requests[0] != null)
4556
|| (github.event.workflow_run.path == '.github/workflows/squad-pr-readiness-request.yml'
4657
&& github.event.workflow_run.conclusion == 'success'))
58+
outputs:
59+
bound: ${{ steps.bind.outputs.bound }}
60+
pr_number: ${{ steps.bind.outputs.pr_number }}
61+
head_sha: ${{ steps.bind.outputs.head_sha }}
62+
base_ref: ${{ steps.bind.outputs.base_ref }}
63+
draft: ${{ steps.bind.outputs.draft }}
64+
labels: ${{ steps.bind.outputs.labels }}
4765
steps:
48-
- name: Checkout scripts (default branch only)
66+
- name: Checkout binding script (default branch only)
4967
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7
5068
with:
5169
persist-credentials: false
5270
sparse-checkout: |
53-
scripts/pr-readiness.mjs
5471
scripts/workflow-run-pr-binding.mjs
5572
sparse-checkout-cone-mode: false
5673
- name: Download PR claim (untrusted data)
@@ -76,15 +93,33 @@ jobs:
7693
claimDir: process.env.CLAIM_DIR,
7794
claimWorkflowPath: '.github/workflows/squad-pr-readiness-request.yml',
7895
});
96+
97+
readiness:
98+
needs: bind
99+
# Runs only for a bound PR. When bind is skipped, fails or binds nothing,
100+
# this job is skipped and never joins the group below.
101+
if: needs.bind.outputs.bound == 'true'
102+
runs-on: ubuntu-latest
103+
timeout-minutes: 5
104+
concurrency:
105+
group: squad-pr-readiness-${{ needs.bind.outputs.pr_number }}-${{ needs.bind.outputs.head_sha }}
106+
cancel-in-progress: true
107+
steps:
108+
- name: Checkout readiness script (default branch only)
109+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7
110+
with:
111+
persist-credentials: false
112+
sparse-checkout: |
113+
scripts/pr-readiness.mjs
114+
sparse-checkout-cone-mode: false
79115
- name: Check PR readiness
80-
if: steps.bind.outputs.bound == 'true'
81116
env:
82117
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
83-
PR_NUMBER: ${{ steps.bind.outputs.pr_number }}
84-
PR_HEAD_SHA: ${{ steps.bind.outputs.head_sha }}
85-
PR_BASE_REF: ${{ steps.bind.outputs.base_ref }}
86-
PR_DRAFT: ${{ steps.bind.outputs.draft }}
87-
PR_LABELS: ${{ steps.bind.outputs.labels }}
118+
PR_NUMBER: ${{ needs.bind.outputs.pr_number }}
119+
PR_HEAD_SHA: ${{ needs.bind.outputs.head_sha }}
120+
PR_BASE_REF: ${{ needs.bind.outputs.base_ref }}
121+
PR_DRAFT: ${{ needs.bind.outputs.draft }}
122+
PR_LABELS: ${{ needs.bind.outputs.labels }}
88123
REPO_OWNER: ${{ github.repository_owner }}
89124
REPO_NAME: ${{ github.event.repository.name }}
90125
RUN_NAME: ${{ github.workflow }}

‎scripts/pr-readiness.mjs‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,14 @@ import { fileURLToPath } from 'node:url';
1919

2020
export const COMMENT_MARKER = '<!-- squad-pr-readiness -->';
2121

22-
/** Check-run names belonging to this workflow (filtered from CI checks). */
23-
export const SELF_CHECK_NAMES = ['readiness', 'PR Readiness Check'];
22+
/**
23+
* Check-run names belonging to this workflow (filtered from CI checks).
24+
* `readiness` is the job of squad-pr-readiness-request.yml (reported on the PR
25+
* head) and the posting job of squad-pr-readiness.yml; `readiness-bind` is that
26+
* workflow's bind job. workflow_run check runs land on the default-branch tip,
27+
* which is the head commit of any PR from dev (dev to main).
28+
*/
29+
export const SELF_CHECK_NAMES = ['readiness', 'readiness-bind', 'PR Readiness Check'];
2430

2531
/** Regex for source files that require a changeset. */
2632
export const SOURCE_PATTERN = /^packages\/squad-(sdk|cli)\/src\//;
@@ -427,16 +433,35 @@ export async function paginate(fetchFn, url, headers) {
427433
// Orchestration
428434
// ---------------------------------------------------------------------------
429435

436+
/**
437+
* The bind job checks the head outside the posting job's concurrency group, so
438+
* a delivery can bind head A and reach the posting job after head B was pushed
439+
* and refreshed. Returns the line to log for such a stale snapshot, or null
440+
* while the bound head is still the PR's head.
441+
* @param {string} prNumber
442+
* @param {string|undefined} boundSha — PR_HEAD_SHA, as the bind job bound it
443+
* @param {string|undefined} liveSha — the PR's head SHA as the API returns it now
444+
* @returns {string|null}
445+
*/
446+
function staleHeadMessage(prNumber, boundSha, liveSha) {
447+
if (typeof liveSha === 'string' && liveSha !== '' && liveSha === boundSha) return null;
448+
return `Skipping stale readiness snapshot for PR #${prNumber}: bound head ${boundSha} is not the live head ${liveSha}; nothing was written.`;
449+
}
450+
430451
/**
431452
* Full PR readiness orchestrator. Reads context from env vars, calls
432453
* GitHub API, runs all checks, and upserts the readiness comment.
433454
*
455+
* It writes only while the PR's head is still PR_HEAD_SHA: the head is compared
456+
* when the PR is first read and again just before writing. A stale snapshot is
457+
* logged and skipped (action `skipped`, no checks), and the script exits 0.
458+
*
434459
* Dependencies (`env` and `fetchFn`) are injectable for testing.
435460
*
436461
* @param {object} [opts]
437462
* @param {Record<string,string>} [opts.env] — defaults to process.env
438463
* @param {typeof globalThis.fetch} [opts.fetchFn] — defaults to global fetch
439-
* @returns {Promise<{ checks: Array<{name:string,pass:boolean,detail:string}>, action: string }>}
464+
* @returns {Promise<{ checks: Array<{name:string,pass:boolean,detail:string}>, action: 'created'|'updated'|'skipped' }>}
440465
*/
441466
export async function run({ env = process.env, fetchFn = globalThis.fetch } = {}) {
442467
const token = env.GITHUB_TOKEN;
@@ -491,6 +516,16 @@ export async function run({ env = process.env, fetchFn = globalThis.fetch } = {}
491516
break;
492517
}
493518

519+
// PR_HEAD_SHA is the bind job's snapshot, and a newer head may have been
520+
// pushed and refreshed since. Stop before querying CI for a head the PR no
521+
// longer has. (If this read failed, the check before writing decides.)
522+
const isStale = (liveSha) => {
523+
const message = staleHeadMessage(prNumber, prHeadSha, liveSha);
524+
if (message) console.log(message);
525+
return message !== null;
526+
};
527+
if (prData && isStale(prData.head?.sha)) return { checks: [], action: 'skipped' };
528+
494529
// 2. Draft status — prefer API truth over env var (workflow_run can't provide it)
495530
const isDraft = prData?.draft ?? prDraft;
496531
checks.push({ name: 'Not in draft', ...checkDraftStatus(isDraft) });
@@ -610,6 +645,14 @@ export async function run({ env = process.env, fetchFn = globalThis.fetch } = {}
610645
(c) => c.body && c.body.includes(COMMENT_MARKER),
611646
);
612647

648+
// Read the head again just before writing: it may have moved while the checks ran.
649+
const liveUrl = `${apiBase}/pulls/${prNumber}`;
650+
const liveRes = await fetchFn(liveUrl, { headers: apiHeaders });
651+
if (!liveRes.ok) {
652+
throw new Error(`GitHub API ${liveRes.status}: ${liveUrl} (cannot confirm head ${prHeadSha}; nothing was written)`);
653+
}
654+
if (isStale((await liveRes.json())?.head?.sha)) return { checks: [], action: 'skipped' };
655+
613656
let action;
614657
if (existing) {
615658
await fetchFn(`${apiBase}/issues/comments/${existing.id}`, {

‎test/pr-readiness.test.ts‎

Lines changed: 107 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,7 @@ describe('run()', () => {
824824
compare: { behind_by: 0 },
825825
reviews: [{ user: { login: 'copilot-pull-request-reviewer' }, state: 'APPROVED', submitted_at: '2025-01-01T00:00:00Z' }],
826826
files: [{ filename: '.changeset/feat.md', additions: 5, deletions: 0 }],
827-
pr: { mergeable: true },
827+
pr: { head: { sha: 'abc123' }, mergeable: true },
828828
checkRuns: { check_runs: [{ name: 'build', conclusion: 'success', status: 'completed' }] },
829829
status: { statuses: [{ state: 'success' }] },
830830
comments: [],
@@ -844,6 +844,8 @@ describe('run()', () => {
844844
},
845845
};
846846
const data = { ...defaults, ...overrides };
847+
// The live PR keeps the bound head (PR_HEAD_SHA) unless a test overrides it.
848+
data.pr = { ...defaults.pr, ...data.pr };
847849

848850
return vi.fn().mockImplementation(async (url, opts) => {
849851
const headers = new Map([['link', '']]);
@@ -940,7 +942,7 @@ describe('run()', () => {
940942
if (url.includes('/check-runs?')) return ok({ check_runs: [] });
941943
if (url.includes('/status')) return ok({ statuses: [] });
942944
if (url.includes('/comments?')) return ok([]);
943-
if (url.match(/\/pulls\/\d+$/)) return ok({ mergeable: true });
945+
if (url.match(/\/pulls\/\d+$/)) return ok({ head: { sha: 'abc123' }, mergeable: true });
944946
if (url.includes('/comments')) return ok({ id: 1 });
945947
return ok({});
946948
});
@@ -1063,13 +1065,17 @@ describe('run()', () => {
10631065

10641066
it('falls back to env PR_DRAFT when PR API fetch fails', async () => {
10651067
const mockFetch = createMockFetch();
1068+
let prReads = 0;
10661069
mockFetch.mockImplementation(async (url, opts) => {
10671070
const headers = new Map([['link', '']]);
10681071
const ok = (json) => ({ ok: true, json: async () => json, headers });
10691072

10701073
if (url === 'https://api.github.com/graphql') return ok({ data: { repository: { pullRequest: { reviewThreads: { nodes: [] } } } } });
1071-
// PR endpoint fails
1072-
if (url.match(/\/pulls\/\d+$/)) return { ok: false, status: 500, headers };
1074+
// The first PR read fails; the read before writing succeeds.
1075+
if (url.match(/\/pulls\/\d+$/)) {
1076+
prReads += 1;
1077+
return prReads === 1 ? { ok: false, status: 500, headers } : ok({ head: { sha: 'abc123' } });
1078+
}
10731079
if (url.includes('/commits?')) return ok([{ sha: '1' }]);
10741080
if (url.includes('/compare/')) return ok({ behind_by: 0 });
10751081
if (url.includes('/reviews?')) return ok([]);
@@ -1108,4 +1114,101 @@ describe('run()', () => {
11081114
expect(body).toContain('| `test/index.test.ts` | +50 −0 |');
11091115
expect(body).toContain('**Total: +75 −10**');
11101116
});
1117+
1118+
// -------------------------------------------------------------------------
1119+
// Out-of-order completion: bind checks the head outside the posting job's
1120+
// concurrency group, so a run bound to head A can post after head B was
1121+
// pushed and refreshed. It must not replace B's checklist with A's.
1122+
// -------------------------------------------------------------------------
1123+
1124+
describe('writes only while the PR head is still the bound head', () => {
1125+
const BOUND = 'a'.repeat(40);
1126+
const LIVE = 'b'.repeat(40);
1127+
const env = { ...baseEnv, PR_HEAD_SHA: BOUND };
1128+
1129+
/** Each read of the PR returns the next head (null: the read fails); the last one repeats. */
1130+
function prReads(...heads) {
1131+
const mockFetch = createMockFetch({ comments: [{ id: 123, body: `${COMMENT_MARKER}\nB's checklist` }] });
1132+
const respond = mockFetch.getMockImplementation();
1133+
let reads = 0;
1134+
mockFetch.mockImplementation(async (url, opts) => {
1135+
if (!/\/pulls\/\d+$/.test(url)) return respond(url, opts);
1136+
const sha = heads[Math.min(reads++, heads.length - 1)];
1137+
const headers = new Map([['link', '']]);
1138+
if (sha === null) return { ok: false, status: 500, headers };
1139+
return { ok: true, json: async () => ({ head: { sha }, mergeable: true }), headers };
1140+
});
1141+
return mockFetch;
1142+
}
1143+
1144+
const writesOf = (mockFetch) => mockFetch.mock.calls
1145+
.filter(([url, opts]) => url.includes('/comments') && ['POST', 'PATCH'].includes(opts?.method))
1146+
.map(([url, opts]) => `${opts.method} ${url}`);
1147+
const ciQueriesFor = (mockFetch, sha) => mockFetch.mock.calls
1148+
.map(([url]) => url)
1149+
.filter((url) => url.includes(`/commits/${sha}/`));
1150+
1151+
async function runLogged(mockFetch) {
1152+
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
1153+
try {
1154+
const outcome = await run({ env, fetchFn: mockFetch }).then(
1155+
(result) => ({ result, error: null }),
1156+
(error) => ({ result: null, error }),
1157+
);
1158+
return { ...outcome, lines: log.mock.calls.map((args) => args.join(' ')) };
1159+
} finally {
1160+
log.mockRestore();
1161+
}
1162+
}
1163+
const naming = (lines, ...shas) => lines.filter((line) => shas.every((sha) => line.includes(sha)));
1164+
1165+
it('skips a late run bound to a head the PR no longer has, before querying CI', async () => {
1166+
const mockFetch = prReads(LIVE);
1167+
const { result, error, lines } = await runLogged(mockFetch);
1168+
1169+
expect(writesOf(mockFetch), `the run bound to ${BOUND} wrote while PR #42 is at ${LIVE}`).toEqual([]);
1170+
expect(error, `the run bound to ${BOUND} must exit cleanly while PR #42 is at ${LIVE}`).toBeNull();
1171+
expect(result, `the run bound to ${BOUND} while PR #42 is at ${LIVE}`).toEqual({ checks: [], action: 'skipped' });
1172+
expect(ciQueriesFor(mockFetch, BOUND), `the run bound to ${BOUND} queried CI after reading head ${LIVE}`)
1173+
.toEqual([]);
1174+
expect(naming(lines, BOUND, LIVE), `one log line must name ${BOUND} and ${LIVE}; logged ${JSON.stringify(lines)}`)
1175+
.toHaveLength(1);
1176+
});
1177+
1178+
it('skips when the head moves while the checks run, by reading it again before writing', async () => {
1179+
const mockFetch = prReads(BOUND, LIVE);
1180+
const { result, error, lines } = await runLogged(mockFetch);
1181+
1182+
expect(writesOf(mockFetch), `PR #42 moved from ${BOUND} to ${LIVE} before the write, but the run wrote`)
1183+
.toEqual([]);
1184+
expect(error, `the run bound to ${BOUND} must exit cleanly once PR #42 is at ${LIVE}`).toBeNull();
1185+
expect(result, `the run bound to ${BOUND} once PR #42 is at ${LIVE}`).toEqual({ checks: [], action: 'skipped' });
1186+
expect(naming(lines, BOUND, LIVE), `one log line must name ${BOUND} and ${LIVE}; logged ${JSON.stringify(lines)}`)
1187+
.toHaveLength(1);
1188+
});
1189+
1190+
it('writes nothing, and fails, when the head cannot be read before writing', async () => {
1191+
const mockFetch = prReads(BOUND, null);
1192+
const { error } = await runLogged(mockFetch);
1193+
1194+
expect(writesOf(mockFetch), `the run bound to ${BOUND} wrote although PR #42 could not be read before writing`)
1195+
.toEqual([]);
1196+
expect(String(error), `the run bound to ${BOUND} must fail when PR #42 cannot be read before writing`)
1197+
.toContain(`cannot confirm head ${BOUND}`);
1198+
});
1199+
1200+
it('still writes when the live head is the bound head', async () => {
1201+
const mockFetch = prReads(BOUND);
1202+
const { result, error, lines } = await runLogged(mockFetch);
1203+
1204+
expect(error, `the run bound to ${BOUND} failed while PR #42 is still at ${BOUND}`).toBeNull();
1205+
expect(writesOf(mockFetch), `PR #42 is still at bound head ${BOUND}, so the run must update its comment`)
1206+
.toEqual(['PATCH https://api.github.com/repos/testorg/testrepo/issues/comments/123']);
1207+
expect(result?.action, `the run bound to ${BOUND} while PR #42 is still at ${BOUND}`).toBe('updated');
1208+
expect(result?.checks).toHaveLength(9);
1209+
expect(ciQueriesFor(mockFetch, BOUND), `CI must be read for bound head ${BOUND}`).toHaveLength(2);
1210+
expect(naming(lines, BOUND), `nothing is skipped while PR #42 is at ${BOUND}; logged ${JSON.stringify(lines)}`)
1211+
.toEqual([]);
1212+
});
1213+
});
11111214
});

0 commit comments

Comments
 (0)