Skip to content

Commit dcc2b0c

Browse files
mchwangclaude
andcommitted
Draft the earlier PR before recording a matching check, so a failure stays retryable
Also refuse a PR-number mismatch before any GitHub change, and remove each head-poll abort listener when its wait ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 07c6630 commit dcc2b0c

4 files changed

Lines changed: 47 additions & 17 deletions

File tree

‎docs/implementation/pull-request-opening.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ Each opening or refresh owns the task state version at the moment it passed step
6969

7070
After an update, the read-back polls up to 5 times, half a second apart, until GitHub shows the pushed head, because GitHub updates a PR's head a moment after a push.
7171

72-
When the check matches (or is unknown) and the task's earlier PR is open and ready for review, publish turns it back into a draft. A task that is not being published as ready never leaves its PR ready for review.
72+
When the check matches (or is unknown) and the task's earlier PR is open and ready for review, publish turns it back into a draft. A task that is not being published as ready never leaves its PR ready for review. This happens before the check result is recorded: if it fails, the task is still running, and a retry checks again and repeats it. A PR-number mismatch is refused before any GitHub change.
7373

7474
The adapter refuses any answer for a PR that is not open. A PR closed between the lookup and the update is never recorded as the task's review PR.
7575

‎github/pull-requests.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,9 +121,11 @@ export class GhPullRequestGateway implements PullRequestGateway {
121121
const { body, ...pr } = this.#pull(await this.#json(['api', '-H', 'Accept: application/vnd.github+json', `repos/${this.repository}/pulls/${number}`], signal), input);
122122
if (pr.number !== number || !body.includes(input.marker)) throw new Error('GitHub returned a different pull request.');
123123
if (headSha === undefined || pr.headSha === headSha || poll >= HEAD_POLLS) return pr;
124-
await new Promise((resolve, reject) => {
125-
const timer = setTimeout(resolve, HEAD_POLL_MS);
126-
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
124+
await new Promise<void>((resolve, reject) => {
125+
signal?.throwIfAborted();
126+
const onAbort = () => { clearTimeout(timer); reject(signal!.reason); };
127+
const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, HEAD_POLL_MS);
128+
signal?.addEventListener('abort', onAbort, { once: true });
127129
});
128130
}
129131
}

‎runner/publish.ts‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -95,18 +95,17 @@ export class PullRequestPublisher {
9595
ownCommits: new Set(this.#store.getLedger(identity).filter(entry => entry.origin === 'owned').map(entry => entry.sha)),
9696
}, signal);
9797
signal?.throwIfAborted();
98-
const check = this.#store.recordAlreadyFixed(identity, task.stateVersion, { snapshotId: snapshot.id, draft, result });
99-
if (result.outcome !== 'clear') {
100-
// A task that is not published as ready never leaves its PR ready for review: its earlier ready PR becomes a draft.
101-
// No await since recordAlreadyFixed, which re-read the task; the change only lowers what the PR offers.
102-
if (earlier && live && !live.draft) {
103-
const pr = await this.#pulls.markDraft(live.number, { base: this.#config.baseBranch, headBranch: branch, marker: marker(earlier.openingId) }, signal);
104-
if (earlier.state === 'opened') this.#store.recordPullRequestDraft(identity, earlier.openingId, pr.number, pr.draft);
105-
}
106-
return draft ? { kind: 'draft skipped', result } : { kind: 'possibly already fixed', result };
107-
}
108-
// Checked before the push: a refused publish must not move the branch.
98+
// Checked before any GitHub change: a refused publish must neither draft the PR nor move the branch.
10999
if (earlier && live && earlier.state === 'opened' && live.number !== earlier.number) throw new GuardRefusal('GitHub returned a different pull request for this branch.');
100+
// A task that is not published as ready never leaves its PR ready for review: on a match its earlier ready PR becomes
101+
// a draft. This comes before the result is recorded, so if it fails the task is still running and a retry repeats it.
102+
// Making a PR a draft only lowers what it offers, so it needs no re-read of the task first.
103+
const drafted = result.outcome !== 'clear' && earlier && live && !live.draft
104+
? await this.#pulls.markDraft(live.number, { base: this.#config.baseBranch, headBranch: branch, marker: marker(earlier.openingId) }, signal) : null;
105+
signal?.throwIfAborted();
106+
const check = this.#store.recordAlreadyFixed(identity, task.stateVersion, { snapshotId: snapshot.id, draft, result });
107+
if (drafted && earlier!.state === 'opened') this.#store.recordPullRequestDraft(identity, earlier!.openingId, drafted.number, drafted.draft);
108+
if (result.outcome !== 'clear') return draft ? { kind: 'draft skipped', result } : { kind: 'possibly already fixed', result };
110109
// No await since recordAlreadyFixed, whose transaction re-read the task: the push follows it directly.
111110
await this.#pusher.push(identity, { head: snapshot.head, branch }, signal);
112111
signal?.throwIfAborted();

‎test/publish.test.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ function runningTask(options: { head?: string } = {}) {
3434
/** `live` is GitHub's set of open PRs by marker; share it between harnesses to model later runs of the same task. */
3535
function harness(store: Store, options: { results?: AlreadyFixedResult[]; open?: (input: OpenPullRequestInput) => Promise<OpenedPullRequest>; found?: OpenedPullRequest | null;
3636
push?: BranchPusher['push']; live?: Map<string, OpenedPullRequest>; next?: { value: number }; config?: Partial<PublishConfig>; draftAfterRefresh?: boolean;
37-
onFind?: () => void; refreshFails?: boolean; closed?: Set<number>; hidden?: Set<string>; openTimesOut?: boolean } = {}) {
37+
onFind?: () => void; refreshFails?: boolean; closed?: Set<number>; hidden?: Set<string>; openTimesOut?: boolean; draftFails?: boolean } = {}) {
3838
const live = options.live ?? new Map<string, OpenedPullRequest>(), counter = options.next ?? { value: 100 }, closed = options.closed ?? new Set<number>();
3939
const log: string[] = [], checks: AlreadyFixedInput[] = [], opened: OpenPullRequestInput[] = [];
4040
const results = options.results ? [...options.results] : [];
@@ -68,6 +68,7 @@ function harness(store: Store, options: { results?: AlreadyFixedResult[]; open?:
6868
},
6969
async markDraft(number, input) {
7070
log.push(`draft ${number}`);
71+
if (options.draftFails) throw new Error('timeout marking the PR a draft');
7172
const pr = { ...live.get(input.marker)!, draft: true }; live.set(input.marker, pr); return pr;
7273
},
7374
async refresh(number, input) {
@@ -355,6 +356,27 @@ describe('recovering a lost opening', () => {
355356
expect(store.taskPullRequests(identity)).toMatchObject([{ number: 100, draft: true }]);
356357
expect(store.getTask(identity).status).toBe('possibly already fixed');
357358
});
359+
it('keeps the task running when marking the earlier PR a draft fails, so a retry repeats it', async () => {
360+
const store = runningTask(), live = new Map<string, OpenedPullRequest>(), next = { value: 100 };
361+
await harness(store, { live, next }).publisher.publish(identity);
362+
rerun(store);
363+
const found: AlreadyFixedResult = { outcome: 'found', baseHead: oid(9), matches: [{ kind: 'closed', by: 'owner/repo#5' }] };
364+
await expect(harness(store, { live, next, results: [found], draftFails: true }).publisher.publish(identity)).rejects.toThrow('timeout');
365+
expect(store.getTask(identity).status).toBe('running');
366+
const retry = harness(store, { live, next, results: [found] });
367+
expect(await retry.publisher.publish(identity)).toMatchObject({ kind: 'possibly already fixed' });
368+
expect(retry.log).toContain('draft 100');
369+
expect(store.taskPullRequests(identity)).toMatchObject([{ number: 100, draft: true }]);
370+
});
371+
it('refuses a PR-number mismatch before drafting anything', async () => {
372+
const store = runningTask(), live = new Map<string, OpenedPullRequest>(), next = { value: 100 };
373+
await harness(store, { live, next }).publisher.publish(identity);
374+
for (const [m, pr] of live) live.set(m, { ...pr, number: 999 });
375+
rerun(store);
376+
const again = harness(store, { live, next, results: [{ outcome: 'found', baseHead: oid(9), matches: [{ kind: 'closed', by: 'owner/repo#5' }] }] });
377+
await expect(again.publisher.publish(identity)).rejects.toThrow(/different pull request/);
378+
expect(again.log.some(line => line.startsWith('draft'))).toBe(false);
379+
});
358380
it('opens a new PR when the earlier draft was closed, and still excludes the old draft from the check', async () => {
359381
const store = runningTask(), live = new Map<string, OpenedPullRequest>(), next = { value: 100 };
360382
store.transitionTask(identity, store.getTask(identity).stateVersion, 'needs human');
@@ -555,8 +577,15 @@ describe('GitHub PR adapter', () => {
555577
if (args.includes('GET') || !args.includes('-X')) { gets++; return JSON.stringify(response({ draft: false, head: { sha: gets < 3 ? oid(2) : oid(3), ref: 'codeboost/issue-12-task', repo: { full_name: 'owner/repo' } } })); }
556578
return JSON.stringify(response({ draft: false }));
557579
});
558-
expect(await gh.refresh(7, { ...input, draft: false, ready: true, headSha: oid(3) })).toMatchObject({ headSha: oid(3) });
580+
const controller = new AbortController();
581+
let listeners = 0;
582+
const add = controller.signal.addEventListener.bind(controller.signal), remove = controller.signal.removeEventListener.bind(controller.signal);
583+
controller.signal.addEventListener = ((...a: Parameters<typeof add>) => { if (a[0] === 'abort') listeners++; return add(...a); }) as typeof add;
584+
controller.signal.removeEventListener = ((...a: Parameters<typeof remove>) => { if (a[0] === 'abort') listeners--; return remove(...a); }) as typeof remove;
585+
expect(await gh.refresh(7, { ...input, draft: false, ready: true, headSha: oid(3) }, controller.signal)).toMatchObject({ headSha: oid(3) });
559586
expect(gets).toBe(3);
587+
// Each wait removes its abort listener, so a long-lived signal does not collect them.
588+
expect(listeners).toBe(0);
560589
});
561590
it('marks an open ready PR as a draft, and leaves a draft alone', async () => {
562591
const calls: string[][] = [];

0 commit comments

Comments
 (0)