Skip to content

Commit fbfe4ce

Browse files
mchwangclaude
andcommitted
Order merge jobs by a per-task sequence when keeping a poll's newer record
A full review response held across another tab's click no longer replaces a running newer job with an earlier ended one: jobs carry a sequence, and a kept running job keeps Merge PR not ready. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent de892bf commit fbfe4ce

5 files changed

Lines changed: 90 additions & 10 deletions

File tree

‎docs/implementation/merge-handoff.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,15 @@ A rebase moves the pull request's base. The guarded merge would then scan only t
6868

6969
## Storage
7070

71-
Schema v19 adds `task_pull_requests.check_id` (the pre-PR check each opening followed) and `merge_jobs`: one row per job or refused click, with three columns: `id` (the click's action ID, primary key), `plan_key` (the task, indexed by `merge_jobs_plan`) and `data`. `data` is a JSON record holding the rest: the click's review token, the guarded merge's action ID once the job reaches that step, `state`, `step`, `reason`, required-check names and states, the merge result URL, start and update times, and `refused` for a refused click. Lookups by state (the running job, the latest job that was not refused) read these JSON fields. A refused click's row is replayed to that click and never shown as the task's job. Writing it never changes the task's state version, so the readiness preparation recorded stays valid while the job waits. A resend of the same click returns its row; another click while a job runs is refused. While a job runs, `prepare-merge` is refused (the job prepares the merge itself). `publish` is refused too, by publishing's own status rule: it publishes only a running task whose plan items have all run, or a task that needs a person, and a job runs only for a task in review or approved but merge blocked. The runner's `start` and `resume` actions are refused too ("A merge is running for this task; wait for it to end or cancel the task."), saved and replayed like other refusals, and neither is offered: a run would move the task's head, and the publish at its end would push it. So no run starts, and no publish can push the pull request's head or begin a refresh of it while the job prepares, waits or merges. Plan import stays allowed during a job, as at any time in review. It changes only the plan, never the branch or the pull request; the readiness the job prepared is then for an older review, so the job's next inspection ends it `failed` ("Pre-merge preparation has not completed for the current review."), or the guarded merge refuses, and nothing is merged.
71+
Schema v19 adds `task_pull_requests.check_id` (the pre-PR check each opening followed) and `merge_jobs`: one row per job or refused click, with three columns: `id` (the click's action ID, primary key), `plan_key` (the task, indexed by `merge_jobs_plan`) and `data`. `data` is a JSON record holding the rest: the click's review token, the guarded merge's action ID once the job reaches that step, `state`, `step`, `reason`, required-check names and states, the merge result URL, `sequence` (the record's place among the task's jobs and refused clicks, from 1, so the browser orders jobs without comparing clock times), start and update times, and `refused` for a refused click. Lookups by state (the running job, the latest job that was not refused) read these JSON fields. A refused click's row is replayed to that click and never shown as the task's job. Writing it never changes the task's state version, so the readiness preparation recorded stays valid while the job waits. A resend of the same click returns its row; another click while a job runs is refused. While a job runs, `prepare-merge` is refused (the job prepares the merge itself). `publish` is refused too, by publishing's own status rule: it publishes only a running task whose plan items have all run, or a task that needs a person, and a job runs only for a task in review or approved but merge blocked. The runner's `start` and `resume` actions are refused too ("A merge is running for this task; wait for it to end or cancel the task."), saved and replayed like other refusals, and neither is offered: a run would move the task's head, and the publish at its end would push it. So no run starts, and no publish can push the pull request's head or begin a refresh of it while the job prepares, waits or merges. Plan import stays allowed during a job, as at any time in review. It changes only the plan, never the branch or the pull request; the readiness the job prepared is then for an older review, so the job's next inspection ends it `failed` ("Pre-merge preparation has not completed for the current review."), or the guarded merge refuses, and nothing is merged.
7272

7373
## API and browser
7474

7575
- `POST /api/action` with `merge` returns at once when the server runs merge jobs (a runner and a pull request published by it, which requires preparation): the reloaded review with the job's latest record as `job`, or, if that reload failed, `{ job, mergeRefreshRequired: true }`. The job may already have moved on or ended by then; the page follows a running job and, for an ended one, asks for a refresh.
7676
- `GET /api/merge` returns `{ queue, job }`: `job` is the task's latest job. A saved refusal is not a job; it is replayed only to its own click.
7777
- Merge PR is offered only while the task is in a mergeable status (read after the inspection) and the only blockers left are ones the job resolves or reports: preparation, a moved base (with a merge conflict it causes), `cmd:` checks, required checks (the job waits for pending ones and ends `blocked` on failing ones, so a person can retry after re-running CI), and mergeability GitHub is still computing.
7878
- While a job runs, the Merge button keeps keyboard focus: it is marked `aria-disabled`, not disabled, and a repeat activation starts nothing. While the click's own request is in flight, the button reads **Requesting merge…** and stays marked, also when the page renders meanwhile (for example when a person selects an item).
79-
- The browser polls `GET /api/merge` with the existing 2 s to 30 s backoff while a job runs, shows its step in the merge banner, and lists waiting checks in the blocker dialog. A full review response read before the poll's latest record of the same job (by its `updatedAt`) keeps that newer record, so a slow **Refresh**, review action, **Refresh plan**, plan import or **Apply** reload does not restart following a job the poll saw end. A click's key is kept until its own job ends or a job newer than the one shown at the click is the latest, so a retry that failed with no answer is resent with the same key. When the job ends, the page updates only the merge control and banner (the outcome, and "Refresh to see the result"), so a person's selection and input survive; after **Refresh**, the page offers **Retry merge** when the job is `blocked`. The design's full step list and a Cancel button come later.
79+
- The browser polls `GET /api/merge` with the existing 2 s to 30 s backoff while a job runs, shows its step in the merge banner, and lists waiting checks in the blocker dialog. A full review response read before the poll's latest record keeps that newer record: a later record of the same job (by its `updatedAt`), or a later job (by its `sequence`, which another tab's click may have started). A kept running job keeps Merge PR not ready and its poll running, so a slow **Refresh**, review action, **Refresh plan**, plan import or **Apply** reload does not restart following a job the poll saw end, or stop following a newer job and offer Retry while it runs. A click's key is kept until its own job ends or a job newer than the one shown at the click is the latest, so a retry that failed with no answer is resent with the same key. When the job ends, the page updates only the merge control and banner (the outcome, and "Refresh to see the result"), so a person's selection and input survive; after **Refresh**, the page offers **Retry merge** when the job is `blocked`. The design's full step list and a Cancel button come later.
8080

8181
## Tests
8282

‎runner/store.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,11 @@ export interface MergeJob {
149149
/** Required checks that have not succeeded yet, as the last inspection read them. */
150150
checks: { context: string; state: string }[];
151151
url: string | null;
152+
/**
153+
* The job's place among the task's jobs and refused clicks, starting at 1: a later click has a higher number. The
154+
* browser orders records of different jobs by it, since wall-clock times can step back.
155+
*/
156+
sequence: number;
152157
startedAt: string;
153158
updatedAt: string;
154159
}
@@ -2140,7 +2145,7 @@ export class Store {
21402145
if (this.runningMergeJob(identity)) throw new GuardRefusal('A merge is already running for this task.');
21412146
const now = input.now ?? new Date().toISOString();
21422147
const job: MergeJob = { id: input.actionId, mergeActionId: null, token: input.token, state: 'running', step: 'preparing', reason: null, checks: [],
2143-
url: null, startedAt: now, updatedAt: now };
2148+
url: null, sequence: this.#nextMergeJobSequence(key), startedAt: now, updatedAt: now };
21442149
this.#run('INSERT INTO merge_jobs VALUES (?,?,?)', job.id, key, encode(job));
21452150
return { job, resent: false };
21462151
});
@@ -2163,11 +2168,16 @@ export class Store {
21632168
}
21642169
const now = new Date().toISOString();
21652170
const job: MergeJob = { id: input.actionId, mergeActionId: null, token: input.token, state: 'failed', step: null,
2166-
reason: input.reason.slice(0, 2_000), checks: [], url: null, startedAt: now, updatedAt: now, refused: true };
2171+
reason: input.reason.slice(0, 2_000), checks: [], url: null, sequence: this.#nextMergeJobSequence(key), startedAt: now, updatedAt: now, refused: true };
21672172
this.#run('INSERT INTO merge_jobs VALUES (?,?,?)', job.id, key, encode(job));
21682173
return job;
21692174
});
21702175
}
2176+
/** One more than the task's highest job sequence; rows in `merge_jobs` are never deleted, so it only grows. */
2177+
#nextMergeJobSequence(key: string): number {
2178+
const row = this.#get(`SELECT COALESCE(MAX(json_extract(data,'$.sequence')),0) AS n FROM merge_jobs WHERE plan_key=?`, key) as { n: number };
2179+
return row.n + 1;
2180+
}
21712181
/** Move a running job to another step or record what it waits for. A job no longer running is left unchanged. */
21722182
updateMergeJob(identity: PlanIdentity, id: string, patch: { step?: MergeJobStep; reason?: string | null; checks?: { context: string; state: string }[];
21732183
mergeActionId?: string }): MergeJob | null {

‎test/browser/review.spec.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -784,6 +784,55 @@ test('keeps a merge-job outcome a poll saw while an older Refresh response was h
784784
await expect(page.getByRole('button',{name:'Preparing…',exact:true})).toHaveCount(0);
785785
});
786786

787+
test('keeps a newer merge job a poll saw while a held Refresh response shows an earlier job ended (F6b)',async({page})=>{
788+
const config={...app.service.config,demo:false};await app.close();removeDemoOutOfScope(config);
789+
const gateway:MergeGateway={inspect:async()=>{const snapshot=(await app.service.load()).snapshot;return {base:snapshot.base,head:snapshot.head,pullRequestState:'OPEN',mergeable:'MERGEABLE',rulesKnown:true,atomicBaseGuard:true,mergeQueue:false,requiredChecks:[],alreadyFixed:'clear',pullRequest:7,draft:false};},merge:async()=>{throw new Error('The browser test answers every merge request itself.');}};
790+
app=await startServer(config,0,undefined,gateway);
791+
let view=await app.service.load();for(const segment of view.segments.filter(value=>value.row==='Unplanned'||value.row==='Ambiguous'))view=await app.service.act({action:'accept',key:segment.key,token:view.token});for(const item of view.items)view=await app.service.act({action:'approve',item:item.id,confirmNoChange:item.count===0,token:view.token});
792+
// Job A runs in this tab. Another tab's click starts job B after A ends; B's record is later than any of A's (sequence),
793+
// while its clock times are earlier, as after a clock step back.
794+
const jobA={id:'0f6b0000-0000-4000-8000-0000000000e1',state:'running',step:'preparing',reason:null,checks:[],url:null,sequence:1,startedAt:'2026-10-11T00:10:00Z',updatedAt:'2026-10-11T00:10:00Z'};
795+
const blockedA={...jobA,state:'blocked',step:null,reason:'Required check failed: ci.',updatedAt:'2026-10-11T00:20:00Z'};
796+
const jobB={...jobA,id:'0f6b0000-0000-4000-8000-0000000000e2',step:'checks',sequence:2,startedAt:'2026-10-11T00:00:00Z',updatedAt:'2026-10-11T00:00:00Z'};
797+
let started=false,hold=false,polls=0,release!:()=>void,holding!:()=>void;
798+
const released=new Promise<void>(resolve=>{release=resolve;}),held=new Promise<void>(resolve=>{holding=resolve;});
799+
await page.route('**/api/merge',route=>{polls++;return route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({queue:null,job:started?jobB:jobA})});});
800+
// The page loads with A running. The held Refresh response was read after A ended (blocked, Retry offered) and before B
801+
// started; it is answered only after the poll has seen B running.
802+
await page.route('**/api/review',async route=>{const response=await route.fetch(),body=await response.json();
803+
if(hold){hold=false;body.merge={...body.merge,ready:true,action:'retry',job:blockedA};holding();await released;}
804+
else body.merge={...body.merge,ready:false,action:null,job:jobA};
805+
await route.fulfill({response,json:body});});
806+
await page.goto(app.url);
807+
await expect(page.getByRole('button',{name:'Preparing…',exact:true})).toBeVisible();
808+
hold=true;
809+
const refreshed=page.waitForResponse(response=>response.url().endsWith('/api/review'));
810+
await page.locator('#review-link').click();await held;
811+
// Selecting an item while Refresh waits renders the merge control, which schedules a poll; that poll sees job B running.
812+
started=true;
813+
await page.getByRole('button',{name:/P2 Document retry behavior/}).click();
814+
await expect(page.getByRole('button',{name:'Waiting for checks…',exact:true})).toBeVisible({timeout:10_000});
815+
await expect(page.locator('#banner')).toHaveText('Waiting for required checks.');
816+
release();
817+
const answer=await (await refreshed).json();
818+
// The interleaving happened: the Refresh answer showed job A ended with Retry offered, after the poll saw B.
819+
expect(answer.merge).toMatchObject({ready:true,action:'retry',job:{id:blockedA.id,state:'blocked'}});
820+
// The older Refresh response does not restore job A: B stays followed, not ready, and its poll keeps running (2 s).
821+
const seen=polls;
822+
await page.waitForTimeout(3_000);
823+
expect(polls).toBeGreaterThan(seen);
824+
const merge=page.locator('#merge');
825+
await expect(merge).toHaveText('Waiting for checks…');
826+
await expect(merge).toHaveAttribute('aria-disabled','true');
827+
await expect(page.getByRole('button',{name:'Retry merge',exact:true})).toHaveCount(0);
828+
// Not ready while B runs: activating the control sends no merge request.
829+
let actions=0,dialogs=0;page.on('request',request=>{if(request.url().endsWith('/api/action'))actions++;});
830+
page.on('dialog',dialog=>{dialogs++;void dialog.accept();});
831+
await merge.dispatchEvent('click');await page.waitForTimeout(500);
832+
expect(dialogs).toBe(0);expect(actions).toBe(0);
833+
await expect(page.locator('#banner')).toHaveText('Waiting for required checks.');
834+
});
835+
787836
/** A runner server whose every full review shows a running merge job (each was read while it ran); the job poll reports
788837
* it merged once `ended` is set. Used to hold one full response while a poll sees the job end. */
789838
async function mergeJobOutcomeRace(page:import('@playwright/test').Page,planning?:PlanningDeps){

‎test/merge-job.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,18 @@ it('keeps a GitHub failure that came before the wait limit, even when the inspec
681681
expect(f.gh.merged).toEqual([]);
682682
});
683683

684+
it('numbers each job and refused click after the task\'s earlier ones, so the browser can order jobs without clocks', async () => {
685+
const f = setup({ prepare: () => 'failed' });
686+
const first = await f.coordinator.start('review-token', randomUUID());
687+
await settled(f.coordinator);
688+
const refusal = f.store.recordMergeJobRefusal(identity, { actionId: randomUUID(), token: 'review-token', reason: 'Refused.' });
689+
// A later click keeps a higher number even when the clock stepped back.
690+
const second = f.store.beginMergeJob(identity, { actionId: randomUUID(), token: 'review-token', now: '2000-01-01T00:00:00.000Z' }).job;
691+
expect([first.sequence, refusal.sequence, second.sequence]).toEqual([1, 2, 3]);
692+
expect(f.coordinator.latest()).toMatchObject({ id: second.id, sequence: 3 });
693+
f.store.finishMergeJob(identity, second.id, { state: 'failed' });
694+
});
695+
684696
// Since #170 a click's admission awaits the review load; these pin what may happen while it does.
685697
it('gives a resend of the same click, during the first send\'s review load, the same job', async () => {
686698
const f = setup(), id = randomUUID(), held = holdNextLoad(f.review as never);

‎web/public/app.js‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -947,19 +947,28 @@ function preserveSettledQuestionAnswers(updated) {
947947
: note;
948948
}) };
949949
}
950-
/** A poll's record of the job a full response also carries, when the poll saw it later than that response did. */
950+
/**
951+
* A poll's record of the task's latest job, when the poll saw it later than a full response read before it. Records of
952+
* one job order by update time; a later job (another tab's click) outranks any record of an earlier one, by the
953+
* server's per-task job sequence, never by clock time.
954+
*/
951955
function newerMergeJob(updated, observationOwner) {
952956
const newer = data?.merge?.job, older = updated.merge?.job;
953-
return observationOwner !== mergeObservationGeneration && newer && older && newer.id === older.id && newer.updatedAt > older.updatedAt
954-
? newer
955-
: null;
957+
if (observationOwner === mergeObservationGeneration || !newer || !older) return null;
958+
const later = newer.id === older.id ? newer.updatedAt > older.updatedAt
959+
: Number.isSafeInteger(newer.sequence) && Number.isSafeInteger(older.sequence) && newer.sequence > older.sequence;
960+
return later ? newer : null;
956961
}
957962
function mergeJobBanner(job) {
958963
return job.state === "running" ? mergeJobText(job) : `${mergeJobText(job)} Refresh to see the result.`;
959964
}
960-
/** The view with a newer observation of its job: an ended job asks for a refresh, as the job poll shows it. */
965+
/**
966+
* The view with a newer observation of its job, as the job poll shows it: a running job is not ready to merge (the
967+
* full response may offer Retry for an earlier job), and an ended job asks for a refresh.
968+
*/
961969
function withMergeJobObservation(view, job) {
962-
if (job.state === "running") return { ...view, merge: { ...view.merge, job } };
970+
if (job.state === "running") return { ...view, merge: { ...view.merge, ready: false, action: null, job,
971+
blockers: view.merge.blockers.filter(blocker => blocker.code !== "job-refresh") } };
963972
const blockers = view.merge.blockers.filter(blocker => !mergeLifecycleBlockers.has(blocker.code));
964973
return { ...view, merge: { ...view.merge, ready: false, action: null, job, blockers: [{ code: "job-refresh", message: mergeJobBanner(job) }, ...blockers] } };
965974
}

0 commit comments

Comments
 (0)