Skip to content

Commit 7779c05

Browse files
authored
Merge pull request #1445 from Wibias/ci/resolve-pr-fallback
fix(ci): reconcile PR from head SHA when the commit-PR index lags
2 parents da8ebd3 + 7f4de36 commit 7779c05

3 files changed

Lines changed: 202 additions & 9 deletions

File tree

‎.github/workflows/enforce-pr-target.yml‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,15 +73,56 @@ jobs:
7373
}
7474
7575
const statusSha = context.payload.sha;
76-
const associatedPrs = await github.paginate(
77-
github.rest.repos.listPullRequestsAssociatedWithCommit,
78-
{ owner, repo, commit_sha: statusSha, per_page: 100 }
79-
);
80-
const candidates = associatedPrs.filter(
81-
candidate =>
82-
candidate.state === "open" &&
83-
candidate.head?.sha === statusSha
84-
);
76+
// Primary authority: GitHub's commit-to-PR index. This read can
77+
// lag a fresh head push, so a non-match is not proof of absence.
78+
let candidates = [];
79+
try {
80+
const associatedPrs = await github.paginate(
81+
github.rest.repos.listPullRequestsAssociatedWithCommit,
82+
{ owner, repo, commit_sha: statusSha, per_page: 100 }
83+
);
84+
candidates = associatedPrs.filter(
85+
candidate =>
86+
candidate.state === "open" &&
87+
candidate.head?.sha === statusSha
88+
);
89+
} catch (error) {
90+
core.warning(
91+
`Could not list PRs associated with commit ${statusSha}: ${error.message}`
92+
);
93+
}
94+
95+
if (candidates.length !== 1) {
96+
// Fallback: reconcile directly against the live head SHA. The
97+
// association index can be stale or empty for a very recent
98+
// head (seen on PR #1441), so an empty/ambiguous index result
99+
// must not silently drop the revalidation. Matching on the
100+
// head SHA is the same authoritative identity the write gate
101+
// uses, and `pulls.list` is a read — compatible with this
102+
// job's `pull-requests: read` permission.
103+
const priorCount = candidates.length;
104+
try {
105+
const openPrs = await github.paginate(github.rest.pulls.list, {
106+
owner,
107+
repo,
108+
state: "open",
109+
per_page: 100
110+
});
111+
candidates = openPrs.filter(
112+
pr =>
113+
pr.state === "open" &&
114+
pr.head?.sha === statusSha
115+
);
116+
core.info(
117+
`Associated-index fallback: ${priorCount} index match(es), ${candidates.length} open PR(s) match head ${statusSha}.`
118+
);
119+
} catch (error) {
120+
core.warning(
121+
`Could not list open PRs for head-${statusSha} fallback: ${error.message}`
122+
);
123+
}
124+
}
125+
85126
if (candidates.length !== 1) {
86127
core.info(
87128
`CodeRabbit status ${statusSha} maps to ${candidates.length} open current-head PRs; skipping ambiguous/stale revalidation.`

‎tests/ci-workflows.test.ts‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1256,6 +1256,29 @@ describe("GitHub Actions hardening", () => {
12561256
return runEnforcePrTarget(script, options);
12571257
}
12581258

1259+
/**
1260+
* Run the read-only `resolve-pr` job's SHA-to-PR resolver in the same
1261+
* harness scope the write gate gets. The resolver is a separate inline
1262+
* script from `enforce-target`; compiling it on its own lets a test pin
1263+
* what `pull-number` it publishes for a given associated-PR / open-PR
1264+
* state. This is the exact surface where the stale-commit-index bug
1265+
* (PR #1441) lived, so the head-SHA fallback is asserted here.
1266+
*/
1267+
async function runResolver(options: Parameters<typeof runEnforcePrTarget>[1]) {
1268+
const text = await readText(".github/workflows/enforce-pr-target.yml");
1269+
const workflow = Bun.YAML.parse(text) as {
1270+
jobs?: Record<string, { steps?: Array<{ name?: string; with?: { script?: string } }> }>;
1271+
};
1272+
const step = workflow.jobs?.["resolve-pr"]?.steps?.find(
1273+
s => s.name === "Resolve trusted gate event to PR",
1274+
);
1275+
const resolverScript = step?.with?.script;
1276+
if (typeof resolverScript !== "string") {
1277+
throw new Error("resolve-pr step has no inline script");
1278+
}
1279+
return runEnforcePrTarget(stripComments(resolverScript), options);
1280+
}
1281+
12591282
/**
12601283
* Run an arbitrary body in the same scope the workflow script gets, and
12611284
* hand back what it returned.
@@ -2890,6 +2913,127 @@ describe("GitHub Actions hardening", () => {
28902913
expect(methodsOf(result)).toContain("issues.listComments");
28912914
});
28922915

2916+
test("the resolver falls back to the head SHA when the commit-PR index is empty", async () => {
2917+
const headSha = "6c42d17f213a632fc2def56053f0cd574b13d459";
2918+
const result = await runResolver({
2919+
pr: { base: { ref: "dev" }, number: 4242, head: { sha: headSha } },
2920+
eventName: "status",
2921+
statusSha: headSha,
2922+
// GitHub's commit-to-PR index can lag a fresh push (seen on #1441):
2923+
// the association endpoint returns no PR for a genuine current head.
2924+
associatedPullRequests: [],
2925+
openPulls: [
2926+
{ number: 4242, state: "open", head: { sha: headSha } },
2927+
{ number: 9999, state: "open", head: { sha: "other" } },
2928+
{ number: 100, state: "closed", head: { sha: headSha } },
2929+
],
2930+
});
2931+
2932+
expect(result.outputs).toEqual([{ name: "pull-number", value: "4242" }]);
2933+
// The fallback must consult the live open-PR list exactly once.
2934+
expect(callsTo(result, "repos.listPullRequestsAssociatedWithCommit")).toHaveLength(1);
2935+
expect(callsTo(result, "pulls.list")).toHaveLength(1);
2936+
expect(result.logs.join(" ")).toContain("Associated-index fallback");
2937+
// A closed PR with the same head must not count as a candidate.
2938+
expect(result.logs.join(" ")).toContain("1 open PR(s) match head");
2939+
});
2940+
2941+
test("the resolver skips when the fallback finds no unique open head match", async () => {
2942+
const headSha = "6c42d17f213a632fc2def56053f0cd574b13d459";
2943+
const result = await runResolver({
2944+
pr: { base: { ref: "dev" }, number: 4242, head: { sha: headSha } },
2945+
eventName: "status",
2946+
statusSha: headSha,
2947+
associatedPullRequests: [],
2948+
// No open PR carries this head; the stale index is not a match.
2949+
openPulls: [
2950+
{ number: 9999, state: "open", head: { sha: "other" } },
2951+
],
2952+
});
2953+
2954+
expect(result.outputs).toEqual([]);
2955+
// The fallback must actually have run: the resolver consults the live
2956+
// open-PR list exactly once. Without this assertion the test would still
2957+
// pass if the fallback were removed (the empty association index by
2958+
// itself already skips), silently losing coverage of the head-SHA
2959+
// reconciliation path.
2960+
expect(callsTo(result, "pulls.list")).toHaveLength(1);
2961+
expect(callsTo(result, "pulls.list")[0]).toMatchObject({
2962+
owner: "lidge-jun",
2963+
repo: "opencodex",
2964+
state: "open",
2965+
});
2966+
expect(result.logs.join(" ")).toContain("skipping ambiguous/stale revalidation");
2967+
});
2968+
2969+
test("the resolver fails closed when two open PRs share the head SHA", async () => {
2970+
const headSha = "6c42d17f213a632fc2def56053f0cd574b13d459";
2971+
const result = await runResolver({
2972+
pr: { base: { ref: "dev" }, number: 4242, head: { sha: headSha } },
2973+
eventName: "status",
2974+
statusSha: headSha,
2975+
associatedPullRequests: [],
2976+
// Two open PRs on the same head: the live lookup is ambiguous, so the
2977+
// resolver must fail closed rather than guess which PR to revalidate.
2978+
openPulls: [
2979+
{ number: 4242, state: "open", head: { sha: headSha } },
2980+
{ number: 7777, state: "open", head: { sha: headSha } },
2981+
],
2982+
});
2983+
2984+
expect(result.outputs).toEqual([]);
2985+
// The live fallback must actually have run before the ambiguity is
2986+
// detected: the resolver consults the open-PR list exactly once and
2987+
// weighs both same-head candidates before failing closed. Without this
2988+
// assertion the test would still pass if the fallback were removed (the
2989+
// empty association index by itself already skips), silently losing
2990+
// coverage of the head-SHA reconciliation path.
2991+
expect(callsTo(result, "pulls.list")).toHaveLength(1);
2992+
expect(callsTo(result, "pulls.list")[0]).toMatchObject({
2993+
owner: "lidge-jun",
2994+
repo: "opencodex",
2995+
state: "open",
2996+
});
2997+
expect(result.logs.join(" ")).toContain("skipping ambiguous/stale revalidation");
2998+
});
2999+
3000+
test("the resolver resolves via the association index when it is already fresh", async () => {
3001+
const headSha = "3f1c0de0a6a4d0a3f9a1b2c3d4e5f60718293a4b";
3002+
const result = await runResolver({
3003+
pr: { base: { ref: "dev" }, number: 42, head: { sha: headSha } },
3004+
eventName: "status",
3005+
statusSha: headSha,
3006+
associatedPullRequests: [
3007+
{ number: 42, state: "open", head: { sha: headSha } },
3008+
],
3009+
});
3010+
3011+
expect(result.outputs).toEqual([{ name: "pull-number", value: "42" }]);
3012+
// A unique index hit must not need the open-PR fallback.
3013+
expect(callsTo(result, "pulls.list")).toEqual([]);
3014+
});
3015+
3016+
test("the resolver fails closed when both resolution paths error", async () => {
3017+
const headSha = "6c42d17f213a632fc2def56053f0cd574b13d459";
3018+
const result = await runResolver({
3019+
pr: { base: { ref: "dev" }, number: 4242, head: { sha: headSha } },
3020+
eventName: "status",
3021+
statusSha: headSha,
3022+
associatedPullRequests: [],
3023+
failOn: [
3024+
"repos.listPullRequestsAssociatedWithCommit",
3025+
"pulls.list",
3026+
],
3027+
});
3028+
3029+
expect(result.outputs).toEqual([]);
3030+
expect(result.logs.join(" ")).toContain("skipping ambiguous/stale revalidation");
3031+
expect(result.warnings.join(" ")).toContain(
3032+
"Could not list PRs associated with commit",
3033+
);
3034+
expect(result.warnings.join(" ")).toContain("Could not list open PRs");
3035+
});
3036+
28933037
test("a non-maintainer issue_comment does not re-run the gate", async () => {
28943038
// The `issue_comment` trigger must only re-run for maintainer comments
28953039
// (OWNER / COLLABORATOR / MEMBER). A random comment from a contributor

‎tests/helpers/enforce-pr-target-harness.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ export type RecordedCall = { method: string; args: unknown };
2222

2323
export type HarnessResult = {
2424
calls: RecordedCall[];
25+
/**
26+
* Values the script wrote through `core.setOutput`, in write order. The
27+
* write-capable gate consumes `RESOLVED_PULL_NUMBER` from the resolver, and
28+
* the client sets it as a step output; exposing it lets a test assert the
29+
* SHA-to-PR resolution directly instead of inferring it from later calls.
30+
*/
31+
outputs: Array<{ name: string; value: unknown }>;
2532
/**
2633
* Paths the script read through its `node:fs` stub. Kept separate from
2734
* `calls` so exact method-sequence assertions stay stable while the fs
@@ -1197,6 +1204,7 @@ export async function runEnforcePrTarget(
11971204

11981205
return {
11991206
calls,
1207+
outputs,
12001208
fsReads,
12011209
logs,
12021210
warnings,

0 commit comments

Comments
 (0)