Skip to content

Commit f094853

Browse files
mchwangclaude
andcommitted
Address Copilot round 8 on F2d: duplicate commits, stale recovery, verified draft opening
- The base comparison fails closed when a commit appears twice, since another commit must then be missing. - A recovered opening ends the publish only when it is this publish's own work (same task version and draft mode); otherwise the PR is recorded and publishing continues with the current head and mode. Draft reconciliation in recovery runs only for draft publishes. - A draft opening that GitHub creates as ready fails, so the opening stays owned and recovery turns the PR into a draft. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 46bbeba commit f094853

6 files changed

Lines changed: 41 additions & 8 deletions

File tree

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ A commit mentions the issue with `#12`, `GH-12`, `owner/repo#12`, or the issue U
3838
**The check fails closed.** It returns `unknown` in each of these cases, and `unknown` is handled like a match:
3939

4040
- more than 100 timeline events, or more than 250 new base commits;
41-
- a task base that is not an ancestor of the base branch;
41+
- a task base that is not an ancestor of the base branch, or a comparison that lists a commit twice;
4242
- a closed issue with no close event;
4343
- a linked item that is missing, of an unknown type, or in a malformed response;
4444
- a GitHub error or invalid JSON;
@@ -50,13 +50,13 @@ A cancelled check throws. It does not return `unknown`.
5050

5151
Only one publish runs per task at a time; a second one is refused. A publish whose signal is already aborted changes nothing. Publish runs these steps in order:
5252

53-
1. **Recover.** If an opening is still `opening`, look for the open PR from the task branch, with the markers of all the task's openings for that branch. If it has this opening's marker, record it as opened; if this was a draft opening and the PR has since been made ready, turn it back into a draft first (a failure keeps the opening owned). If it has another opening's marker, this opening created nothing (one open PR per branch): mark it `abandoned` and continue. If none exists, the request may still be in flight or not yet visible. So publish stops with `OpeningUnsettled` until the opening is 10 minutes old (`settleMs`). After that, it marks the opening `abandoned` and continues.
53+
1. **Recover.** If an opening is still `opening`, look for the open PR from the task branch, with the markers of all the task's openings for that branch. If it has this opening's marker, record it as opened; if this was a draft opening, this publish is a draft publish too, and the PR has since been made ready, turn it back into a draft first (a failure keeps the opening owned). The recovered opening ends this publish only when it is this publish's own work: same task state version and same draft mode. Otherwise the PR is recorded and publishing continues, so the main path pushes the current head and brings the PR into the current mode. If it has another opening's marker, this opening created nothing (one open PR per branch): mark it `abandoned` and continue. If none exists, the request may still be in flight or not yet visible. So publish stops with `OpeningUnsettled` until the opening is 10 minutes old (`settleMs`). After that, it marks the opening `abandoned` and continues.
5454
2. **Status and no changes.** Refuse unless the task is running (or in needs human, for a draft). If the task head is its base, open nothing. A running task moves to needs human.
5555
3. **Find the branch PR.** Ask GitHub for the branch's open PR every time, with the markers of the task's opened and abandoned openings for that branch (none if the task has no PR yet). An open PR that carries none of them was not opened by codeboost: publish refuses before anything is pushed. A PR with an opened record's marker but another number is refused too. When the PR's draft state on GitHub differs from the record, the record is corrected here (for example after a draft change whose record was lost), under the task's state-version guard. This comes before the check: an abandoned opening's PR links the issue and has no recorded number, so only its marker shows it is the task's own, and its number is added to the own PRs for the check.
5656
4. **Check.** Run the check. Record the result, and any status change, in one transaction. That transaction refuses if the task changed during the check.
5757
5. **Push.** When the task already has an open PR, the refresh is recorded first (the push moves that PR's head), then the push runs; otherwise the push runs straight after the check's transaction with no await in between. Push the task head to `codeboost/issue-<issue>-<task slug>-<hash>`. The slug is readable but can collide. The hash is 16 hex characters of SHA-256 over the exact task identity, so two tasks never share a branch.
5858
6. **Re-read.** Right before the GitHub call, the Store confirms that the latest check is clear and that nothing changed since that check: same task state version, same review version (approvals, choices and notes), same snapshot, same head.
59-
7. **Open or reuse.** Open a new PR, or update the open earlier PR (found in step 3 with the markers of every earlier opening, abandoned ones included; an abandoned opening's PR is adopted in the same transaction that records the update) and mark it ready (or a draft). An update is recorded before it starts. If its confirmation is lost, the next publish drops the record in step 1 and repeats the update after a new check; the update is idempotent. Record the result.
59+
7. **Open or reuse.** Open a new PR (a draft opening that GitHub creates as ready fails, keeping the opening owned; recovery then turns it into a draft), or update the open earlier PR (found in step 3 with the markers of every earlier opening, abandoned ones included; an abandoned opening's PR is adopted in the same transaction that records the update) and mark it ready (or a draft). An update is recorded before it starts. If its confirmation is lost, the next publish drops the record in step 1 and repeats the update after a new check; the update is idempotent. Record the result.
6060

6161
Each opening or refresh owns the task state version at the moment it passed step 6. The PR is always recorded. The status changes only when the task still has that version. Every status change, admission and context change increases the version. So a response that arrives after the task changed never moves it.
6262

‎github/already-fixed.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,8 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
220220
const entry = object(raw, 'commit');
221221
const message = object(entry.commit, 'commit').message;
222222
if (typeof entry.sha !== 'string' || !SHA.test(entry.sha) || typeof message !== 'string') throw new Unknown('GitHub returned an invalid commit.');
223+
// Each commit once: a repeated SHA means another commit is missing, so the list cannot be trusted as complete.
224+
if (commits.some(commit => commit.sha === entry.sha)) throw new Unknown('GitHub returned a commit twice in the comparison.');
223225
commits.push({ sha: entry.sha, message });
224226
}
225227
if (total === 0) break;

‎github/pull-requests.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ export class GhPullRequestGateway implements PullRequestGateway {
9898
const response = input.draft ? await draftCall(post) : await post();
9999
const { body, ...pr } = this.#pull(response, input);
100100
if (markerOf(body) !== input.marker) throw new Error('GitHub returned a pull request without its marker.');
101+
// The PR exists, but not in the requested state: failing keeps the opening owned, and recovery turns it into a draft.
102+
if (input.draft && !pr.draft) throw new Error('GitHub opened the pull request as ready, not as a draft.');
101103
return pr;
102104
}
103105

‎runner/publish.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export class PullRequestPublisher {
7777

7878
async #publish(identity: PlanIdentity, input: { problems?: readonly string[] }, signal?: AbortSignal): Promise<PublishOutcome> {
7979
const draft = input.problems !== undefined;
80-
const recovered = await this.#recover(identity, signal);
80+
const recovered = await this.#recover(identity, draft, signal);
8181
if (recovered) return recovered;
8282
const task = this.#store.getTask(identity), snapshot = this.#store.getSnapshot(identity), plan = this.#store.getPlan(identity);
8383
const reviewVersion = this.#store.reviewVersion(identity);
@@ -172,6 +172,11 @@ export class PullRequestPublisher {
172172
return { kind: 'opened', number: pr.number, url: pr.url, draft: pr.draft, status };
173173
}
174174

175+
/** Whether a lost opening is the current publish's own: the task has not changed since it began, and the mode matches. */
176+
#isCurrent(identity: PlanIdentity, lost: TaskPullRequest, draft: boolean): boolean {
177+
return this.#store.getTask(identity).stateVersion === lost.ownerVersion && lost.draft === draft;
178+
}
179+
175180
/** The task's PR records for one branch into one base, in the configured repository. */
176181
#branchRows(prs: readonly TaskPullRequest[], branch: string, base: string): TaskPullRequest[] {
177182
return prs.filter(pr => pr.headBranch === branch && pr.base === base && pr.repository.toLowerCase() === this.#config.repository.toLowerCase());
@@ -182,7 +187,7 @@ export class PullRequestPublisher {
182187
* does not prove the request was refused while GitHub may still apply or show it, so the opening stays owned until
183188
* the settle time has passed; only then is it abandoned. The caller retries after OpeningUnsettled.
184189
*/
185-
async #recover(identity: PlanIdentity, signal?: AbortSignal): Promise<PublishOutcome | null> {
190+
async #recover(identity: PlanIdentity, draft: boolean, signal?: AbortSignal): Promise<PublishOutcome | null> {
186191
// An update whose confirmation was lost is repeated, not adopted: its description may or may not have landed.
187192
const refreshing = this.#store.taskPullRequests(identity).find(pr => pr.refresh !== null);
188193
if (refreshing) this.#store.abandonRefresh(identity, refreshing.openingId);
@@ -210,15 +215,21 @@ export class PullRequestPublisher {
210215
// failure keeps the opening owned (the next publish retries); drafts being unsupported is definite, so the PR is
211216
// recorded as it is and reported.
212217
let found: { number: number; url: string; headSha: string; draft: boolean } = pr;
213-
if (lost.draft && !pr.draft) {
218+
// Only when this publish is itself a draft publish; a ready publish's main path marks the PR ready anyway.
219+
if (lost.draft && draft && !pr.draft) {
214220
try { found = await this.#pulls.markDraft(pr.number, { base: lost.base, headBranch: lost.headBranch, marker: marker(lost.openingId) }, signal); }
215221
catch (error) {
216222
if (!(error instanceof DraftsUnsupported)) throw error;
223+
const current = this.#isCurrent(identity, lost, draft);
217224
this.#store.recordPullRequestOpened(identity, lost.openingId, pr);
218-
return { kind: 'draft unsupported', number: pr.number };
225+
return current ? { kind: 'draft unsupported', number: pr.number } : null;
219226
}
220227
}
228+
// The recovered opening finishes this publish only if it is this publish's own work: same task version and same
229+
// draft mode. Otherwise (the task was rerun, or moved between ready and needs human) the PR is recorded and this
230+
// publish continues, so the main path pushes the current head and refreshes the PR into the current mode.
231+
const current = this.#isCurrent(identity, lost, draft);
221232
const status = this.#store.recordPullRequestOpened(identity, lost.openingId, found);
222-
return { kind: 'opened', number: found.number, url: found.url, draft: found.draft, status };
233+
return current ? { kind: 'opened', number: found.number, url: found.url, draft: found.draft, status } : null;
223234
}
224235
}

‎test/already-fixed.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ describe('the pre-PR already-fixed check', () => {
120120
{ totalCount: 101 }, { hasNextPage: true }, { nodes: [cross(pr(1))], totalCount: 2 },
121121
{ commits: Array.from({ length: MAX_BASE_COMMITS + 1 }, (_, i) => ({ sha: sha(2000 + i), message: 'x' })) }, { status: 'diverged' }, { status: 'behind' },
122122
{ commits: [{ sha: sha(5), message: 'x' }], totalCommits: 2 },
123+
{ commits: [{ sha: sha(5), message: 'x' }, { sha: sha(5), message: 'x' }] },
123124
{ errors: [{ message: 'rate limited' }] }, { nameWithOwner: 'other/repo' }, { baseRef: 'other' },
124125
{ state: 'CLOSED' }, { nodes: [cross(null)] }, { nodes: [cross({ __typename: 'Discussion' })] },
125126
{ nodes: [cross(pr(1, 'OPEN', { repository: null }))] }, { nodes: [{ __typename: 'LabeledEvent' }] },

‎test/publish.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,18 @@ describe('recovering a lost opening', () => {
329329
expect(store.taskPullRequests(identity)).toMatchObject([{ state: 'opened', number: 100, draft: true }]);
330330
expect(store.getTask(identity).status).toBe('needs human');
331331
});
332+
it('records a recovered opening from an older run, then continues the current publish with the new head and mode', async () => {
333+
const store = runningTask(), live = new Map<string, OpenedPullRequest>(), next = { value: 100 };
334+
store.transitionTask(identity, store.getTask(identity).stateVersion, 'needs human');
335+
// A needs-human draft POST lands, but its answer is lost.
336+
await expect(harness(store, { live, next, openTimesOut: true }).publisher.publish(identity, { problems: ['x'] })).rejects.toThrow('timeout');
337+
// The person sends the task back; it reruns (new head oid3) and now publishes as ready.
338+
rerun(store);
339+
const again = harness(store, { live, next });
340+
expect(await again.publisher.publish(identity)).toMatchObject({ kind: 'opened', number: 100, draft: false, status: 'in review' });
341+
expect(again.log.filter(line => !line.startsWith('find'))).toEqual(['check', 'push codeboost/issue-12-task-42 003', 'refresh 100 ready']);
342+
expect(store.taskPullRequests(identity)).toMatchObject([{ state: 'opened', number: 100, draft: false, headSha: oid(3) }]);
343+
});
332344
it('keeps an unconfirmed opening owned until it settles, then abandons it, checks again and opens a new PR', async () => {
333345
const store = runningTask();
334346
await expect(harness(store, { open: async () => { throw new Error('timeout'); } }).publisher.publish(identity)).rejects.toThrow('timeout');
@@ -772,6 +784,11 @@ describe('GitHub PR adapter', () => {
772784
expect(await new GhPullRequestGateway({ repository: 'owner/repo' }, async () => JSON.stringify([response({ body: `${marker}\nplan quoting ${other}` })]))
773785
.findOpened({ ...input, markers: [other, marker] })).toMatchObject({ marker });
774786
});
787+
it('fails a draft opening that GitHub created as ready, so the opening stays owned for recovery', async () => {
788+
const gh = new GhPullRequestGateway({ repository: 'owner/repo' }, async () => JSON.stringify(response({ draft: false })));
789+
await expect(gh.open({ ...input, draft: true })).rejects.toThrow(/as ready, not as a draft/);
790+
expect(await gh.open({ ...input, draft: false })).toMatchObject({ draft: false });
791+
});
775792
it('finds a lost PR only by its marker, and refuses a PR on the branch that codeboost did not open', async () => {
776793
const calls: string[][] = [];
777794
const found = new GhPullRequestGateway({ repository: 'owner/repo' }, async args => { calls.push([...args]); return JSON.stringify([response()]); });

0 commit comments

Comments
 (0)