Skip to content

Commit 6c15c41

Browse files
mchwangclaude
andcommitted
Address Copilot round 10 on F2d: own the review version too
- recordAlreadyFixed takes the review version the publish read and refuses a result obtained before a review change. - Each opening and refresh stores the plan's review version it owns; its confirmation still records the PR but moves the task only when both the state version and the review version are unchanged. Recovery treats a lost opening as current only under both. - Design doc: adoption happens in step 3, not in the update; the owned versions are the state and review versions. - AGENTS.md: an in-flight action owns every version counter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent af56100 commit 6c15c41

5 files changed

Lines changed: 72 additions & 28 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ For features with background jobs, polling, retries, cancellation, or shutdown:
99
- Define the lifecycle states and ownership before implementation: pending, running, completed, failed, cancelled, stale, and closing.
1010
- Treat persisted state, in-memory jobs, subprocesses, HTTP requests, and rendered UI as separate state holders. Define how each transitions and settles.
1111
- Never apply a background response without proving it is still current. Use a generation, attempt ID, version, or guarded merge so older polling responses cannot overwrite newer actions.
12+
- When the local state has more than one version counter (for example a task's state version and its plan's review version), an in-flight action owns all of them, and applying its response requires every one to be unchanged. One counter does not cover writes that advance only another.
1213
- A current response may still move a record only along a transition allowed from the state the action was guarded for. Derive the new status from that state as well as the response; a response alone must never move a record out of a state that waits for a person.
1314
- Do not release a concurrency slot when cancellation is requested. Keep the job tracked until its underlying invocation or subprocess has terminated.
1415
- Do not let a retry replace a locally active job, even when its persisted lease has expired or wall-clock time changes.

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,9 @@ Only one publish runs per task at a time; a second one is refused. A publish who
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 (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.
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 was already adopted in step 3, and an update only ever starts on an opened record) 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

61-
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.
61+
Each opening or refresh owns the task state version and the plan's review version at the moment it passed step 6. The PR is always recorded. The status changes only when the task still has both (review input such as approvals, choices and notes changes only the review version). Every status change, admission and context change increases the version. So a response that arrives after the task changed never moves it.
6262

6363
| Task during the GitHub call | PR | Status after |
6464
|---|---|---|

‎runner/publish.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ export class PullRequestPublisher {
128128
catch (error) { if (!(error instanceof DraftsUnsupported)) throw error; leftReady = live.number; }
129129
}
130130
signal?.throwIfAborted();
131-
const check = this.#store.recordAlreadyFixed(identity, stateVersion, { snapshotId: snapshot.id, draft, result });
131+
const check = this.#store.recordAlreadyFixed(identity, stateVersion, { snapshotId: snapshot.id, reviewVersion, draft, result });
132132
if (drafted && earlier!.state === 'opened') this.#store.recordPullRequestDraft(identity, earlier!.openingId, drafted.number, drafted.draft, check.stateVersion);
133133
const ready = leftReady === undefined ? {} : { leftReady };
134134
if (result.outcome !== 'clear') return draft ? { kind: 'draft skipped', result, ...ready } : { kind: 'possibly already fixed', result, ...ready };
@@ -177,9 +177,9 @@ export class PullRequestPublisher {
177177
return { kind: 'opened', number: pr.number, url: pr.url, draft: pr.draft, status };
178178
}
179179

180-
/** Whether a lost opening is the current publish's own: the task has not changed since it began, and the mode matches. */
180+
/** Whether a lost opening is the current publish's own: neither the task nor its review changed since it began, and the mode matches. */
181181
#isCurrent(identity: PlanIdentity, lost: TaskPullRequest, draft: boolean): boolean {
182-
return this.#store.getTask(identity).stateVersion === lost.ownerVersion && lost.draft === draft;
182+
return this.#store.getTask(identity).stateVersion === lost.ownerVersion && this.#store.reviewVersion(identity) === lost.ownerReviewVersion && lost.draft === draft;
183183
}
184184

185185
/** The task's PR records for one branch into one base, in the configured repository. */

‎runner/store.ts‎

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ export interface TaskPullRequest {
3030
state: 'opening' | 'opened' | 'abandoned'; number: number | null; url: string | null; createdAt: string;
3131
/** The task state version this opening owns; only a response for that exact version may change the task status. */
3232
ownerVersion: number;
33+
/** The plan's review version this opening owns: review input (approvals, choices, notes) since then makes it stale. */
34+
ownerReviewVersion: number;
3335
/** An update of this open PR that started and has not been confirmed; the PR may already show it. */
3436
refresh: { head: string; draft: boolean; stateVersion: number } | null;
3537
}
@@ -913,9 +915,9 @@ export class Store {
913915
state_version INTEGER NOT NULL, review_version INTEGER NOT NULL, checked_at TEXT NOT NULL);
914916
CREATE TABLE IF NOT EXISTS task_pull_requests (
915917
opening_id TEXT PRIMARY KEY, plan_key TEXT NOT NULL REFERENCES tasks(plan_key), repository TEXT NOT NULL, base TEXT NOT NULL,
916-
head_branch TEXT NOT NULL, head_sha TEXT NOT NULL, draft INTEGER NOT NULL, owner_version INTEGER NOT NULL,
918+
head_branch TEXT NOT NULL, head_sha TEXT NOT NULL, draft INTEGER NOT NULL, owner_version INTEGER NOT NULL, owner_review_version INTEGER NOT NULL,
917919
state TEXT NOT NULL CHECK (state IN ('opening','opened','abandoned')), number INTEGER, url TEXT,
918-
refresh_head TEXT, refresh_draft INTEGER, refresh_version INTEGER,
920+
refresh_head TEXT, refresh_draft INTEGER, refresh_version INTEGER, refresh_review_version INTEGER,
919921
created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
920922
CHECK ((state = 'opened') = (number IS NOT NULL AND url IS NOT NULL)));
921923
CREATE UNIQUE INDEX IF NOT EXISTS task_pull_requests_number ON task_pull_requests (lower(repository), number) WHERE number IS NOT NULL;
@@ -927,7 +929,7 @@ export class Store {
927929
openingId: row.opening_id as string, repository: row.repository as string, base: row.base as string, headBranch: row.head_branch as string,
928930
headSha: row.head_sha as string, draft: row.draft === 1, state: row.state as TaskPullRequest['state'],
929931
number: row.number as number | null, url: row.url as string | null, createdAt: row.created_at as string,
930-
ownerVersion: row.owner_version as number,
932+
ownerVersion: row.owner_version as number, ownerReviewVersion: row.owner_review_version as number,
931933
refresh: row.refresh_head === null ? null : { head: row.refresh_head as string, draft: row.refresh_draft === 1, stateVersion: row.refresh_version as number },
932934
};
933935
}
@@ -952,7 +954,7 @@ export class Store {
952954
* Records a pre-PR check. A match, or a check that could not be completed, moves a running task to possibly already
953955
* fixed in the same transaction. A needs-human task keeps its status; its draft PR is not opened.
954956
*/
955-
recordAlreadyFixed(identity: PlanIdentity, expectedStateVersion: number, input: { snapshotId: string; draft: boolean; result: AlreadyFixedResult }): AlreadyFixedCheck {
957+
recordAlreadyFixed(identity: PlanIdentity, expectedStateVersion: number, input: { snapshotId: string; reviewVersion: number; draft: boolean; result: AlreadyFixedResult }): AlreadyFixedCheck {
956958
if (!['clear', 'found', 'unknown'].includes(input.result?.outcome)) throw new Error('Invalid already-fixed result.');
957959
const key = identityKey(identity);
958960
return this.#transaction(() => {
@@ -962,8 +964,10 @@ export class Store {
962964
if (input.result.outcome !== 'clear' && !input.draft) this.#run("UPDATE tasks SET status='possibly already fixed' WHERE plan_key=?", key);
963965
this.#touch(key);
964966
const id = randomUUID(), checkedAt = new Date().toISOString(), stateVersion = this.#task(key).state_version as number;
965-
// Review input (approvals, choices, notes) advances review_version without touching the task; bind the check to both.
967+
// Review input (approvals, choices, notes) advances review_version without touching the task; bind the check to both,
968+
// and refuse a result the publish obtained before a review change (it would move the task on stale review state).
966969
const reviewVersion = this.#current(key).review_version as number;
970+
if (reviewVersion !== input.reviewVersion) throw new GuardRefusal('The review changed during the check. Reload before writing.');
967971
this.#run('INSERT INTO already_fixed_checks (id,plan_key,snapshot_id,outcome,result,state_version,review_version,checked_at) VALUES (?,?,?,?,?,?,?,?)',
968972
id, key, input.snapshotId, input.result.outcome, encode(input.result), stateVersion, reviewVersion, checkedAt);
969973
return { id, snapshotId: input.snapshotId, result: input.result, stateVersion, reviewVersion, checkedAt };
@@ -980,9 +984,9 @@ export class Store {
980984
if (this.#get("SELECT 1 FROM task_pull_requests WHERE plan_key=? AND state='opening'", key)) throw new GuardRefusal('A pull request is already being opened; recover it first.');
981985
const openingId = randomUUID(), now = new Date().toISOString();
982986
this.#touch(key);
983-
this.#run(`INSERT INTO task_pull_requests (opening_id,plan_key,repository,base,head_branch,head_sha,draft,owner_version,state,number,url,created_at,updated_at)
984-
VALUES (?,?,?,?,?,?,?,?,'opening',NULL,NULL,?,?)`, openingId, key, input.repository, input.base, input.headBranch, input.headSha, input.draft ? 1 : 0,
985-
this.#task(key).state_version as number, now, now);
987+
this.#run(`INSERT INTO task_pull_requests (opening_id,plan_key,repository,base,head_branch,head_sha,draft,owner_version,owner_review_version,state,number,url,created_at,updated_at)
988+
VALUES (?,?,?,?,?,?,?,?,?,'opening',NULL,NULL,?,?)`, openingId, key, input.repository, input.base, input.headBranch, input.headSha, input.draft ? 1 : 0,
989+
this.#task(key).state_version as number, this.#current(key).review_version as number, now, now);
986990
return this.taskPullRequests(identity).find(pr => pr.openingId === openingId)!;
987991
});
988992
}
@@ -1000,16 +1004,16 @@ export class Store {
10001004
if (row?.state !== 'opened') throw new GuardRefusal('Unknown pull request.');
10011005
this.#touch(key);
10021006
const version = this.#task(key).state_version as number;
1003-
this.#run('UPDATE task_pull_requests SET refresh_head=?, refresh_draft=?, refresh_version=?, updated_at=? WHERE opening_id=?',
1004-
input.headSha, input.draft ? 1 : 0, version, new Date().toISOString(), input.openingId);
1007+
this.#run('UPDATE task_pull_requests SET refresh_head=?, refresh_draft=?, refresh_version=?, refresh_review_version=?, updated_at=? WHERE opening_id=?',
1008+
input.headSha, input.draft ? 1 : 0, version, this.#current(key).review_version as number, new Date().toISOString(), input.openingId);
10051009
return version;
10061010
});
10071011
}
10081012
/** An unconfirmed update is dropped; the next publish checks again and repeats it (the update is idempotent). */
10091013
abandonRefresh(identity: PlanIdentity, openingId: string): void {
10101014
const key = identityKey(identity);
10111015
this.#transaction(() => {
1012-
if (this.#run("UPDATE task_pull_requests SET refresh_head=NULL, refresh_draft=NULL, refresh_version=NULL, updated_at=? WHERE plan_key=? AND opening_id=? AND refresh_head IS NOT NULL",
1016+
if (this.#run("UPDATE task_pull_requests SET refresh_head=NULL, refresh_draft=NULL, refresh_version=NULL, refresh_review_version=NULL, updated_at=? WHERE plan_key=? AND opening_id=? AND refresh_head IS NOT NULL",
10131017
new Date().toISOString(), key, openingId).changes !== 1) throw new GuardRefusal('No update of this pull request is in flight.');
10141018
this.#touch(key);
10151019
});
@@ -1030,7 +1034,7 @@ export class Store {
10301034
const key = identityKey(identity);
10311035
return this.#confirmPullRequest(key, pr, () =>
10321036
this.#get("SELECT * FROM task_pull_requests WHERE plan_key=? AND opening_id=? AND state='opening'", key, openingId),
1033-
row => ({ head: row.head_sha as string, owned: row.owner_version as number }), openingId, 'No pull request is being opened with this ID.');
1037+
row => ({ head: row.head_sha as string, owned: row.owner_version as number, ownedReview: row.owner_review_version as number }), openingId, 'No pull request is being opened with this ID.');
10341038
}
10351039
/** A refresh of the task's open PR landed, for the head and state version beginRefresh recorded. Same status rule. */
10361040
recordRefreshConfirmed(identity: PlanIdentity, openingId: string, pr: { number: number; url: string; headSha: string; draft: boolean },
@@ -1039,22 +1043,23 @@ export class Store {
10391043
return this.#confirmPullRequest(key, pr, () =>
10401044
this.#get("SELECT * FROM task_pull_requests WHERE plan_key=? AND opening_id=? AND state='opened' AND number=? AND refresh_head=? AND refresh_version=?",
10411045
key, openingId, pr.number, refresh.head, refresh.stateVersion),
1042-
() => ({ head: refresh.head, owned: refresh.stateVersion }), openingId, 'No update of this pull request is in flight.');
1046+
row => ({ head: refresh.head, owned: refresh.stateVersion, ownedReview: row.refresh_review_version as number }), openingId, 'No update of this pull request is in flight.');
10431047
}
10441048
#confirmPullRequest(key: string, pr: { number: number; url: string; headSha: string; draft: boolean }, find: () => Record<string, SQLOutputValue> | undefined,
1045-
expected: (row: Record<string, SQLOutputValue>) => { head: string; owned: number }, openingId: string, missing: string): TaskStatus {
1049+
expected: (row: Record<string, SQLOutputValue>) => { head: string; owned: number; ownedReview: number }, openingId: string, missing: string): TaskStatus {
10461050
if (!Number.isSafeInteger(pr.number) || pr.number < 1 || typeof pr.url !== 'string') throw new Error('Invalid pull request.');
10471051
return this.#transaction(() => {
10481052
const row = find();
10491053
if (!row) throw new GuardRefusal(missing);
1050-
const { head, owned } = expected(row);
1051-
this.#run("UPDATE task_pull_requests SET state='opened', number=?, url=?, draft=?, head_sha=?, refresh_head=NULL, refresh_draft=NULL, refresh_version=NULL, updated_at=? WHERE opening_id=?",
1054+
const { head, owned, ownedReview } = expected(row);
1055+
this.#run("UPDATE task_pull_requests SET state='opened', number=?, url=?, draft=?, head_sha=?, refresh_head=NULL, refresh_draft=NULL, refresh_version=NULL, refresh_review_version=NULL, updated_at=? WHERE opening_id=?",
10521056
pr.number, pr.url, pr.draft ? 1 : 0, head, new Date().toISOString(), openingId);
10531057
const task = this.#task(key);
10541058
// Every status change and every admission increases the state version, so an unchanged version means the task is
1055-
// still in the status the opening or refresh was guarded for with no attempt active. A needs-human task stays
1056-
// there whatever the PR looks like; only a running task can move to in review.
1057-
if (task.state_version === owned && task.status === 'running') {
1059+
// still in the status the opening or refresh was guarded for with no attempt active. Review input advances only the
1060+
// review version, so that must be unchanged too. A needs-human task stays there whatever the PR looks like; only a
1061+
// running task can move to in review.
1062+
if (task.state_version === owned && this.#current(key).review_version === ownedReview && task.status === 'running') {
10581063
this.#run('UPDATE tasks SET status=? WHERE plan_key=?', pr.headSha === head && !pr.draft ? 'in review' : 'needs human', key);
10591064
}
10601065
this.#touch(key);

0 commit comments

Comments
 (0)