diff --git a/changelog.d/pan-5995.md b/changelog.d/pan-5995.md new file mode 100644 index 00000000000..a11e00ba493 --- /dev/null +++ b/changelog.d/pan-5995.md @@ -0,0 +1,5 @@ +#### Fixed + +- **A half-merged UAT batch survives a dashboard restart and can be finished:** when a polyrepo batch merge stops after some repos landed, the batch is no longer voided, replaced or cleaned up, and no new batch is built for that project until it is finished. The board shows it as "partially promoted: resume promote". Merging it again checks that the landed repos really merged, that each remaining repo's batch branch is unchanged since it was built, and that its members' pull requests there are still open, at the reviewed heads, and have no changes requested. A repo whose push landed before a crash but was never recorded counts as landed. It then publishes only the remaining repos and runs the normal post-merge steps. If any check fails, it refuses with the reason and changes nothing. A batch that can never be finished can be abandoned with `pan merge void --abandon-partial --reason `: landed repos keep their merges, the batch's branches are cleaned up, and new batches can be built again. ([#5995](https://github.com/eltmon/overdeck/issues/5995)) +- **A ready feature keeps its batch with the merge train off:** an older merged PR on a reused feature branch no longer voids a batch whose member is ready now. ([#5995](https://github.com/eltmon/overdeck/issues/5995)) +- **Failed UAT batch cleanup backs off:** a cleanup that keeps failing now waits 1 minute, doubling per failure up to 1 hour, instead of retrying every tick. ([#5995](https://github.com/eltmon/overdeck/issues/5995)) diff --git a/docs/MERGE-TRAIN.md b/docs/MERGE-TRAIN.md index 6290f411076..964f8900628 100644 --- a/docs/MERGE-TRAIN.md +++ b/docs/MERGE-TRAIN.md @@ -261,15 +261,22 @@ never deleted, and `safeGenerationWorktreePath` accepts only a `uat-*` folder under `workspaces/`, so a `feature-*` workspace is never removed. Every cleanup git call has a 60-second timeout (`CLEANUP_GIT_TIMEOUT_MS`). A step succeeds only when git succeeds or says the target is already gone (`removeOrAlreadyGone`: -"remote ref does not exist", "branch … not found", "is not a working tree"). -Any other failure, including a timeout, leaves `cleaned_at` unset, so the next -tick retries and no origin `uat/*` branch is silently leaked. There is no -backoff: a batch whose cleanup keeps failing is retried, and logged, every -tick. A failed stack teardown skips that batch's worktree and branch removal -for the tick, so the worktree is never removed under a running `compose down`. -For a polyrepo batch, a member repo the batch never recorded (a failed -assembly) has its leftover `/` worktree removed before its -branch is deleted. Stack teardown in +"remote ref does not exist", "branch … not found", or git's exact LC_ALL=C line +`fatal: '' is not a working tree`). Any other failure, including a +timeout, leaves `cleaned_at` unset, so a later tick retries and no origin +`uat/*` branch is silently leaked. A failed attempt backs that batch off +(PAN-5995): `cleanup_attempts` counts the failures and +`cleanup_next_attempt_at` holds the next try, 1 minute after the first failure, +doubling per failure, capped at 1 hour (`cleanupBackoffMs`). A success clears +both. Neither write moves `updated_at`, so a failing cleanup never restarts a +superseded batch's 24-hour grace period. A failed stack teardown skips that +batch's worktree and branch removal for the tick, so the worktree is never +removed under a running `compose down`. For a polyrepo batch, a member repo +the batch never recorded (a failed assembly) has its leftover +`/` worktree removed before its branch is deleted. That sweep +refuses to run when any such repo key is not one plain path segment (it +contains `/`, `\` or `..`), so a key can never reach outside its own +`workspaces/uat-*` folder. Stack teardown in the reconciler and in cleanup is bounded at 120 seconds (`UAT_TEARDOWN_DEADLINE_MS`), below compose's own 300-second cap. @@ -279,6 +286,59 @@ neither stamps nor invalidates a marked generation, cleanup does not reap it, and the void verb refuses it, so promote's final `promoted` write never overwrites a void. +**Partially promoted batches (PAN-5995).** The in-process set is lost when the +dashboard restarts. A polyrepo promote publishes one member repo at a time and +stamps each repo's `promoted_at` as it lands, so the durable record of a +half-finished promote is a batch that is not `promoted` but has at least one +repo with `promoted_at` (`isUatGenerationPartiallyPromoted`). Whatever the train +setting or the departure evidence, such a batch is never invalidated by the +reconciler, superseded by a new assembly, voided by another batch's promote or +by `pan merge void` (409), or reaped by cleanup. While a `ready` one exists the +reconciler assembles nothing for the project, even when forced (action +`partially-promoted`); the hold lifts once the row reads `promoted`. The +reconciler logs it and the board shows it as "partially promoted: resume +promote". + +To finish it, merge the batch again. The normal member gate cannot pass: a +member whose repo already landed reads as merged and leaves the ready set. So +for a partially promoted batch, and only for one, `uat-promote-members.ts` +replaces that gate, and the promote checks the rest: + +- every stamped repo is confirmed merged on its target (`findLandedMerge` + finds a merge containing the `uat/*` head assembly recorded; a current tip + that differs from that head, a rewritten branch, never counts as landed, and + a repo with no recorded head cannot be proven, so the resume refuses); +- every pending repo's `uat/*` branch on origin is still at the head assembly + recorded (`uat_generation_repos.head_sha`, PAN-5995; a row without one is + refused); +- in every pending repo, each member's PR or MR is open, has no changes + requested (GitHub `CHANGES_REQUESTED`, GitLab `requested_changes`), and is + at the head the batch bundled. A PR that is no longer open passes only when + its repo already landed without its stamp (`findLandedMerge` finds the merge: + a push the remote accepted before a crash or a timeout). Promote's recovery + then stamps that repo before anything else runs; +- a member with work in a pending repo still lands only at the heads its + review approved (the PAN-5786 reviewed-heads check, which reads review + records rather than the PR). The merge gate (approval and CI per PR) and + the ready-set check are not used: they judge PRs the landed repos merged; +- each pending repo's target is unchanged over the batch's files and the + trial merge is clean (the normal phase A checks). + +Any failure refuses with the reason and publishes nothing. Otherwise the +promote skips the stamped repos, lands the rest, finalizes the batch and runs +the normal per-member post-merge path. The reconciler never stamps a +partially promoted batch `promoted` on containment evidence, even when every +repo landed: the resumed promote finalizes it, so post-merge runs. +`uatBranchHead` fetches the `uat/*` ref before it reads it, and the trial merge +merges that verified SHA, not the ref name, so a fetch in between cannot swap +what lands. A batch assembled before PAN-5995 has no recorded head, so its +resume is refused. + +If a partially promoted batch cannot be resumed (a remaining PR was closed for +good, a target moved over the batch's files, the `uat/*` branch moved), the +operator abandons it: `pan merge void --abandon-partial --reason +` (see "Voiding a batch"). Nothing else ends a partially promoted batch. + ### When the train is off Turning the train off stops new batches; it does not freeze the existing ones @@ -290,7 +350,9 @@ forge or git read. With a live batch it runs the reconciler with - stamps a batch whose branch is contained in main `promoted`; - invalidates a batch, and stops its stack, only on positive evidence that a - member left it: the member merged outside the batch, its PR or MR is no + member left it. A member in the ready set right now is never departed + (PAN-5995: checked before the merged-ids evidence, so an older merged PR on a + reused `feature/` branch cannot void it). Otherwise: the member merged outside the batch, its PR or MR is no longer open, changes were requested, or its branch head moved (`departureEvidence`, `uat-departure-evidence.ts`, reading the same cached listings as the ready set). A member that is merely not ready right now @@ -321,7 +383,20 @@ void. The journal entry is written before the teardown. Voiding a batch that is already `invalidated` succeeds and changes nothing (`alreadyVoided: true`), so a retry after a lost answer is safe. It refuses an `assembling` batch, because the engine's final write would overwrite the void; a batch a promote is -merging, for the same reason; and a `promoted` or `failed` batch. The next tick's +merging, for the same reason; a partially promoted batch (PAN-5995), whose +promote must be resumed; and a `promoted` or `failed` batch. + +`--abandon-partial` (PAN-5995, needs `--reason`; body `{ abandonPartial: true, +reason }` on the same admin-only route) is the operator's exit for a partially +promoted batch that cannot be resumed. It never reverts a landed repo and +never touches a target branch. It writes the activity entry first and is +refused (503, nothing changed) when that write fails, since the entry is the +record of what was left landed. The row then becomes `invalidated` with a reason +naming the landed and the unlanded repos; the landed repos keep their +`promoted_at` and merge SHA rows as the record. An `invalidated` row no longer +counts as partially promoted, so the assembly hold lifts, and cleanup reaps +the batch's `uat/*` branches and worktrees like any voided batch. The activity +entry says it was abandoned and what landed. The next tick's cleanup removes the worktree and branches, whether the train is on or off. With the train on, that same tick may assemble a fresh batch from the features that are still ready: a void retires that tree, and does not hold the diff --git a/packages/contracts/src/composer-commands.generated.ts b/packages/contracts/src/composer-commands.generated.ts index a24b7eb27f6..eb854a8d392 100644 --- a/packages/contracts/src/composer-commands.generated.ts +++ b/packages/contracts/src/composer-commands.generated.ts @@ -424,7 +424,7 @@ export const COMPOSER_COMMAND_MANIFEST: ComposerCommandManifestEntry[] = [ {"id":"pan-flywheel-stats","path":["flywheel","stats"],"display":"/pan flywheel stats","description":"Substrate-bug discovery rate and P0 count, computed from the tracker and forge","args":[],"options":[{"flags":"--json","description":"Output as JSON","required":false,"valueHint":null},{"flags":"--window ","description":"Window in days (default 30)","required":true,"valueHint":"days"}],"aliases":[],"category":"Flywheel"}, {"id":"pan-merge","path":["merge"],"display":"/pan merge","description":"Merge an issue through the dashboard merge door, or manage Flywheel auto-merge","args":[{"name":"id","required":false,"variadic":false}],"options":[],"aliases":[],"category":"Review"}, {"id":"pan-merge-cancel","path":["merge","cancel"],"display":"/pan merge cancel","description":"Cancel a pending Flywheel auto-merge during its cooldown window","args":[{"name":"id","required":true,"variadic":false}],"options":[],"aliases":[],"category":"Review"}, - {"id":"pan-merge-void","path":["merge","void"],"display":"/pan merge void","description":"Void a UAT batch so it can never merge; the next merge-train tick removes its worktree and uat/* branches (with the train on, it may assemble a fresh batch from features still ready)","args":[{"name":"generation","required":true,"variadic":false}],"options":[{"flags":"--reason ","description":"why the batch is voided (stored on the batch and journaled)","required":true,"valueHint":"text"}],"aliases":[],"category":"Review"}, + {"id":"pan-merge-void","path":["merge","void"],"display":"/pan merge void","description":"Void a UAT batch so it can never merge; the next merge-train tick removes its worktree and uat/* branches (with the train on, it may assemble a fresh batch from features still ready)","args":[{"name":"generation","required":true,"variadic":false}],"options":[{"flags":"--reason ","description":"why the batch is voided (stored on the batch and journaled)","required":true,"valueHint":"text"},{"flags":"--abandon-partial","description":"abandon a partially promoted batch that cannot be resumed; landed repos keep their merges (needs --reason)","required":false,"valueHint":null}],"aliases":[],"category":"Review"}, {"id":"pan-artifacts","path":["artifacts"],"display":"/pan artifacts","description":"Create, publish, validate, inspect, and open shared HTML artifacts","args":[],"options":[],"aliases":[],"category":"Data"}, {"id":"pan-artifacts-create","path":["artifacts","create"],"display":"/pan artifacts create","description":"Validate and publish an HTML artifact","args":[{"name":"file","required":true,"variadic":false}],"options":[{"flags":"--issue ","description":"Issue ID for artifact provenance","required":true,"valueHint":"id"},{"flags":"--workspace ","description":"Workspace ID for artifact provenance","required":true,"valueHint":"id"},{"flags":"--agent-role ","description":"Agent role: plan, work, review, test, ship, flywheel, or user","required":true,"valueHint":"role"},{"flags":"--agent-harness ","description":"Agent harness: claude-code, pi, ohmypi, codex, acp, kimi-code, opencode, muse, prime-agent, grok, antigravity, or user","required":true,"valueHint":"harness"},{"flags":"--run-id ","description":"Run ID for artifact provenance","required":true,"valueHint":"id"},{"flags":"--session-id ","description":"Session ID for artifact provenance","required":true,"valueHint":"id"},{"flags":"--title ","description":"Artifact title","required":true,"valueHint":"title"},{"flags":"--description <text>","description":"Artifact description","required":true,"valueHint":"text"},{"flags":"--strict","description":"Enable strict validation warnings","required":false,"valueHint":null},{"flags":"--json","description":"Emit JSON result","required":false,"valueHint":null}],"aliases":[],"category":"Data"}, {"id":"pan-artifacts-publish","path":["artifacts","publish"],"display":"/pan artifacts publish","description":"Revalidate and republish an existing artifact when changes are pending","args":[{"name":"file","required":true,"variadic":false}],"options":[{"flags":"--strict","description":"Enable strict validation warnings","required":false,"valueHint":null},{"flags":"--json","description":"Emit JSON result","required":false,"valueHint":null}],"aliases":[],"category":"Data"}, diff --git a/src/cli/commands/__tests__/merge.test.ts b/src/cli/commands/__tests__/merge.test.ts index 82334015052..43582a19436 100644 --- a/src/cli/commands/__tests__/merge.test.ts +++ b/src/cli/commands/__tests__/merge.test.ts @@ -368,12 +368,36 @@ describe('merge CLI', () => { expect(process.exitCode).toBe(1); }); - it('is registered as `pan merge void <generation> --reason`', async () => { + it('is registered as `pan merge void <generation> --reason [--abandon-partial]`', async () => { const program = new Command(); registerMergeCommands(program); const merge = program.commands.find((c) => c.name() === 'merge')!; const voidCmd = merge.commands.find((c) => c.name() === 'void')!; - expect(voidCmd.options.map((o) => o.long)).toContain('--reason'); + expect(voidCmd.options.map((o) => o.long)).toEqual(expect.arrayContaining(['--reason', '--abandon-partial'])); + }); + + it('PAN-5995: --abandon-partial posts abandonPartial with the reason and reports the abandon', async () => { + const call = vi.fn().mockResolvedValue({ + ok: true, status: 200, + json: async () => ({ voided: 'uat/min-dune-1128-3', statusReason: 'abandoned by the operator while partially promoted (landed: fe@m1; not landed: api): x', stackTeardown: 'done', abandoned: true }), + }); + + await mergeVoidCommand('uat/min-dune-1128-3', { reason: 'x', abandonPartial: true }, call as never); + + expect(call).toHaveBeenCalledWith('/api/merge-train/generations/min-dune-1128-3/void', expect.objectContaining({ + method: 'POST', body: { reason: 'x', abandonPartial: true }, + })); + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Abandoned uat/min-dune-1128-3')); + expect(process.exitCode).toBeUndefined(); + }); + + it('PAN-5995: --abandon-partial without --reason fails before calling the dashboard', async () => { + const call = vi.fn(); + + await mergeVoidCommand('uat/min-dune-1128-3', { abandonPartial: true }, call as never); + + expect(call).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); }); }); diff --git a/src/cli/commands/merge.ts b/src/cli/commands/merge.ts index e680c9c57a8..e55786a8f5c 100644 --- a/src/cli/commands/merge.ts +++ b/src/cli/commands/merge.ts @@ -196,10 +196,14 @@ const GENERATION_NAME_SHAPE = /^(uat\/)?[A-Za-z0-9][A-Za-z0-9._-]*$/; * The dashboard's next merge-train tick removes its uat-* worktree and uat/* * branches; with the train on, that tick may assemble a fresh batch from the * features that are still ready. Nothing calls this automatically. + * + * PAN-5995: `--abandon-partial` (with a required `--reason`) is the operator's + * exit for a partially promoted batch that cannot be resumed. Landed repos + * keep their merges; the batch becomes `invalidated` and cleanup reaps it. */ export async function mergeVoidCommand( generation: string, - options: { reason?: string } = {}, + options: { reason?: string; abandonPartial?: boolean } = {}, call: typeof callDashboard = callDashboard, ): Promise<void> { const name = generation.trim(); @@ -208,23 +212,33 @@ export async function mergeVoidCommand( process.exitCode = 1; return; } + if (options.abandonPartial && !options.reason?.trim()) { + console.error('--abandon-partial needs --reason <text>: say why the rest of the batch will not land'); + process.exitCode = 1; + return; + } const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), MERGE_VOID_REQUEST_TIMEOUT_MS); try { // The route re-adds `uat/`; sending it bare keeps an encoded slash out of the URL. const res = await call(`/api/merge-train/generations/${encodeURIComponent(name.replace(/^uat\//, ''))}/void`, { method: 'POST', - body: options.reason ? { reason: options.reason } : {}, + body: { + ...(options.reason ? { reason: options.reason } : {}), + ...(options.abandonPartial ? { abandonPartial: true } : {}), + }, signal: controller.signal, }); - const payload = await res.json().catch(() => ({})) as { voided?: unknown; statusReason?: unknown; stackTeardown?: unknown; alreadyVoided?: unknown; error?: unknown }; + const payload = await res.json().catch(() => ({})) as { voided?: unknown; statusReason?: unknown; stackTeardown?: unknown; alreadyVoided?: unknown; abandoned?: unknown; error?: unknown }; if (res.ok && typeof payload.voided === 'string' && payload.alreadyVoided === true) { console.log(`${payload.voided} was already voided (${String(payload.statusReason)}); nothing changed.`); return; } if (res.ok && typeof payload.voided === 'string') { const teardown = payload.stackTeardown === 'failed' ? ' Its UAT stack did not stop; cleanup retries it.' : ''; - console.log(`Voided ${payload.voided} (${String(payload.statusReason)}). The next merge-train tick removes its worktree and branches.${teardown}`); + console.log(payload.abandoned === true + ? `Abandoned ${payload.voided} (${String(payload.statusReason)}). Landed repos keep their merges; the next merge-train tick removes its worktrees and uat/* branches, and new batches may assemble.${teardown}` + : `Voided ${payload.voided} (${String(payload.statusReason)}). The next merge-train tick removes its worktree and branches.${teardown}`); return; } console.error(`Void refused for ${name}: ${typeof payload.error === 'string' ? payload.error : `Dashboard returned HTTP ${res.status}`}`); @@ -268,5 +282,6 @@ export function registerMergeCommands(program: Command): void { .command('void <generation>') .description('Void a UAT batch so it can never merge; the next merge-train tick removes its worktree and uat/* branches (with the train on, it may assemble a fresh batch from features still ready)') .option('--reason <text>', 'why the batch is voided (stored on the batch and journaled)') - .action((generation: string, opts: { reason?: string }) => mergeVoidCommand(generation, opts)); + .option('--abandon-partial', 'abandon a partially promoted batch that cannot be resumed; landed repos keep their merges (needs --reason)') + .action((generation: string, opts: { reason?: string; abandonPartial?: boolean }) => mergeVoidCommand(generation, opts)); } diff --git a/src/dashboard/frontend/src/components/merge-train/train/BatchCard.tsx b/src/dashboard/frontend/src/components/merge-train/train/BatchCard.tsx index 2de1d80b656..7cf0687268b 100644 --- a/src/dashboard/frontend/src/components/merge-train/train/BatchCard.tsx +++ b/src/dashboard/frontend/src/components/merge-train/train/BatchCard.tsx @@ -245,7 +245,8 @@ export function BatchCard({ gen, projectKey, projectName, hero = false, mergeEna // The member menu opens only when it has an item: Merge alone (train on) or Open issue. const live = (gen.status === 'ready' || gen.status === 'assembling') && (mergeEnabled || !!onNavigateIssue); const promotable = isPromotable(gen.status); - const reasonShown = gen.statusReason && (gen.status === 'superseded' || gen.status === 'invalidated'); + // PAN-5995: a ready batch carries a reason only when it is partially promoted. + const reasonShown = gen.statusReason && (gen.status === 'superseded' || gen.status === 'invalidated' || gen.status === 'ready'); const shipPending = gen.status === 'promoted' && gen.versionSyncConfigured === true && gen.shipStatus?.status !== 'passed'; const built = builtAgo(gen.createdAt, now); const repos = gen.repos ?? []; diff --git a/src/dashboard/frontend/src/components/merge-train/train/__tests__/BatchCard.test.tsx b/src/dashboard/frontend/src/components/merge-train/train/__tests__/BatchCard.test.tsx index 3a87347a872..073dba3a9ee 100644 --- a/src/dashboard/frontend/src/components/merge-train/train/__tests__/BatchCard.test.tsx +++ b/src/dashboard/frontend/src/components/merge-train/train/__tests__/BatchCard.test.tsx @@ -58,6 +58,13 @@ describe('BatchCard', () => { expect(screen.queryByTestId('batch-merge-min-otter-1101-4')).toBeNull(); }); + it('PAN-5995: a partially promoted ready batch shows its reason and still offers Merge batch to resume', () => { + mockFetch({}); + renderCard(gen({ status: 'ready', statusReason: 'partially promoted: resume promote' })); + expect(screen.getByTestId('batch-reason-min-otter-1101-4').textContent).toBe('partially promoted: resume promote'); + expect(screen.getByTestId('batch-merge-min-otter-1101-4')).toBeTruthy(); + }); + it.each([ ['ready', true], ['superseded', false], diff --git a/src/dashboard/frontend/src/components/merge-train/train/boardTypes.ts b/src/dashboard/frontend/src/components/merge-train/train/boardTypes.ts index 70cb1540122..df670e45bff 100644 --- a/src/dashboard/frontend/src/components/merge-train/train/boardTypes.ts +++ b/src/dashboard/frontend/src/components/merge-train/train/boardTypes.ts @@ -105,7 +105,7 @@ export interface UatGenerationPayload { errorCode?: string; at: string; } | null; - /** Why the batch became superseded or invalidated (WI-3); null otherwise. */ + /** Why the batch became superseded or invalidated (WI-3), or that it is partially promoted (PAN-5995); null otherwise. */ statusReason?: string | null; /** PAN-5364: the batch whose merge voided this one (invalidated only); null otherwise. */ voidedBy?: string | null; diff --git a/src/dashboard/server/routes/__tests__/merge-train-lanes.test.ts b/src/dashboard/server/routes/__tests__/merge-train-lanes.test.ts index ae5b2e9361b..d060dc3ccf1 100644 --- a/src/dashboard/server/routes/__tests__/merge-train-lanes.test.ts +++ b/src/dashboard/server/routes/__tests__/merge-train-lanes.test.ts @@ -329,6 +329,13 @@ describe('POST /api/merge-train/generations/:name/void', () => { expect(mockVoidUatGeneration).toHaveBeenLastCalledWith('uat/min-dune-1128-3', ''); }); + it('PAN-5995: passes abandonPartial through, and 400s a non-boolean one', async () => { + await postVoid('min-dune-1128-3', { reason: 'api MR closed', abandonPartial: true }); + expect(mockVoidUatGeneration).toHaveBeenLastCalledWith('uat/min-dune-1128-3', 'api MR closed', undefined, { abandonPartial: true }); + expect((await postVoid('min-dune-1128-3', { reason: 'x', abandonPartial: 'yes' })).status).toBe(400); + expect(mockVoidUatGeneration).toHaveBeenCalledTimes(1); + }); + it('passes the service refusal through', async () => { mockVoidUatGeneration.mockResolvedValueOnce({ status: 409, body: { error: 'uat/min-dune-1128-3 is already promoted' } }); const res = await postVoid('min-dune-1128-3', {}); @@ -363,4 +370,14 @@ describe('POST /api/merge-train/generations/:name/void', () => { expect(res.status).toBe(403); expect(mockVoidUatGeneration).not.toHaveBeenCalled(); }); + + it.each(Object.entries(AGENT_TOKEN_SCOPES))('PAN-5995: refuses --abandon-partial from a %s agent token with 403', async (role, scopes) => { + mockVerifyAccessToken.mockReturnValueOnce({ + ok: true, + record: { id: 'tok-1', kind: 'token', scopes: [...scopes], agentId: 'agent-pan-9', agentKind: role === 'conversation' ? 'conversation' : 'agent', role }, + }); + const res = await postVoid('min-dune-1128-3', { reason: 'x', abandonPartial: true }, { Authorization: 'Bearer odk_agent' }); + expect(res.status).toBe(403); + expect(mockVoidUatGeneration).not.toHaveBeenCalled(); + }); }); diff --git a/src/dashboard/server/routes/merge-train-lanes.ts b/src/dashboard/server/routes/merge-train-lanes.ts index 1a9c8e6148a..7e64830a3b5 100644 --- a/src/dashboard/server/routes/merge-train-lanes.ts +++ b/src/dashboard/server/routes/merge-train-lanes.ts @@ -73,7 +73,8 @@ const postMergePolicyRoute = HttpRouter.add( // POST /api/merge-train/generations/:name/void — PAN-5966: the operator voids a // batch so it can never merge; the next reconciler tick cleans up its uat-* -// worktree and uat/* branches. Operator only: no row in route-scopes.ts, so the +// worktree and uat/* branches. PAN-5995: `{ abandonPartial: true, reason }` +// abandons a partially promoted batch (landed repos keep their merges). Operator only: no row in route-scopes.ts, so the // route keeps the `admin` default. Nothing in the system calls it on its own. const postVoidGenerationRoute = HttpRouter.add( 'POST', @@ -93,11 +94,16 @@ const postVoidGenerationRoute = HttpRouter.add( const name = param.startsWith('uat/') ? param : `uat/${param}`; if (!/^uat\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) return jsonResponse({ error: 'Invalid generation name' }, { status: 400 }); const body = yield* readJsonBody; - const rawReason = body && typeof body === 'object' ? (body as Record<string, unknown>)['reason'] : undefined; - if (rawReason !== undefined && typeof rawReason !== 'string') { - return jsonResponse({ error: 'body must be { reason?: string }' }, { status: 400 }); + const fields = body && typeof body === 'object' ? (body as Record<string, unknown>) : {}; + const rawReason = fields['reason']; + const abandonPartial = fields['abandonPartial']; + if ((rawReason !== undefined && typeof rawReason !== 'string') || (abandonPartial !== undefined && typeof abandonPartial !== 'boolean')) { + return jsonResponse({ error: 'body must be { reason?: string, abandonPartial?: boolean }' }, { status: 400 }); } - const result = yield* Effect.promise(() => voidUatGeneration(name, rawReason ?? '')); + // PAN-5995: `abandonPartial` is the operator's exit for a partially promoted batch. + const result = yield* Effect.promise(() => (abandonPartial + ? voidUatGeneration(name, rawReason ?? '', undefined, { abandonPartial: true }) + : voidUatGeneration(name, rawReason ?? ''))); return jsonResponse(result.body, { status: result.status }); })), ); diff --git a/src/dashboard/server/services/__tests__/uat-departure-evidence.test.ts b/src/dashboard/server/services/__tests__/uat-departure-evidence.test.ts index c597cc4ad31..e8129920363 100644 --- a/src/dashboard/server/services/__tests__/uat-departure-evidence.test.ts +++ b/src/dashboard/server/services/__tests__/uat-departure-evidence.test.ts @@ -84,6 +84,11 @@ describe('memberDepartureEvidence', () => { .resolves.toBeNull(); }); + it('PAN-5995: reports a GitLab MR whose reviewer requested changes', async () => { + await expect(memberDepartureEvidence(poly, REPOS, deps({ '/repos/myn/fe': [openPr] }, { '/repos/myn/api': [{ ...openMr, detailed_merge_status: 'requested_changes' }] }))) + .resolves.toBe('had changes requested'); + }); + it('reports a head that moved in one member repo', async () => { await expect(memberDepartureEvidence(poly, REPOS, deps({ '/repos/myn/fe': [openPr] }, { '/repos/myn/api': [{ ...openMr, sha: 'd'.repeat(40) }] }))) .resolves.toBe('branch gained commits in api'); diff --git a/src/dashboard/server/services/__tests__/uat-generation-void.test.ts b/src/dashboard/server/services/__tests__/uat-generation-void.test.ts index 82169e162d6..ab7e5b08dc1 100644 --- a/src/dashboard/server/services/__tests__/uat-generation-void.test.ts +++ b/src/dashboard/server/services/__tests__/uat-generation-void.test.ts @@ -30,6 +30,17 @@ function gen(status: UatGeneration['status']): UatGeneration { }; } +/** PAN-5995: fe landed and was stamped; api did not. */ +function partialRow(): UatGeneration { + return { + ...gen('ready'), + repos: [ + { repoKey: 'fe', repoPath: '/repos/myn/fe', branch: 'uat/min-dune-1128-3', baseSha: 'a', targetBranch: 'main', worktreePath: '/repos/myn/workspaces/uat-min-dune-1128-3/fe', mergeOrder: 0, promotedAt: '2026-11-28T01:00:00.000Z', mergeSha: 'm1' }, + { repoKey: 'api', repoPath: '/repos/myn/api', branch: 'uat/min-dune-1128-3', baseSha: 'b', targetBranch: 'main', worktreePath: '/repos/myn/workspaces/uat-min-dune-1128-3/api', mergeOrder: 1, promotedAt: null, mergeSha: null }, + ], + }; +} + function makeDeps(row: UatGeneration | null, overrides: Partial<VoidUatGenerationDeps> = {}) { const updates: Array<[string, unknown]> = []; const journal: Array<{ message: string; details: string }> = []; @@ -154,6 +165,61 @@ describe('voidUatGeneration', () => { expect(journal).toHaveLength(1); }); + it('PAN-5995: refuses a partially promoted generation with no in-process promote mark (a restart mid-promote)', async () => { + const row: UatGeneration = { + ...gen('ready'), + repos: [ + { repoKey: 'fe', repoPath: '/repos/myn/fe', branch: 'uat/min-dune-1128-3', baseSha: 'a', targetBranch: 'main', worktreePath: '/repos/myn/workspaces/uat-min-dune-1128-3/fe', mergeOrder: 0, promotedAt: '2026-11-28T01:00:00.000Z', mergeSha: 'm1' }, + { repoKey: 'api', repoPath: '/repos/myn/api', branch: 'uat/min-dune-1128-3', baseSha: 'b', targetBranch: 'main', worktreePath: '/repos/myn/workspaces/uat-min-dune-1128-3/api', mergeOrder: 1, promotedAt: null, mergeSha: null }, + ], + }; + const { deps, updates, teardowns, journal } = makeDeps(row); + + const result = await voidUatGeneration('uat/min-dune-1128-3', 'x', deps); + + expect(result.status).toBe(409); + expect((result.body as { error: string }).error).toContain('partially promoted: resume promote'); + // It names the operator's way out. + expect((result.body as { error: string }).error).toContain('pan merge void uat/min-dune-1128-3 --abandon-partial --reason <text>'); + expect(updates).toEqual([]); + expect(teardowns).toEqual([]); + expect(journal).toEqual([]); + }); + + it('PAN-5995: --abandon-partial journals first, and changes nothing when the journal cannot be written', async () => { + const { deps, updates, teardowns } = makeDeps(partialRow(), { journal: async () => { throw new Error('event store down'); } }); + + const result = await voidUatGeneration('uat/min-dune-1128-3', 'api MR closed', deps, { abandonPartial: true }); + + expect(result.status).toBe(503); + expect((result.body as { error: string }).error).toContain('was not abandoned'); + expect(updates).toEqual([]); + expect(teardowns).toEqual([]); + }); + + it('PAN-5995: --abandon-partial needs a reason', async () => { + const { deps, updates } = makeDeps(partialRow()); + + const result = await voidUatGeneration('uat/min-dune-1128-3', ' ', deps, { abandonPartial: true }); + + expect(result.status).toBe(400); + expect(updates).toEqual([]); + }); + + it('PAN-5995: --abandon-partial invalidates the batch, names what landed, journals it, and never touches the landed repos', async () => { + const { deps, updates, teardowns, journal } = makeDeps(partialRow()); + + const result = await voidUatGeneration('uat/min-dune-1128-3', 'the api MR was closed by hand', deps, { abandonPartial: true }); + + const statusReason = 'abandoned by the operator while partially promoted (landed: fe@m1; not landed: api): the api MR was closed by hand'; + expect(result).toEqual({ status: 200, body: { voided: 'uat/min-dune-1128-3', statusReason, stackTeardown: 'done', abandoned: true } }); + // Status and reason only: the repo rows, with fe's promoted_at and merge sha, are not rewritten. + expect(updates).toEqual([['uat/min-dune-1128-3', { status: 'invalidated', statusReason }]]); + expect(teardowns).toEqual(['uat/min-dune-1128-3']); + expect(journal[0]!.message).toBe('Operator abandoned partially promoted UAT batch uat/min-dune-1128-3'); + expect(journal[0]!.details).toContain('The landed repos keep their merges; nothing is reverted.'); + }); + it('keeps the void when the journal write fails', async () => { const { deps, updates } = makeDeps(gen('ready'), { journal: async () => { throw new Error('event store down'); } }); diff --git a/src/dashboard/server/services/__tests__/uat-promote-members.test.ts b/src/dashboard/server/services/__tests__/uat-promote-members.test.ts new file mode 100644 index 00000000000..938e8348610 --- /dev/null +++ b/src/dashboard/server/services/__tests__/uat-promote-members.test.ts @@ -0,0 +1,272 @@ +/** + * PAN-5995: resuming a partially promoted polyrepo batch. The member gate a + * normal promote uses refuses such a batch (its landed repo merged the + * members' PRs), so it is replaced by `resumeMemberStates`; these tests run + * that gate against the real `promoteUatGeneration` with fake git and forge + * listings, as a retry after a dashboard restart would (no in-process mark). + */ +import { describe, expect, it, vi } from 'vitest'; +import type { UatGeneration, UatGenerationRepo } from '../../../../lib/overdeck/merge-types.js'; +import type { GhPrRow } from '../../../../lib/overdeck/pr-listing.js'; +import { + promoteUatGeneration, + type PolyrepoRepoPromoteGit, + type UatPromoteDeps, +} from '../../../../lib/cloister/uat-promote.js'; +import { isUatGenerationPromoting } from '../../../../lib/cloister/uat-promote-inflight.js'; +import { resumeMemberStates, type ResumeGateDeps } from '../uat-promote-members.js'; +import type { DepartureEvidenceDeps, DepartureRepo } from '../uat-departure-evidence.js'; + +const NAME = 'uat/min-otter-1203'; +const REPOS: DepartureRepo[] = [ + { repoKey: 'fe', repoPath: '/myn/fe', forge: 'github' }, + { repoKey: 'api', repoPath: '/myn/api', forge: 'github' }, +]; + +function repoRow(repoKey: string, mergeOrder: number, overrides: Partial<UatGenerationRepo> = {}): UatGenerationRepo { + return { + repoKey, repoPath: `/myn/${repoKey}`, branch: NAME, baseSha: `${repoKey}-base`, targetBranch: 'main', + worktreePath: `/myn/workspaces/uat-min-otter-1203/${repoKey}`, mergeOrder, + headSha: `${repoKey}-uat-head`, promotedAt: null, mergeSha: null, ...overrides, + }; +} + +/** fe landed and was stamped before the restart; api is still pending. */ +function partialGeneration(): UatGeneration { + return { + name: NAME, worktreePath: '/myn/workspaces/uat-min-otter-1203', projectRoot: '/myn', + baseSha: 'fe@fe-base api@api-base', status: 'ready', + repos: [repoRow('fe', 0, { promotedAt: '2026-12-03T10:00:00.000Z', mergeSha: 'fe-merge' }), repoRow('api', 1)], + members: [ + { + issueId: 'MIN-1', title: 'One', branch: 'feature/min-1', headSha: 'fe@f1 api@a1', mergeOrder: 1, + repos: [ + { repoKey: 'fe', branch: 'feature/min-1', headSha: 'f1', mergeOrderInRepo: 0 }, + { repoKey: 'api', branch: 'feature/min-1', headSha: 'a1', mergeOrderInRepo: 0 }, + ], + }, + { + issueId: 'MIN-2', title: 'Two', branch: 'feature/min-2', headSha: 'fe@f2', mergeOrder: 2, + repos: [{ repoKey: 'fe', branch: 'feature/min-2', headSha: 'f2', mergeOrderInRepo: 1 }], + }, + ], + heldOut: [], resolutions: [], stackStartedAt: null, cleanedAt: null, + createdAt: '2026-12-03T09:00:00.000Z', updatedAt: '2026-12-03T10:00:00.000Z', + }; +} + +/** Open PR listings: fe's PRs merged with the landed batch; api's MIN-1 PR is open at the bundled head. */ +function listings(api: GhPrRow[] = [{ headRefName: 'feature/min-1', headRefOid: 'a1', reviewDecision: 'APPROVED' }]): DepartureEvidenceDeps { + return { + readOpenPullRequests: async (repoPath) => (repoPath === '/myn/api' ? api : []), + readMergeRequests: async () => [], + }; +} + +interface FakeGit extends PolyrepoRepoPromoteGit { trials: string[]; trialShas: Array<string | undefined>; published: string[] } + +function fakeGit(repoKey: string, options: { landed?: string | null; uatHead?: string | null } = {}): FakeGit { + const trials: string[] = []; + const trialShas: Array<string | undefined> = []; + const published: string[] = []; + return { + trials, trialShas, published, + targetHeadSha: async () => `${repoKey}-base`, + changedFilesSince: async () => [], + batchChangedFiles: async () => [], + trialMerge: async (branch, _message, sha) => { + trials.push(branch); + trialShas.push(sha); + return { repoKey, handle: `/wt/${repoKey}`, mergeSha: `${repoKey}-merge` }; + }, + publishPrepared: async (prepared) => { published.push(prepared.mergeSha); }, + discardPrepared: async () => {}, + findLandedMerge: async () => (options.landed === undefined ? null : options.landed), + uatBranchHead: async () => (options.uatHead === undefined ? `${repoKey}-uat-head` : options.uatHead), + }; +} + +const reviewedAsBundled = async () => null; + +async function resume( + gen: UatGeneration, + fe: FakeGit, + api: FakeGit, + deps: DepartureEvidenceDeps = listings(), + reviewedHeads: ResumeGateDeps['reviewedHeadsRefusal'] = reviewedAsBundled, +) { + // The gate probes the same fake git the promote uses. + const gitFor = new Map([['fe', fe], ['api', api]]); + const states = await resumeMemberStates(gen, REPOS, { + listings: deps, + reviewedHeadsRefusal: reviewedHeads, + landedMerge: (repo) => gitFor.get(repo.repoKey)!.findLandedMerge(repo.branch), + }); + const statuses: string[] = []; + const stamped: Array<[string, string | undefined]> = []; + const firePostMerge = vi.fn(() => true); + const promoteDeps: UatPromoteDeps = { + git: { + fetchMain: async () => { throw new Error('monorepo git must not run'); }, + mergeIntoMain: async () => { throw new Error('monorepo git must not run'); }, + changedFilesSince: async () => { throw new Error('monorepo git must not run'); }, + batchChangedFiles: async () => { throw new Error('monorepo git must not run'); }, + }, + polyrepoGit: new Map([['fe', fe], ['api', api]]), + markRepoPromoted: (_name, repoKey, _at, mergeSha) => { stamped.push([repoKey, mergeSha]); }, + now: () => new Date('2026-12-03T12:00:00.000Z'), + store: { + get: () => gen, + insert: () => {}, + update: (_name, patch) => { if (patch.status) statuses.push(patch.status); }, + listNames: () => [NAME], + listChain: () => [], + }, + teardownStack: async () => {}, + firePostMerge, + memberEligibility: (issueId) => states.get(issueId.toUpperCase()) ?? { eligible: false, reason: 'state could not be read' }, + }; + const result = await promoteUatGeneration(NAME, '/myn', promoteDeps); + return { states, result, statuses, stamped, firePostMerge }; +} + +describe('PAN-5995: resuming a partially promoted batch after a restart', () => { + it('lands the remaining repo, skips the landed one, and runs post-merge for every member', async () => { + const gen = partialGeneration(); + expect(isUatGenerationPromoting(NAME)).toBe(false); // a restart emptied the in-process set + const fe = fakeGit('fe', { landed: 'fe-merge' }); + const api = fakeGit('api'); + + const { states, result, statuses, stamped, firePostMerge } = await resume(gen, fe, api); + + expect(states.get('MIN-1')).toEqual({ eligible: true }); + // MIN-2 only touched fe, which already landed. + expect(states.get('MIN-2')).toEqual({ eligible: true }); + expect(result).toMatchObject({ success: true, members: ['MIN-1', 'MIN-2'] }); + expect(fe.trials).toEqual([]); + expect(fe.published).toEqual([]); + expect(api.published).toEqual(['api-merge']); + // The trial merge merges the head it verified, not whatever the ref names now. + expect(api.trialShas).toEqual(['api-uat-head']); + expect(stamped).toEqual([['api', 'api-merge']]); + expect(statuses).toContain('promoted'); + expect(firePostMerge.mock.calls.map((call) => call[0])).toEqual(['MIN-1', 'MIN-2']); + }); + + it('B1: a remaining repo that landed but was never stamped (crash between push and stamp) is recovered, and post-merge runs', async () => { + // api's push reached origin, then the dashboard died before the stamp. The + // forge closed MIN-1's api PR as merged, so the listing no longer shows it. + const fe = fakeGit('fe', { landed: 'fe-merge' }); + const api = fakeGit('api', { landed: 'api-landed' }); + + const { states, result, statuses, stamped, firePostMerge } = await resume(partialGeneration(), fe, api, listings([])); + + expect(states.get('MIN-1')).toEqual({ eligible: true }); + expect(result).toMatchObject({ success: true }); + expect(api.trials).toEqual([]); + expect(api.published).toEqual([]); + expect(stamped).toEqual([['api', 'api-landed']]); + expect(statuses).toContain('promoted'); + expect(firePostMerge.mock.calls.map((call) => call[0])).toEqual(['MIN-1', 'MIN-2']); + }); + + it('refuses when a remaining repo\'s uat branch moved since assembly, and leaves the batch untouched', async () => { + const fe = fakeGit('fe', { landed: 'fe-merge' }); + const api = fakeGit('api', { uatHead: 'api-pushed-later' }); + + const { result, statuses, stamped, firePostMerge } = await resume(partialGeneration(), fe, api); + + expect(result).toMatchObject({ success: false, reason: 'merge-failed' }); + expect((result as { message: string }).message).toContain('cannot be resumed: api (uat/min-otter-1203 moved from api-uat-h to api-pushe since assembly)'); + expect(api.trials).toEqual([]); + expect(api.published).toEqual([]); + expect(stamped).toEqual([]); + expect(statuses).toEqual([]); + expect(firePostMerge).not.toHaveBeenCalled(); + }); + + it('refuses when a remaining repo\'s uat branch is gone, or assembly recorded no head for it', async () => { + const gone = await resume(partialGeneration(), fakeGit('fe', { landed: 'fe-merge' }), fakeGit('api', { uatHead: null })); + expect((gone.result as { message: string }).message).toContain('uat/min-otter-1203 no longer exists on origin'); + + const legacy = partialGeneration(); + legacy.repos = [legacy.repos![0]!, repoRow('api', 1, { headSha: null })]; + const unrecorded = await resume(legacy, fakeGit('fe', { landed: 'fe-merge' }), fakeGit('api')); + expect((unrecorded.result as { message: string }).message).toContain('assembly recorded no uat head for it'); + expect(unrecorded.statuses).toEqual([]); + }); + + it('refuses when a repo stamped promoted is not actually merged on its target', async () => { + const api = fakeGit('api'); + const { result, statuses, firePostMerge } = await resume(partialGeneration(), fakeGit('fe', { landed: null }), api); + + expect(result).toMatchObject({ success: false, reason: 'merge-failed' }); + expect((result as { message: string }).message).toContain('its recorded uat head is not contained in main'); + expect(api.published).toEqual([]); + expect(statuses).toEqual([]); + expect(firePostMerge).not.toHaveBeenCalled(); + }); + + it('refuses a member whose PR in a pending repo closed, had changes requested, or moved; landed-only members stay cleared', async () => { + const cases: Array<[GhPrRow[], string]> = [ + [[], 'its PR or MR in api is no longer open, and api has not landed'], + [[{ headRefName: 'feature/min-1', headRefOid: 'a1', reviewDecision: 'CHANGES_REQUESTED' }], 'its PR or MR in api had changes requested'], + [[{ headRefName: 'feature/min-1', headRefOid: 'a9', reviewDecision: 'APPROVED' }], 'its branch in api moved since the batch was assembled'], + ]; + for (const [rows, why] of cases) { + const api = fakeGit('api'); + const { states, result, statuses } = await resume(partialGeneration(), fakeGit('fe', { landed: 'fe-merge' }), api, listings(rows)); + + expect(states.get('MIN-1')).toEqual({ eligible: false, reason: `cannot resume the promote: ${why}` }); + expect(states.get('MIN-2')).toEqual({ eligible: true }); + expect(result).toMatchObject({ success: false, reason: 'member-not-ready' }); + expect(api.published).toEqual([]); + expect(statuses).toEqual([]); + } + }); + + it('still lands pending work only at its reviewed heads; a landed-only member is not asked', async () => { + const asked: string[] = []; + const reviewedHeads = async (member: { issueId: string }) => { + asked.push(member.issueId); + return 'needs re-review: api moved after approval (the batch merged a1, the review approved a0)'; + }; + const api = fakeGit('api'); + const { states, result } = await resume(partialGeneration(), fakeGit('fe', { landed: 'fe-merge' }), api, listings(), reviewedHeads); + + expect(asked).toEqual(['MIN-1']); + expect(states.get('MIN-1')).toEqual({ + eligible: false, + reason: 'cannot resume the promote: needs re-review: api moved after approval (the batch merged a1, the review approved a0)', + }); + expect(states.get('MIN-2')).toEqual({ eligible: true }); + expect(result).toMatchObject({ success: false, reason: 'member-not-ready' }); + expect(api.published).toEqual([]); + }); + + it('cannot prove a closed-PR repo landed without the head assembly recorded, and points to --abandon-partial', async () => { + const legacy = partialGeneration(); + legacy.repos = [legacy.repos![0]!, repoRow('api', 1, { headSha: null })]; + const probed: string[] = []; + const states = await resumeMemberStates(legacy, REPOS, { + listings: listings([]), + reviewedHeadsRefusal: reviewedAsBundled, + landedMerge: async (repo) => { probed.push(repo.repoKey); return 'api-landed'; }, + }); + + expect(probed).toEqual([]); + expect(states.get('MIN-1')!.eligible).toBe(false); + expect(states.get('MIN-1')!.reason).toContain('whether it landed cannot be proven'); + expect(states.get('MIN-1')!.reason).toContain('--abandon-partial'); + }); + + it('refuses every member with the read error when a listing cannot be read', async () => { + const unreadable: DepartureEvidenceDeps = { readOpenPullRequests: async () => null, readMergeRequests: async () => null }; + const states = await resumeMemberStates(partialGeneration(), REPOS, { listings: unreadable, reviewedHeadsRefusal: reviewedAsBundled }); + + expect(states.get('MIN-1')).toEqual({ + eligible: false, + reason: 'state could not be read (the GitHub PR listing for /myn/api could not be read)', + }); + }); +}); diff --git a/src/dashboard/server/services/__tests__/uat-train.test.ts b/src/dashboard/server/services/__tests__/uat-train.test.ts index 3b3f5ed5bc5..3de67318771 100644 --- a/src/dashboard/server/services/__tests__/uat-train.test.ts +++ b/src/dashboard/server/services/__tests__/uat-train.test.ts @@ -325,6 +325,19 @@ describe('getUatGenerationsPayload', () => { ]); }); + it('says "partially promoted: resume promote" for a ready batch with a landed repo (PAN-5995)', async () => { + const landed = { repoKey: 'fe', repoPath: '/repos/myn/fe', branch: 'uat/pan-half-1203', baseSha: 'a', targetBranch: 'main', worktreePath: '/repos/myn/workspaces/uat-pan-half-1203/fe', mergeOrder: 0, promotedAt: '2026-12-03T10:00:00.000Z', mergeSha: 'm1' }; + const pending = { ...landed, repoKey: 'api', repoPath: '/repos/myn/api', mergeOrder: 1, promotedAt: null, mergeSha: null }; + mocks.listUatGenerations.mockReturnValue([ + { ...gen([]), name: 'uat/pan-half-1203', status: 'ready', repos: [landed, pending] } as UatGeneration, + ]); + mocks.findXBriefByIssue.mockReturnValue(Effect.succeed(null)); + + const payload = await getUatGenerationsPayload('/repos/myn'); + + expect(payload.map((p) => [p.name, p.statusReason])).toEqual([['uat/pan-half-1203', 'partially promoted: resume promote']]); + }); + it('scans 50 rows for the board and 10 rows otherwise (PAN-5364)', async () => { mocks.listUatGenerations.mockReturnValue([]); @@ -891,6 +904,31 @@ describe('postUatGenerationPromotePayload', () => { expect(eligibility?.('MIN-2')).toEqual({ eligible: false, reason: 'needs re-review: api moved after approval (the batch merged 333333333333, the review approved 111111111111)' }); }); + // PAN-5995: a partially promoted batch's members read as merged, so the + // normal gate would refuse its resume; the resume gate replaces it. + it('never asks the merge gate or the ready set for a partially promoted batch', async () => { + mocks.findProjectByPath.mockReturnValue({ name: 'myn', path: '/myn', workspace: { type: 'polyrepo', repos: [{ name: 'fe', path: 'fe' }] } }); + mocks.getUatGeneration.mockReturnValue({ + status: 'ready', + members: [{ issueId: 'MIN-1', repos: [{ repoKey: 'fe', branch: 'feature/min-1', headSha: 'f1', mergeOrderInRepo: 0 }] }], + repos: [{ repoKey: 'fe', branch: 'uat/min-dune-1203', promotedAt: '2026-12-03T10:00:00.000Z', mergeSha: 'm1' }], + }); + mocks.resolveProjectFromIssueSync.mockReturnValue({ projectKey: 'myn', projectName: 'MYN', projectPath: '/myn' }); + mocks.resolveProjectReposFromResolvedIssue.mockReturnValue([{ repoKey: 'fe', repoPath: '/myn/fe', required: true }]); + let eligibility: ((issueId: string) => { eligible: boolean; reason?: string }) | undefined; + mocks.promoteUatGeneration.mockImplementation(async (_name: string, _root: string, deps: { memberEligibility: typeof eligibility }) => { + eligibility = deps.memberEligibility; + return { success: false, reason: 'merge-failed', message: 'x' }; + }); + + await postUatGenerationPromotePayload('uat/min-dune-1203', vi.fn()); + + expect(mocks.evaluateIssueMergeGate).not.toHaveBeenCalled(); + expect(mocks.listReadyIssuesForProject).not.toHaveBeenCalled(); + // MIN-1 contributed only to fe, which already landed. + expect(eligibility?.('MIN-1')).toEqual({ eligible: true }); + }); + it('never asks a monorepo member for polyrepo reviewed heads', async () => { mocks.getUatGeneration.mockReturnValue({ status: 'ready', members: [{ issueId: 'PAN-1' }] }); mocks.evaluateIssueMergeGate.mockResolvedValue({ ready: true }); diff --git a/src/dashboard/server/services/uat-departure-evidence.ts b/src/dashboard/server/services/uat-departure-evidence.ts index a073dc83413..2ba948dda67 100644 --- a/src/dashboard/server/services/uat-departure-evidence.ts +++ b/src/dashboard/server/services/uat-departure-evidence.ts @@ -44,15 +44,23 @@ const defaultDeps: DepartureEvidenceDeps = { export const GITHUB_OPEN_LISTING_CAP = 100; /** The open PR/MR for one branch, normalized: head SHA and whether changes were requested. */ -interface OpenReview { headSha: string | null; changesRequested: boolean } +export interface OpenReview { headSha: string | null; changesRequested: boolean } -/** The open review, `null` when provably not open, or `'unknown'` when a truncated listing cannot say. */ -async function openReviewFor(repo: DepartureRepo, branch: string, deps: DepartureEvidenceDeps): Promise<OpenReview | null | 'unknown'> { +/** + * The open review, `null` when provably not open, or `'unknown'` when a truncated listing cannot say. + * PAN-5995: also the resumed-promote check for each pending repo (`uat-promote-members.ts`). + */ +export async function openReviewFor( + repo: DepartureRepo, + branch: string, + deps: DepartureEvidenceDeps = defaultDeps, +): Promise<OpenReview | null | 'unknown'> { if (repo.forge === 'gitlab') { const rows = await deps.readMergeRequests(repo.repoPath); if (rows === null) throw new Error(`the GitLab MR listing for ${repo.repoPath} could not be read`); const row = rows.find((r) => r.source_branch === branch && (r.state ?? '').toLowerCase() === 'opened'); - return row ? { headSha: row.sha ?? null, changesRequested: false } : null; + // PAN-5995: GitLab reports a reviewer's requested changes in the merge status. + return row ? { headSha: row.sha ?? null, changesRequested: row.detailed_merge_status === 'requested_changes' } : null; } const rows = await deps.readOpenPullRequests(repo.repoPath); if (rows === null) throw new Error(`the GitHub PR listing for ${repo.repoPath} could not be read`); @@ -62,7 +70,7 @@ async function openReviewFor(repo: DepartureRepo, branch: string, deps: Departur } /** Full or abbreviated SHAs name the same commit when one is a prefix of the other. */ -function sameCommit(a: string, b: string): boolean { +export function sameCommit(a: string, b: string): boolean { const x = a.toLowerCase(); const y = b.toLowerCase(); return x.startsWith(y) || y.startsWith(x); diff --git a/src/dashboard/server/services/uat-generation-void.ts b/src/dashboard/server/services/uat-generation-void.ts index a999ecf2729..1dd42c3ee41 100644 --- a/src/dashboard/server/services/uat-generation-void.ts +++ b/src/dashboard/server/services/uat-generation-void.ts @@ -15,12 +15,25 @@ * merge train is on or off. An `assembling` row is refused, because the * engine's own final write would overwrite the void, and so is a row a * promote is merging (`isUatGenerationPromoting`), whose final `promoted` - * write would. Voiding an already-invalidated row succeeds without writing - * anything (`alreadyVoided`), so a retry after a lost answer is safe. The + * write would. PAN-5995: a partially promoted row (a repo already landed, + * `isUatGenerationPartiallyPromoted`) is refused too, even after a restart; + * its promote is resumed, not voided. The operator's one other exit is + * `abandonPartial` (`pan merge void <gen> --abandon-partial --reason <text>`), + * which needs a reason: it journals which repos landed and which did not + * FIRST, refusing (503, nothing changed) when that write fails, then + * invalidates the row, keeps every landed repo's merge and `promoted_at` stamp, and + * lets cleanup reap the batch's `uat/*` branches and worktrees. It never + * touches a target branch. Voiding an already-invalidated row + * succeeds without writing anything (`alreadyVoided`), so a retry after a + * lost answer is safe. The * journal entry is written before the stack teardown, which can take minutes. */ import { emitActivityEntryDurable } from '../../../lib/activity-logger.js'; -import { isUatGenerationPromoting } from '../../../lib/cloister/uat-promote-inflight.js'; +import { + isUatGenerationPartiallyPromoted, + isUatGenerationPromoting, + PARTIALLY_PROMOTED_REASON, +} from '../../../lib/cloister/uat-promote-inflight.js'; import { teardownUatStack } from '../../../lib/cloister/uat-stack.js'; import { getUatGeneration, @@ -72,7 +85,7 @@ async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> { export interface VoidUatGenerationResult { status: number; body: - | { voided: string; statusReason: string; stackTeardown: 'done' | 'failed' | 'skipped'; alreadyVoided?: true } + | { voided: string; statusReason: string; stackTeardown: 'done' | 'failed' | 'skipped'; alreadyVoided?: true; abandoned?: true } | { error: string }; } @@ -80,6 +93,7 @@ export async function voidUatGeneration( name: string, reason: string, deps: VoidUatGenerationDeps = defaultDeps(), + options: { abandonPartial?: boolean } = {}, ): Promise<VoidUatGenerationResult> { const gen = deps.get(name); if (!gen) return { status: 404, body: { error: `No UAT generation named ${name}` } }; @@ -95,22 +109,58 @@ export async function voidUatGeneration( if (isUatGenerationPromoting(name)) { return { status: 409, body: { error: `${name} is being merged to main right now; it cannot be voided` } }; } + // PAN-5995: some repos already landed; a plain void would strand the rest. + const partial = isUatGenerationPartiallyPromoted(gen); + const trimmed = reason.trim(); + if (partial && !options.abandonPartial) { + return { + status: 409, + body: { + error: `${name} is ${PARTIALLY_PROMOTED_REASON}: some member repos already landed, so it cannot be voided. ` + + 'Resume the promote (Merge batch) to land the rest. If it cannot be resumed, abandon it with ' + + `\`pan merge void ${name} --abandon-partial --reason <text>\`: landed repos keep their merges.`, + }, + }; + } + if (partial && !trimmed) { + return { status: 400, body: { error: `abandoning partially promoted ${name} needs a reason (--reason <text>)` } }; + } if (!VOIDABLE.includes(gen.status)) { return { status: 409, body: { error: `${name} is already ${gen.status}; only a ready or superseded batch can be voided` } }; } - const trimmed = reason.trim(); - const statusReason = trimmed ? `voided by the operator: ${trimmed}` : 'voided by the operator'; + const landedKeys = (gen.repos ?? []).filter((r) => r.promotedAt).map((r) => `${r.repoKey}@${(r.mergeSha ?? 'landed').slice(0, 9)}`); + const pendingKeys = (gen.repos ?? []).filter((r) => !r.promotedAt).map((r) => r.repoKey); + const statusReason = partial + ? `abandoned by the operator while partially promoted (landed: ${landedKeys.join(', ')}; not landed: ${pendingKeys.join(', ') || 'none'}): ${trimmed}` + : trimmed ? `voided by the operator: ${trimmed}` : 'voided by the operator'; + const members = gen.members.map((m) => m.issueId).join(', ') || 'no members'; + if (partial) { + // PAN-5995: an abandon is journaled first, and refused if that write fails: + // it is the only record that the landed repos were left as they are. + try { + await deps.journal({ + message: `Operator abandoned partially promoted UAT batch ${name}`, + details: `${statusReason}. Was ${gen.status}; members: ${members}. The landed repos keep their merges; nothing is reverted. ` + + 'The next merge-train tick removes its uat-* worktrees and uat/* branches, and new batches may assemble again.', + }); + } catch (err) { + const why = err instanceof Error ? err.message : String(err); + deps.log(`[uat-void] ${name}: abandon refused, journal entry failed: ${why}`); + return { status: 503, body: { error: `${name} was not abandoned: the activity journal could not be written (${why}); nothing changed, retry once it is back` } }; + } + } deps.update(name, { status: 'invalidated', statusReason }); - deps.log(`[uat-void] ${name} voided (was ${gen.status}): ${statusReason}`); + deps.log(`[uat-void] ${name} ${partial ? 'abandoned' : 'voided'} (was ${gen.status}): ${statusReason}`); - const members = gen.members.map((m) => m.issueId).join(', ') || 'no members'; - await deps.journal({ - message: `Operator voided UAT batch ${name}`, - details: `${statusReason}. Was ${gen.status}; members: ${members}. The next merge-train tick removes its uat-* worktree and uat/* branches.`, - }).catch((err) => { - deps.log(`[uat-void] ${name}: journal entry failed: ${err instanceof Error ? err.message : String(err)}`); - }); + if (!partial) { + await deps.journal({ + message: `Operator voided UAT batch ${name}`, + details: `${statusReason}. Was ${gen.status}; members: ${members}. The next merge-train tick removes its uat-* worktree and uat/* branches.`, + }).catch((err) => { + deps.log(`[uat-void] ${name}: journal entry failed: ${err instanceof Error ? err.message : String(err)}`); + }); + } let stackTeardown: 'done' | 'failed' = 'done'; await withDeadline(deps.teardownStack(gen), VOID_TEARDOWN_DEADLINE_MS).catch((err) => { @@ -118,5 +168,5 @@ export async function voidUatGeneration( deps.log(`[uat-void] ${name}: stack teardown failed (cleanup retries it): ${err instanceof Error ? err.message : String(err)}`); }); - return { status: 200, body: { voided: name, statusReason, stackTeardown } }; + return { status: 200, body: { voided: name, statusReason, stackTeardown, ...(partial ? { abandoned: true as const } : {}) } }; } diff --git a/src/dashboard/server/services/uat-promote-members.ts b/src/dashboard/server/services/uat-promote-members.ts new file mode 100644 index 00000000000..9d8093886ac --- /dev/null +++ b/src/dashboard/server/services/uat-promote-members.ts @@ -0,0 +1,202 @@ +/** + * Who may land in a batch promote: the member answers `promoteUatGeneration`'s + * synchronous `memberEligibility` gate reads. Split out of uat-train.ts. + * + * A normal promote asks the merge gate for every member (PAN-3917 FR-9, + * PAN-5680), and for a polyrepo project also requires the member in the + * ready set (PAN-5641) at its reviewed heads (PAN-5786). + * + * PAN-5995: a partially promoted generation (a repo already stamped + * `promoted_at`) cannot pass that gate. Its landed repos merged the members' + * PRs and MRs there, so the members read as merged and leave the ready set. + * For such a generation, and only for it, the merge gate and the ready-set + * check are replaced: every member PR or MR in a repo still pending must be + * open, without changes requested, and at the head assembly bundled (or the + * repo already landed without its stamp), and the + * PAN-5786 reviewed-heads check still applies to a member with a pending repo + * (it reads review records, not the PR). The promote then confirms each landed + * repo's merge on its target and each pending repo's uat head + * (`uat-promote.ts`), and its trial merges check the targets, so any failure + * refuses with nothing published. + */ +import type { UatGeneration, UatGenerationRepo } from '../../../lib/overdeck/merge-types.js'; +import type { ProjectConfig } from '../../../lib/projects.js'; +import { evaluateIssueMergeGate } from '../../../lib/cloister/merge-gate.js'; +import { buildPolyrepoUatPromoteGitDeps } from '../../../lib/cloister/uat-promote.js'; +import { ABANDON_HINT } from '../../../lib/cloister/uat-promote-resume.js'; +import { isUatGenerationPartiallyPromoted } from '../../../lib/cloister/uat-promote-inflight.js'; +import { memberReposForProject } from '../../../lib/overdeck/ready-set.js'; +import { listReadyIssuesForProject } from './derived-issue-state.js'; +import { memberReviewedHeadsRefusal } from './uat-reviewed-heads.js'; +import { openReviewFor, sameCommit, type DepartureEvidenceDeps, type DepartureRepo } from './uat-departure-evidence.js'; + +/** + * PAN-5680: how long a batch merge waits for its members' merge-gate reads + * before it refuses. The gate makes several forge reads per member (listing, + * MR view, approvals, a 3 s mergeability re-read), each with its own 30 s + * limit; one deadline bounds the click as a whole. + */ +export const PROMOTE_MEMBER_READ_DEADLINE_MS = 60_000; + +export interface MemberState { eligible: boolean; reason?: string } + +/** The work's answer, or a rejection once `ms` passes without one. */ +async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> { + let timer: ReturnType<typeof setTimeout> | undefined; + const deadline = new Promise<never>((_, reject) => { + timer = setTimeout(() => reject(new Error(`the forge reads did not answer within ${Math.round(ms / 1000)} s`)), ms); + }); + try { + return await Promise.race([work, deadline]); + } finally { + clearTimeout(timer); + } +} + +const unreadable = (error: unknown): MemberState => ({ + eligible: false, + reason: `state could not be read (${error instanceof Error ? error.message : String(error)})`, +}); + +/** Each member's answer, keyed by upper-cased issue id. */ +export async function readPromoteMemberStates( + current: UatGeneration, + root: string, + projectConfig: ProjectConfig | null | undefined, +): Promise<Map<string, MemberState>> { + if (isUatGenerationPartiallyPromoted(current)) { + const ids = current.members.map((m) => m.issueId.toUpperCase()); + try { + if (!projectConfig) throw new Error('the project config could not be found'); + const repos = memberReposForProject(root, projectConfig) + .map((r) => ({ repoKey: r.repoKey, repoPath: r.repoPath, forge: r.forge })); + const repoGit = buildPolyrepoUatPromoteGitDeps(current.repos ?? []); + const landedMerge = async (repo: UatGenerationRepo) => + (repo.headSha ? repoGit.get(repo.repoKey)?.findLandedMerge(repo.branch, repo.headSha) : null) ?? null; + return await withDeadline(resumeMemberStates(current, repos, { landedMerge }), PROMOTE_MEMBER_READ_DEADLINE_MS); + } catch (error) { + return new Map(ids.map((id) => [id, unreadable(error)])); + } + } + + // PAN-3917 FR-9: a member may land only if its own PR is still ready — + // approved, green, mergeable. `uat-promote`'s gate is synchronous, so the + // answers are read up front and the closure reads them. + // + // PAN-5680: the answer is the merge gate's own verdict. It used to be the + // derived state, which reads only the forge listing: a GitLab listing row + // carries no pipeline and no approval, and a polyrepo root is not a repo, + // so no MYN member could ever derive `ready`. The gate reads each MR's view, + // approvals and member CI. All the reads share one deadline, so a slow or + // rate-limited forge refuses with a reason instead of holding the click. + // + // The gate judges one MR per issue. A polyrepo issue has one per member + // repo, so a polyrepo member must also still be in the ready set, which + // requires every one of its member PRs and MRs to be ready (PAN-5641). + const polyrepo = projectConfig?.workspace?.type === 'polyrepo'; + const readyIds = polyrepo + ? withDeadline(listReadyIssuesForProject(root), PROMOTE_MEMBER_READ_DEADLINE_MS) + .then((ready) => new Set(ready.map((issue) => issue.issueId.toUpperCase()))) + : null; + // Read once for every member below; a rejection is handled there. + readyIds?.catch(() => {}); + const memberStates = new Map<string, MemberState>(); + await Promise.all(current.members.map(async (member) => { + const issueId = member.issueId.toUpperCase(); + try { + const gate = await withDeadline(evaluateIssueMergeGate(issueId), PROMOTE_MEMBER_READ_DEADLINE_MS); + if (!gate.ready) { + memberStates.set(issueId, { eligible: false, reason: `is not ready to merge: ${gate.reason ?? 'the merge gate gave no reason'}` }); + return; + } + // PAN-5786: and only at the heads its review approved. + const moved = polyrepo ? await memberReviewedHeadsRefusal(member) : null; + memberStates.set(issueId, readyIds && !(await readyIds).has(issueId) + ? { eligible: false, reason: 'is not ready to merge: one of its member-repo PRs or MRs is not ready' } + : moved ? { eligible: false, reason: moved } : { eligible: true }); + } catch (error) { + memberStates.set(issueId, unreadable(error)); + } + })); + return memberStates; +} + +export interface ResumeGateDeps { + /** The open PR / MR listings (the train-off departure evidence's reader). */ + listings?: DepartureEvidenceDeps; + /** PAN-5786's reviewed-heads check. */ + reviewedHeadsRefusal?: typeof memberReviewedHeadsRefusal; + /** + * The merge that already brought this repo's recorded uat head into its + * target, or null (`findLandedMerge`). Asked only for a repo with a recorded + * head. Omitted = nothing counts as landed. + */ + landedMerge?: (repo: UatGenerationRepo) => Promise<string | null>; +} + +/** + * PAN-5995: the gate for a partially promoted generation. A member is cleared + * when, in every repo still pending, its PR or MR is open, has no changes + * requested, and is at the head the generation bundled, or when that repo + * already landed without its stamp (a push the remote accepted before a crash + * or a timeout): the forge then reads the PR as merged, and the promote's + * recovery stamps the repo before anything else runs. A member that only + * contributed to landed repos is cleared: its work already merged there. + */ +export async function resumeMemberStates( + gen: UatGeneration, + repos: readonly DepartureRepo[], + deps: ResumeGateDeps = {}, +): Promise<Map<string, MemberState>> { + const reviewedHeadsRefusal = deps.reviewedHeadsRefusal ?? memberReviewedHeadsRefusal; + const pending = new Map((gen.repos ?? []).filter((r) => !r.promotedAt).map((r) => [r.repoKey, r])); + const byKey = new Map(repos.map((r) => [r.repoKey, r])); + // One landed-merge probe per repo, shared by every member that needs it. + const landed = new Map<string, Promise<string | null>>(); + const hasLanded = (repo: UatGenerationRepo) => { + if (!deps.landedMerge) return Promise.resolve(null); + let probe = landed.get(repo.repoKey); + if (!probe) { probe = deps.landedMerge(repo); landed.set(repo.repoKey, probe); } + return probe; + }; + const states = new Map<string, MemberState>(); + for (const member of gen.members) { + const issueId = member.issueId.toUpperCase(); + const refuse = (why: string) => states.set(issueId, { eligible: false, reason: `cannot resume the promote: ${why}` }); + if ((member.repos ?? []).length === 0) { + refuse('the generation recorded no per-repo branches for it'); + continue; + } + try { + let refused = false; + let stillToLand = 0; + for (const contribution of (member.repos ?? []).filter((r) => pending.has(r.repoKey))) { + const key = contribution.repoKey; + const repo = byKey.get(key); + const review = repo ? await openReviewFor(repo, contribution.branch, deps.listings) : undefined; + // B1: a PR the forge closed because its repo landed is not a departure. + // Landed is proven only at the uat head assembly recorded. + const pendingRepo = pending.get(key)!; + if (review === null && pendingRepo.headSha && await hasLanded(pendingRepo)) continue; + const why = review === undefined ? `${key} is not a configured member repo` + : review === null && !pendingRepo.headSha + ? `its PR or MR in ${key} is no longer open, and assembly recorded no uat head for ${key}, so whether it landed cannot be proven; ${ABANDON_HINT}` + : review === 'unknown' ? `its PR in ${key} is missing from a truncated listing, so it cannot be confirmed open` + : review === null ? `its PR or MR in ${key} is no longer open, and ${key} has not landed` + : review.changesRequested ? `its PR or MR in ${key} had changes requested` + : review.headSha && !sameCommit(review.headSha, contribution.headSha) + ? `its branch in ${key} moved since the batch was assembled` + : null; + if (why) { refuse(why); refused = true; break; } + stillToLand += 1; + } + // PAN-5786: work still to land lands only at the heads its review approved. + const moved = !refused && stillToLand > 0 ? await reviewedHeadsRefusal(member) : null; + if (moved) refuse(moved); + else if (!refused) states.set(issueId, { eligible: true }); + } catch (error) { + states.set(issueId, unreadable(error)); + } + } + return states; +} diff --git a/src/dashboard/server/services/uat-train.ts b/src/dashboard/server/services/uat-train.ts index 842e5cda4cb..b32291b9118 100644 --- a/src/dashboard/server/services/uat-train.ts +++ b/src/dashboard/server/services/uat-train.ts @@ -40,9 +40,11 @@ import { import type { BaseMove } from '../../../lib/cloister/bookkeeping-paths.js'; import { buildConflictAgentHook } from '../../../lib/cloister/uat-conflict-agent.js'; import { reconcileUatGenerations, type ReconcileResult } from '../../../lib/cloister/uat-reconciler.js'; +import { isUatGenerationPartiallyPromoted, PARTIALLY_PROMOTED_REASON } from '../../../lib/cloister/uat-promote-inflight.js'; import { mergePathOwner } from './merge-path-owner.js'; import { ensureLegacyReviewImport } from '../../../lib/cloister/review-records-legacy-import.js'; -import { keepPinnedFeatures, memberReviewedHeadsRefusal, pinReadySetToReviewedHeads, reportDroppedMember } from './uat-reviewed-heads.js'; +import { keepPinnedFeatures, pinReadySetToReviewedHeads, reportDroppedMember } from './uat-reviewed-heads.js'; +import { readPromoteMemberStates } from './uat-promote-members.js'; import { batchWindowAppliesToProject, buildSelectBatch, @@ -73,7 +75,6 @@ import { import { forgeForProject, listReadyIssuesForProject, mergedIssueIdsForProject, ReadySetUnavailableError } from './derived-issue-state.js'; import { readOpenRepoPullRequests } from '../../../lib/overdeck/pr-listing.js'; import { MERGE_QUEUE_DEADLINE_MS, orderPolyrepoQueue, PolyrepoRefsUnavailableError, resolveReposForIssue } from './polyrepo-queue.js'; -import { evaluateIssueMergeGate } from '../../../lib/cloister/merge-gate.js'; import { extractACFromDocument } from '../../../lib/xbrief/acceptance-criteria.js'; import { findXBriefByIssue, invalidateXBriefIndex, readXBriefDocument } from '../../../lib/xbrief/xbrief-index.js'; import { findProjectByPath, listProjectsSync } from '../../../lib/projects.js'; @@ -600,7 +601,7 @@ export interface UatGenerationPayload { * whether version sync is configured for the project. */ shipStatus: null; - /** PAN-4753 WI-3: why the batch became superseded or invalidated; null otherwise. */ + /** PAN-4753 WI-3: why the batch became superseded or invalidated, or PAN-5995 `partially promoted: resume promote`; null otherwise. */ statusReason: string | null; /** PAN-5364: the batch whose merge voided this one (invalidated only); null otherwise. */ voidedBy: string | null; @@ -791,7 +792,9 @@ export async function getUatGenerationsPayload( versionSyncConfigured, shipStatus: null, // A reason only explains a voided or replaced batch; a later promote keeps the column. - statusReason: gen.status === 'superseded' || gen.status === 'invalidated' ? gen.statusReason ?? null : null, + // PAN-5995: a half-landed batch says so, so the operator retries the promote. + statusReason: isUatGenerationPartiallyPromoted(gen) ? PARTIALLY_PROMOTED_REASON + : gen.status === 'superseded' || gen.status === 'invalidated' ? gen.statusReason ?? null : null, voidedBy: gen.status === 'invalidated' ? gen.voidedBy ?? null : null, repos: (gen.repos ?? []).map((r) => ({ repoKey: r.repoKey, @@ -848,26 +851,7 @@ export async function postUatGenerationStackPayload(name: string): Promise< return { ok: true, frontendUrl: result.frontendUrl!, evicted: result.evicted }; } -/** - * PAN-5680: how long a batch merge waits for its members' merge-gate reads - * before it refuses. The gate makes several forge reads per member (listing, - * MR view, approvals, a 3 s mergeability re-read), each with its own 30 s - * limit; one deadline bounds the click as a whole. - */ -export const PROMOTE_MEMBER_READ_DEADLINE_MS = 60_000; - -/** The work's answer, or a rejection once `ms` passes without one. */ -async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> { - let timer: ReturnType<typeof setTimeout> | undefined; - const deadline = new Promise<never>((_, reject) => { - timer = setTimeout(() => reject(new Error(`the forge reads did not answer within ${Math.round(ms / 1000)} s`)), ms); - }); - try { - return await Promise.race([work, deadline]); - } finally { - clearTimeout(timer); - } -} +export { PROMOTE_MEMBER_READ_DEADLINE_MS } from './uat-promote-members.js'; export async function postUatGenerationPromotePayload( name: string, @@ -901,48 +885,9 @@ export async function postUatGenerationPromotePayload( // member's record. The merge itself is the evidence — the generation's own // rows carry the merge sha, and readiness is re-derived from each PR. - // PAN-3917 FR-9: a member may land only if its own PR is still ready — - // approved, green, mergeable. `uat-promote`'s gate is synchronous, so the - // answers are read up front and the closure reads them. - // - // PAN-5680: the answer is the merge gate's own verdict. It used to be the - // derived state, which reads only the forge listing: a GitLab listing row - // carries no pipeline and no approval, and a polyrepo root is not a repo, - // so no MYN member could ever derive `ready`. The gate reads each MR's view, - // approvals and member CI. All the reads share one deadline, so a slow or - // rate-limited forge refuses with a reason instead of holding the click. - // - // The gate judges one MR per issue. A polyrepo issue has one per member - // repo, so a polyrepo member must also still be in the ready set, which - // requires every one of its member PRs and MRs to be ready (PAN-5641). const polyrepo = projectConfig?.workspace?.type === 'polyrepo'; - const readyIds = polyrepo - ? withDeadline(listReadyIssuesForProject(root), PROMOTE_MEMBER_READ_DEADLINE_MS) - .then((ready) => new Set(ready.map((issue) => issue.issueId.toUpperCase()))) - : null; - // Read once for every member below; a rejection is handled there. - readyIds?.catch(() => {}); - const memberStates = new Map<string, { eligible: boolean; reason?: string }>(); - await Promise.all(current.members.map(async (member) => { - const issueId = member.issueId.toUpperCase(); - try { - const gate = await withDeadline(evaluateIssueMergeGate(issueId), PROMOTE_MEMBER_READ_DEADLINE_MS); - if (!gate.ready) { - memberStates.set(issueId, { eligible: false, reason: `is not ready to merge: ${gate.reason ?? 'the merge gate gave no reason'}` }); - return; - } - // PAN-5786: and only at the heads its review approved. - const moved = polyrepo ? await memberReviewedHeadsRefusal(member) : null; - memberStates.set(issueId, readyIds && !(await readyIds).has(issueId) - ? { eligible: false, reason: 'is not ready to merge: one of its member-repo PRs or MRs is not ready' } - : moved ? { eligible: false, reason: moved } : { eligible: true }); - } catch (error) { - memberStates.set(issueId, { - eligible: false, - reason: `state could not be read (${error instanceof Error ? error.message : String(error)})`, - }); - } - })); + // PAN-3917 FR-9, PAN-5680, PAN-5995: who may land (`uat-promote-members.ts`). + const memberStates = await readPromoteMemberStates(current, root, projectConfig); // A polyrepo generation merges into each member repo's own target branch, so // it needs per-repo promote git. Supplying it is what selects the two-phase // (trial-merge everything, then publish) path. diff --git a/src/lib/cloister/uat-generation-deps.ts b/src/lib/cloister/uat-generation-deps.ts index ebe3cdf7211..6d61c04bcb1 100644 --- a/src/lib/cloister/uat-generation-deps.ts +++ b/src/lib/cloister/uat-generation-deps.ts @@ -42,9 +42,14 @@ export const CLEANUP_GIT_TIMEOUT_MS = 60_000; const runCleanupGit = (args: string[], cwd: string) => execFileAsync('git', args, { cwd, maxBuffer: 16 * 1024 * 1024, timeout: CLEANUP_GIT_TIMEOUT_MS, env: { ...process.env, LC_ALL: 'C' } }); -/** What git prints when the thing a cleanup step removes is already gone. */ -const ALREADY_GONE = { - worktree: /is not a working tree|No such file or directory|does not exist/i, +/** + * What git prints when the thing a cleanup step removes is already gone. + * PAN-5995: `worktree` is git's exact LC_ALL=C line for a path that is not a + * registered worktree (`fatal: '<path>' is not a working tree`), so any other + * failure that merely mentions a missing file still rejects. + */ +export const ALREADY_GONE = { + worktree: /^fatal: '.*' is not a working tree$/m, localBranch: /branch '.*' not found/i, remoteBranch: /remote ref does not exist/i, } as const; @@ -414,6 +419,11 @@ export async function listRemoteUatBranches(projectRoot: string): Promise<string .map((ref) => ref.slice('refs/heads/'.length)); } +/** PAN-5995: a residue-sweep repo key is one plain path segment: no `/`, no `\`, no `..`, not empty. */ +export function isSafeResidueRepoKey(repoKey: string): boolean { + return repoKey !== '' && !/[/\\]/.test(repoKey) && !repoKey.includes('..'); +} + /** * Polyrepo cleanup deps (PAN-3093). Each member repo owns its own worktree and * branch, and the wrapper folder holds them all. @@ -472,8 +482,15 @@ export function buildPolyrepoCleanupGit( // deleted the branch for every recorded repo, and repeating it costs a // full remote handshake per repo before its expected failure. const recorded = new Set(recordedRepoKeys); - for (const repo of writable) { - if (recorded.has(repo.repoKey)) continue; + const swept = writable.filter((repo) => !recorded.has(repo.repoKey)); + // PAN-5995: a repo key names a folder inside the generation folder. A key + // such as `../uat-other` would still pass the uat-* path check and reach + // a sibling generation, so refuse the sweep before any git call. + const unsafe = swept.filter((repo) => !isSafeResidueRepoKey(repo.repoKey)); + if (unsafe.length > 0) { + throw new Error(`[uat-cleanup] refusing residue sweep: unsafe repo key(s): ${unsafe.map((r) => JSON.stringify(r.repoKey)).join(', ')}`); + } + for (const repo of swept) { // A failed assembly can leave an unrecorded worktree with the branch // checked out; remove it first, or `branch -D` fails every tick. const leftover = safeGenerationWorktreePath(projectPath, `${generation.worktreePath}/${repo.repoKey}`); diff --git a/src/lib/cloister/uat-generation-engine.ts b/src/lib/cloister/uat-generation-engine.ts index 145729991bd..4c22465b055 100644 --- a/src/lib/cloister/uat-generation-engine.ts +++ b/src/lib/cloister/uat-generation-engine.ts @@ -18,7 +18,7 @@ */ import type { BaseMove } from './bookkeeping-paths.js'; import { makeUniqueUatCandidateName } from './uat-candidate-name.js'; -import { isUatGenerationPromoting } from './uat-promote-inflight.js'; +import { isUatGenerationPartiallyPromoted, isUatGenerationPromoting } from './uat-promote-inflight.js'; import { applyUnionLintPlan, planUnionLint, @@ -127,7 +127,7 @@ export interface GenerationStorePort { name: string, // 'repos' is written only by the polyrepo engine; the monorepo path never // sets it, so its generations keep reading back as a synthesized N=1 entry. - patch: Partial<Pick<UatGeneration, 'status' | 'baseSha' | 'members' | 'heldOut' | 'resolutions' | 'cleanedAt' | 'repos' | 'statusReason' | 'voidedBy'>>, + patch: Partial<Pick<UatGeneration, 'status' | 'baseSha' | 'members' | 'heldOut' | 'resolutions' | 'cleanedAt' | 'repos' | 'statusReason' | 'voidedBy' | 'cleanupAttempts' | 'cleanupNextAttemptAt'>>, ): void; /** Existing generation names. */ listNames(): string[]; @@ -369,8 +369,11 @@ export async function assembleUatGeneration( // This generation is now the current one; older ready generations remain // testable but are no longer the freshest — flip them to superseded. + // PAN-5995: never a partially promoted one; its promote must stay resumable. for (const older of deps.store.listChain(input.projectRoot, ['ready'])) { - if (older.name !== name) deps.store.update(older.name, { status: 'superseded', statusReason: `replaced by ${name}` }); + if (older.name !== name && !isUatGenerationPartiallyPromoted(older)) { + deps.store.update(older.name, { status: 'superseded', statusReason: `replaced by ${name}` }); + } } log(`[uat-generation] ${name}: ready — ${members.length} member(s), ${resolutions.length} resolution(s), ${heldOut.length} held out`); @@ -446,9 +449,25 @@ export const CLEANABLE_STATUSES: readonly UatGenerationStatus[] = ['superseded', */ export const SUPERSEDED_REAP_AFTER_MS = 24 * 60 * 60 * 1000; +/** PAN-5995: the wait after the first failed cleanup; it doubles per failure. */ +export const CLEANUP_BACKOFF_BASE_MS = 60_000; +/** PAN-5995: the longest wait between cleanup attempts. */ +export const CLEANUP_BACKOFF_MAX_MS = 60 * 60_000; + +/** Wait after the `attempts`-th consecutive failed cleanup: 1, 2, 4 … minutes, capped at 1 hour. */ +export function cleanupBackoffMs(attempts: number): number { + const exponent = Math.min(Math.max(attempts - 1, 0), 30); + return Math.min(CLEANUP_BACKOFF_BASE_MS * 2 ** exponent, CLEANUP_BACKOFF_MAX_MS); +} + function reapable(gen: UatGeneration, now: number): boolean { if (!CLEANABLE_STATUSES.includes(gen.status) || gen.cleanedAt) return false; if (isUatGenerationPromoting(gen.name)) return false; + // PAN-5995: a half-landed batch keeps its branches; the retried promote needs them. + if (isUatGenerationPartiallyPromoted(gen)) return false; + // PAN-5995: a failed cleanup waits out its backoff. + const retryAt = Date.parse(gen.cleanupNextAttemptAt || ''); + if (Number.isFinite(retryAt) && now < retryAt) return false; if (gen.status !== 'superseded') return true; if (gen.stackStartedAt) return false; const supersededAt = Date.parse(gen.updatedAt || ''); @@ -463,7 +482,9 @@ function reapable(gen: UatGeneration, now: number): boolean { * never merge, so once its grace period passes with no stack running * ({@link SUPERSEDED_REAP_AFTER_MS}) it is reaped and flips to 'invalidated', * keeping why it was replaced. Any artifact removal that fails leaves - * `cleanedAt` unset, so the next tick retries. Rows are + * `cleanedAt` unset and, PAN-5995, backs the generation off: 1 minute after + * the first failure, doubling per failure, capped at 1 hour + * ({@link cleanupBackoffMs}). A success clears the backoff. Rows are * never deleted: the chain is the audit trail. Promoted generations keep * their row but lose branch/worktree/stack — their content lives on main now. */ @@ -477,6 +498,15 @@ export async function cleanupUatGenerations( const terminal = deps.store.listChain(projectRoot, [...CLEANABLE_STATUSES]) .filter((gen) => reapable(gen, now)); + const backOff = (gen: UatGeneration) => { + const attempts = (gen.cleanupAttempts ?? 0) + 1; + const wait = cleanupBackoffMs(attempts); + // Measured from the failure, not the tick start: a slow failure still waits the full delay. + const failedAt = (deps.now ?? Date.now)(); + deps.store.update(gen.name, { cleanupAttempts: attempts, cleanupNextAttemptAt: new Date(failedAt + wait).toISOString() }); + log(`[uat-generation] cleanup ${gen.name}: attempt ${attempts} failed; next try in ${Math.round(wait / 60_000)}m`); + }; + for (const gen of terminal) { let cleaned = true; if (gen.stackStartedAt && deps.teardownStack) { @@ -485,7 +515,10 @@ export async function cleanupUatGenerations( log(`[uat-generation] cleanup ${gen.name}: stack teardown failed: ${err instanceof Error ? err.message : String(err)}`); }); // PAN-5966: never pull the worktree out from under a compose down still running. - if (!cleaned) continue; + if (!cleaned) { + backOff(gen); + continue; + } } if (deps.removeRepoArtifacts) { // Polyrepo: one worktree and one branch per member repo, then the wrapper @@ -511,15 +544,21 @@ export async function cleanupUatGenerations( log(`[uat-generation] cleanup ${gen.name}: branch deletion failed: ${err instanceof Error ? err.message : String(err)}`); }); } - if (!cleaned) continue; + if (!cleaned) { + backOff(gen); + continue; + } const cleanedAt = new Date().toISOString(); + const cleared = gen.cleanupAttempts || gen.cleanupNextAttemptAt + ? { cleanupAttempts: null, cleanupNextAttemptAt: null } + : {}; if (gen.status === 'superseded') { const reaped = 'cleaned up: a superseded batch can no longer merge'; // Keep why the batch was replaced; the cleanup only adds to it. - deps.store.update(gen.name, { status: 'invalidated', cleanedAt, statusReason: gen.statusReason ? `${gen.statusReason}; ${reaped}` : reaped }); + deps.store.update(gen.name, { status: 'invalidated', cleanedAt, ...cleared, statusReason: gen.statusReason ? `${gen.statusReason}; ${reaped}` : reaped }); log(`[uat-generation] cleanup: reaped superseded ${gen.name}`); } else { - deps.store.update(gen.name, { cleanedAt }); + deps.store.update(gen.name, { cleanedAt, ...cleared }); } } } diff --git a/src/lib/cloister/uat-polyrepo-engine.ts b/src/lib/cloister/uat-polyrepo-engine.ts index 3fb654dc1d3..082e8fac442 100644 --- a/src/lib/cloister/uat-polyrepo-engine.ts +++ b/src/lib/cloister/uat-polyrepo-engine.ts @@ -25,6 +25,7 @@ import { makeUniqueUatCandidateName } from './uat-candidate-name.js'; import { generationFolderName } from './uat-generation-engine.js'; +import { isUatGenerationPartiallyPromoted } from './uat-promote-inflight.js'; import { applyUnionLintPlan, planUnionLint, @@ -337,7 +338,13 @@ export async function assemblePolyrepoUatGeneration( if (abandoned.length > 0) { log(`[uat-polyrepo] ${name}: repo(s) ${abandoned.map((r) => r.repoKey).join(', ')} lost every contribution to a hold-out — no branch published; local worktree reaped with the generation folder`); } - const publishedRepos = pass.repos.filter((r) => carrying.has(r.repoKey)); + // PAN-5995: each published repo records the uat head it pushes, so a + // resumed promote can refuse a uat branch that moved since assembly. + const publishedRepos: UatGenerationRepo[] = []; + for (const repo of pass.repos.filter((r) => carrying.has(r.repoKey))) { + const headSha = await deps.repoGit.get(repo.repoKey)!.generationHeadSha().catch(() => null); + publishedRepos.push({ ...repo, headSha }); + } const { members, resolutions } = collectMembers(input.features, heldOutIds, pass.mergedByIssue); @@ -361,8 +368,11 @@ export async function assemblePolyrepoUatGeneration( } } + // PAN-5995: never a partially promoted one; its promote must stay resumable. for (const older of deps.store.listChain(input.projectRoot, ['ready'])) { - if (older.name !== name) deps.store.update(older.name, { status: 'superseded', statusReason: `replaced by ${name}` }); + if (older.name !== name && !isUatGenerationPartiallyPromoted(older)) { + deps.store.update(older.name, { status: 'superseded', statusReason: `replaced by ${name}` }); + } } log(`[uat-polyrepo] ${name}: ready — ${members.length} member(s) across ${publishedRepos.length} repo(s), ${resolutions.length} resolution(s), ${heldOut.length} held out`); diff --git a/src/lib/cloister/uat-promote-inflight.ts b/src/lib/cloister/uat-promote-inflight.ts index 2663cbaa741..d4a547885ff 100644 --- a/src/lib/cloister/uat-promote-inflight.ts +++ b/src/lib/cloister/uat-promote-inflight.ts @@ -1,7 +1,7 @@ /** * PAN-5966: the UAT generations a promote is merging right now, in this * process. Promote, the reconciler, cleanup and the void verb all run in the - * dashboard server, so an in-process set is enough to keep them apart: + * dashboard server, so an in-process set keeps them apart while a promote runs: * * - `promoteUatGeneration` marks the generation for its whole run; * - the reconciler neither stamps nor invalidates a marked generation, so a @@ -10,8 +10,17 @@ * - void refuses a marked generation, so promote's final `promoted` write can * never overwrite a void. * - * A leaf module (no imports) so every one of those can import it without a cycle. + * PAN-5995: the set does not survive a restart, so the same four sites also + * honor the durable record, {@link isUatGenerationPartiallyPromoted}: a + * generation with a repo stamped `promoted_at` but not finalized is never + * invalidated, superseded, voided or reaped. The retried promote finishes it, + * skipping every repo already stamped. The one exit besides finishing is the + * operator's `pan merge void <gen> --abandon-partial --reason <text>`. + * + * A leaf module (type-only imports) so every one of those can import it without a cycle. */ +import type { UatGeneration } from '../overdeck/merge-types.js'; + const promoting = new Set<string>(); export function isUatGenerationPromoting(name: string): boolean { @@ -28,3 +37,24 @@ export async function withUatGenerationPromoting<T>(name: string, work: () => Pr promoting.delete(name); } } + +/** PAN-5995: what the board and the reconciler log say about a partially promoted generation. */ +export const PARTIALLY_PROMOTED_REASON = 'partially promoted: resume promote'; + +/** + * PAN-5995: a promote published at least one member repo (`promoted_at` is + * stamped) but never wrote the final `promoted` status. That covers both a + * promote cut off between repos and one cut off after its last repo but before + * finalizing. The stamps are durable, so this holds across a restart that + * empties the in-process promoting set. Only polyrepo generations persist + * per-repo stamps; a monorepo generation is never partially promoted. + * + * An `invalidated` row is not: every writer refuses to invalidate a partially + * promoted row, so the only way one becomes `invalidated` is the operator's + * `--abandon-partial`. Abandoned, it is terminal: the assembly hold lifts, + * cleanup reaps its `uat/*` branches and worktrees, and its `promoted_at` + * stamps stay as the record of what landed. + */ +export function isUatGenerationPartiallyPromoted(gen: Pick<UatGeneration, 'status' | 'repos'>): boolean { + return gen.status !== 'promoted' && gen.status !== 'invalidated' && (gen.repos ?? []).some((repo) => !!repo.promotedAt); +} diff --git a/src/lib/cloister/uat-promote-resume.ts b/src/lib/cloister/uat-promote-resume.ts new file mode 100644 index 00000000000..ec84d5d3d35 --- /dev/null +++ b/src/lib/cloister/uat-promote-resume.ts @@ -0,0 +1,60 @@ +/** + * PAN-5995: the git checks a resumed polyrepo promote makes before it lands + * anything. A partially promoted generation has repos stamped `promoted_at` + * and repos still pending. Before the promote skips the first and lands the + * second, it confirms: + * + * - each stamped repo really merged on its target ({@link landedStampRefusal}); + * - each pending repo's uat branch is still at the head assembly pushed + * ({@link movedUatHeads}), so only the tested tree lands. + * + * Split out of uat-promote.ts. Structural git types, so this module imports + * nothing from it. + */ +import type { UatGenerationRepo } from '../overdeck/merge-types.js'; + +/** PAN-5995: where a refusal sends the operator when a resume can never prove its state. */ +export const ABANDON_HINT = 'if the batch cannot be finished, abandon it with `pan merge void <generation> --abandon-partial --reason <text>`'; + +interface ResumeRepoGit { + findLandedMerge(branchName: string, recordedHead: string): Promise<string | null>; + uatBranchHead?(branchName: string): Promise<string | null>; +} + +const firstLine = (err: unknown) => (err instanceof Error ? err.message.split('\n')[0] : String(err)); + +/** Why a stamped repo cannot be confirmed merged on its target, or null when it can. */ +export async function landedStampRefusal(repo: UatGenerationRepo, git: ResumeRepoGit | undefined): Promise<string | null> { + if (!git) return 'there are no promote git deps for it, so its merge cannot be confirmed'; + // The head assembly recorded is what was tested; without it, a merge of a rewritten branch could pass. + if (!repo.headSha) return `assembly recorded no uat head for it, so its merge cannot be proven; ${ABANDON_HINT}`; + try { + if (await git.findLandedMerge(repo.branch, repo.headSha)) return null; + } catch (err) { + return `confirming its merge failed (${firstLine(err)})`; + } + return `it is stamped promoted at ${repo.promotedAt}, but its recorded uat head is not contained in ${repo.targetBranch ?? 'main'} (or ${repo.branch} was rewritten since assembly)`; +} + +/** Pending repos whose uat branch is not at the head assembly recorded, each with the reason. */ +export async function movedUatHeads( + pending: readonly UatGenerationRepo[], + repoGit: ReadonlyMap<string, ResumeRepoGit>, +): Promise<Array<{ repoKey: string; why: string }>> { + const moved: Array<{ repoKey: string; why: string }> = []; + for (const repo of pending) { + const git = repoGit.get(repo.repoKey); + if (!repo.headSha) { moved.push({ repoKey: repo.repoKey, why: `assembly recorded no uat head for it; ${ABANDON_HINT}` }); continue; } + if (!git?.uatBranchHead) { moved.push({ repoKey: repo.repoKey, why: 'its uat head cannot be read' }); continue; } + let head: string | null; + try { + head = await git.uatBranchHead(repo.branch); + } catch (err) { + moved.push({ repoKey: repo.repoKey, why: `reading its uat head failed (${firstLine(err)})` }); + continue; + } + if (head === null) moved.push({ repoKey: repo.repoKey, why: `${repo.branch} no longer exists on origin` }); + else if (head !== repo.headSha) moved.push({ repoKey: repo.repoKey, why: `${repo.branch} moved from ${repo.headSha.slice(0, 9)} to ${head.slice(0, 9)} since assembly` }); + } + return moved; +} diff --git a/src/lib/cloister/uat-promote.ts b/src/lib/cloister/uat-promote.ts index 4f75d98f86b..ee50cb52bae 100644 --- a/src/lib/cloister/uat-promote.ts +++ b/src/lib/cloister/uat-promote.ts @@ -23,7 +23,8 @@ import { execFile } from 'child_process'; import type { UatGeneration, UatGenerationRepo, UatGenerationStatus } from '../overdeck/merge-sync.js'; import type { VerifiedMergedRepo } from './merge-verification.js'; import type { GenerationStorePort } from './uat-generation-engine.js'; -import { withUatGenerationPromoting } from './uat-promote-inflight.js'; +import { isUatGenerationPartiallyPromoted, withUatGenerationPromoting } from './uat-promote-inflight.js'; +import { ABANDON_HINT, landedStampRefusal, movedUatHeads } from './uat-promote-resume.js'; const execFileAsync = promisify(execFile); @@ -69,8 +70,12 @@ export interface PolyrepoRepoPromoteGit { changedFilesSince(baseSha: string): Promise<string[]>; /** Files this repo's uat branch changes vs its merge-base with the target. */ batchChangedFiles(branchName: string): Promise<string[]>; - /** Merge the uat branch into the target locally. MUST NOT push. */ - trialMerge(branchName: string, message: string): Promise<PreparedRepoMerge>; + /** + * Merge the uat branch into the target locally. MUST NOT push. PAN-5995: + * with `sha`, merge exactly that commit, not whatever the ref points at now; + * a resume passes the head it verified, so a fetch in between cannot swap it. + */ + trialMerge(branchName: string, message: string, sha?: string): Promise<PreparedRepoMerge>; /** Push an already-prepared merge to the target branch. */ publishPrepared(prepared: PreparedRepoMerge): Promise<void>; /** Drop a prepared merge's worktree. Must be safe to call twice. */ @@ -79,6 +84,10 @@ export interface PolyrepoRepoPromoteGit { * If this repo's uat branch is ALREADY contained in its target branch, the * merge commit that brought it in; otherwise null. * + * PAN-5995: judged at `recordedHead` (the tested head assembly pushed), not + * at the branch's current tip; a tip that differs from it answers null. + * + * * Publishing and stamping are two operations against two systems. A process * death, a thrown state write, or a dropped connection after the remote * accepted the push leaves a repo genuinely landed with `promoted_at` null. @@ -87,7 +96,14 @@ export interface PolyrepoRepoPromoteGit { * wedging a half-landed batch permanently. This lets recovery prove the truth * from git instead of trusting local state. */ - findLandedMerge(branchName: string): Promise<string | null>; + findLandedMerge(branchName: string, recordedHead: string): Promise<string | null>; + /** + * PAN-5995: the head of this repo's uat branch, freshly fetched into the + * `origin/<branch>` ref that trialMerge merges, or null when the branch is + * gone from origin. A failed fetch throws. A resumed promote compares it with + * the head assembly recorded. Omitted = unknown, so a resume refuses. + */ + uatBranchHead?(branchName: string): Promise<string | null>; } export interface UatPromoteDeps { @@ -157,6 +173,8 @@ export type PromoteResult = * a newer one and an invalidated one was voided; neither is promotable. */ const PROMOTABLE: readonly UatGenerationStatus[] = ['ready']; +/** The live statuses a promote voids in its siblings. */ +const SWEPT: readonly UatGenerationStatus[] = ['ready', 'superseded']; /** * The fast, forge-free refusal for a promote request: a generation that @@ -405,8 +423,15 @@ async function promotePolyrepo( // all-or-nothing, so one such row withholds it for the whole generation and // post-merge verification refuses forever. Recovering the SHA is the only // way out, and it is exactly what findLandedMerge answers. - if (repo.promotedAt && repo.mergeSha) { recovered.push(repo); continue; } const git = repoGit.get(repo.repoKey); + if (repo.promotedAt && repo.mergeSha) { + // PAN-5995: a stamp is a claim. Before resuming, confirm on the target + // that a merge containing this repo's uat head really landed. + const why = await landedStampRefusal(repo, git); + if (why) unproven.push({ repoKey: repo.repoKey, why }); + recovered.push(repo); + continue; + } if (!git) { // An unstamped row without deps is simply pending, and the `missing` check // below rejects it by name. A STAMPED one is the dangerous case: the stamp @@ -419,9 +444,18 @@ async function promotePolyrepo( continue; } + // PAN-5995: with no recorded head, "landed" is unprovable: unstamped stays pending, stamped refuses. + if (!repo.headSha) { + if (repo.promotedAt) { + unproven.push({ repoKey: repo.repoKey, why: `assembly recorded no uat head for it, so its merge cannot be proven; ${ABANDON_HINT}` }); + } + recovered.push(repo); + continue; + } + let landedSha: string | null = null; try { - landedSha = await git.findLandedMerge(repo.branch); + landedSha = await git.findLandedMerge(repo.branch, repo.headSha); } catch (err) { // Unknown is not "pending". Treating it as pending would trial-merge and // possibly republish a merge that is already live. @@ -480,6 +514,18 @@ async function promotePolyrepo( const pending = recovered.filter((r) => !r.promotedAt); if (alreadyLanded.length > 0) { log(`[uat-promote] ${gen.name}: resuming — ${alreadyLanded.map((r) => r.repoKey).join(', ')} already landed`); + // PAN-5995: land only what was tested. A pending repo's uat branch must + // still be at the head assembly pushed. + const moved = await movedUatHeads(pending, repoGit); + if (moved.length > 0) { + const detail = moved.map((m) => `${m.repoKey} (${m.why})`).join('; '); + log(`[uat-promote] ${gen.name}: not resuming — ${detail}`); + return { + success: false, + reason: 'merge-failed', + message: `${gen.name} is partially promoted, but it cannot be resumed: ${detail}. Nothing was published on this attempt.`, + }; + } } if (pending.length === 0) { // Every repo already landed. This is the crash window between the last @@ -560,7 +606,8 @@ async function promotePolyrepo( } try { - prepared.push(await git.trialMerge(repo.branch, message)); + // PAN-5995: a resume merges the uat head movedUatHeads verified. + prepared.push(await git.trialMerge(repo.branch, message, alreadyLanded.length > 0 ? repo.headSha ?? undefined : undefined)); } catch (err) { await discardAll(); return { @@ -708,9 +755,13 @@ async function finishPromote( const invalidated: string[] = []; for (const other of deps.store.listChain(projectRoot, ['ready', 'superseded'])) { if (other.name === gen.name) continue; + // PAN-5995: a half-landed batch is resumed, never voided. Re-read the row: + // a sibling's promote may stamp a repo while an earlier teardown awaits. + const current = deps.store.get(other.name); + if (!current || !SWEPT.includes(current.status) || isUatGenerationPartiallyPromoted(current)) continue; deps.store.update(other.name, { status: 'invalidated', statusReason: `${gen.name} was merged to main`, voidedBy: gen.name }); invalidated.push(other.name); - await deps.teardownStack(other).catch(() => {}); + await deps.teardownStack(current).catch(() => {}); } // Standard per-issue post-merge handoff, exactly once each (PAN-328 guard). @@ -768,8 +819,9 @@ async function finishPromote( export function buildPolyrepoUatPromoteGitDeps( repos: ReadonlyArray<{ repoKey: string; repoPath: string; targetBranch?: string }>, ): Map<string, PolyrepoRepoPromoteGit> { + // PAN-5995: bounded, like assembly's git (`GIT_CALL_TIMEOUT_MS`): a resumed promote must not hang a click forever. const runGit = (args: string[], cwd: string) => - execFileAsync('git', args, { cwd, maxBuffer: 16 * 1024 * 1024 }); + execFileAsync('git', args, { cwd, maxBuffer: 16 * 1024 * 1024, timeout: 10 * 60_000 }); return new Map( repos.map((repo) => { @@ -800,15 +852,16 @@ export function buildPolyrepoUatPromoteGitDeps( return stdout.split('\n').map((l) => l.trim()).filter(Boolean); }, - trialMerge: async (branchName, message) => { + trialMerge: async (branchName, message, sha) => { const safeBranch = safeUatBranchName(branchName); + if (sha !== undefined && !/^[0-9a-f]{7,40}$/i.test(sha)) throw new Error(`unsafe uat head sha: ${sha}`); const worktreePath = worktreeFor(safeBranch); await runGit(['worktree', 'remove', '--force', worktreePath], repo.repoPath).catch(() => {}); await runGit(['worktree', 'prune'], repo.repoPath).catch(() => {}); await runGit(['worktree', 'add', '--detach', worktreePath, originTarget], repo.repoPath); try { const originRef = `origin/${safeBranch}`; - const ref = await runGit(['rev-parse', '--verify', originRef], worktreePath) + const ref = sha ?? await runGit(['rev-parse', '--verify', originRef], worktreePath) .then(() => originRef) .catch(() => safeBranch); await runGit(['merge', '--no-ff', ref, '-m', message], worktreePath); @@ -832,8 +885,18 @@ export function buildPolyrepoUatPromoteGitDeps( await runGit(['worktree', 'prune'], repo.repoPath).catch(() => {}); }, - findLandedMerge: async (branchName) => { + uatBranchHead: async (branchName) => { + const safeBranch = safeUatBranchName(branchName); + const listed = await runGit(['ls-remote', 'origin', `refs/heads/${safeBranch}`], repo.repoPath); + if (!listed.stdout.trim()) return null; + // Refresh and read the tracking ref trialMerge merges, so the head checked is the head merged. + await runGit(['fetch', 'origin', `+refs/heads/${safeBranch}:refs/remotes/origin/${safeBranch}`], repo.repoPath); + return (await runGit(['rev-parse', `origin/${safeBranch}`], repo.repoPath)).stdout.trim(); + }, + + findLandedMerge: async (branchName, recordedHead) => { const safeBranch = safeUatBranchName(branchName); + if (!/^[0-9a-f]{7,40}$/i.test(recordedHead)) throw new Error(`unsafe recorded uat head: ${recordedHead}`); // This call establishes REMOTE truth after an ambiguous publish, so a // failed fetch must not be answered from a cached target ref: that // could report "not landed" for a merge that is live, and republish it. @@ -859,23 +922,27 @@ export function buildPolyrepoUatPromoteGitDeps( const tip = await runGit(['rev-parse', ref], repo.repoPath) .then(({ stdout }) => stdout.trim()) .catch(() => ''); - if (!tip) return null; + // PAN-5995: a uat tip that is not the recorded head was rewritten after + // assembly, so whatever landed from it is not what was tested. + if (tip && !tip.toLowerCase().startsWith(recordedHead.toLowerCase())) return null; + // The recorded head is the evidence; a gone branch still leaves its commit. + const head = tip || recordedHead; // Contained in the target? If not, this repo genuinely has not landed. - const contained = await runGit(['merge-base', '--is-ancestor', tip, originTarget], repo.repoPath) + const contained = await runGit(['merge-base', '--is-ancestor', head, originTarget], repo.repoPath) .then(() => true) .catch(() => false); if (!contained) return null; // The merge commit that brought it in: the oldest merge on the - // ancestry path from the batch tip to the target head. + // ancestry path from the batch head to the target head. const { stdout } = await runGit( - ['rev-list', '--ancestry-path', '--merges', '--reverse', `${tip}..${originTarget}`], + ['rev-list', '--ancestry-path', '--merges', '--reverse', `${head}..${originTarget}`], repo.repoPath, ).catch(() => ({ stdout: '' })); const mergeCommit = stdout.split('\n').map((l) => l.trim()).filter(Boolean)[0]; - // A fast-forwarded target has no merge commit; the tip itself is what landed. - return mergeCommit ?? tip; + // A fast-forwarded target has no merge commit; the head itself is what landed. + return mergeCommit ?? head; }, }; diff --git a/src/lib/cloister/uat-reconciler.ts b/src/lib/cloister/uat-reconciler.ts index 4ca52d00dc7..a83f82c36d8 100644 --- a/src/lib/cloister/uat-reconciler.ts +++ b/src/lib/cloister/uat-reconciler.ts @@ -16,6 +16,13 @@ * the batch. Per-PR ownership is not consulted while off: with the train * off every normal feature reads as per-PR owned. A generation a promote * is merging (`isUatGenerationPromoting`) is never touched, on or off. + * PAN-5995: neither is a partially promoted one (a repo stamped + * `promoted_at`, status not `promoted`; it survives a restart that empties + * the in-process set). It is logged as "partially promoted: resume + * promote". While a ready one exists no new generation assembles for the + * project, forced or not (action `partially-promoted`): the retried + * promote must land the rest against the targets it was tested on. The + * hold lifts once the promote completes and the row reads `promoted`. * 2. Invalidate live generations that went stale — a member left the ready * set (merged on its own, or no longer ready), a member branch gained * commits, or the per-PR train now owns a member. The one-sentence @@ -51,7 +58,11 @@ import type { ReadyFeature, GenerationStorePort } from './uat-generation-engine. import type { UatGeneration } from '../overdeck/merge-sync.js'; import type { BatchChoice } from './batch-window.js'; import type { BaseMove } from './bookkeeping-paths.js'; -import { isUatGenerationPromoting } from './uat-promote-inflight.js'; +import { + isUatGenerationPartiallyPromoted, + isUatGenerationPromoting, + PARTIALLY_PROMOTED_REASON, +} from './uat-promote-inflight.js'; /** * An 'assembling' row with NO PROGRESS for this long is marked failed (train @@ -202,7 +213,9 @@ export interface ReconcileResult { /** PAN-3965: exactly one feature is ready — it merges directly, no batch. */ | 'single-feature' /** PAN-4753: the batch window is still open — not enough features, not waited long enough. */ - | 'waiting'; + | 'waiting' + /** PAN-5995: a ready generation is partially promoted; nothing assembles until its promote is resumed. */ + | 'partially-promoted'; invalidated: string[]; generation?: UatGeneration; /** PAN-4970: ready features the per-PR auto-merge scheduler owns this tick, upper-cased and sorted. */ @@ -332,7 +345,8 @@ async function staleWhileOff( ): Promise<string | null> { for (const member of gen.members) { const id = member.issueId.toUpperCase(); - if (mergedIds.has(id)) return `${member.issueId} was merged on its own, outside the batch`; + // PAN-5995: the ready set first. A member that is ready right now has not + // departed, even when an older PR on a reused `feature/<id>` branch merged. if (desiredIds.has(id)) { const current = headShas.get(member.branch); if (current !== undefined && !unreadableAnchor(current) && current !== member.headSha) { @@ -340,6 +354,7 @@ async function staleWhileOff( } continue; } + if (mergedIds.has(id)) return `${member.issueId} was merged on its own, outside the batch`; const evidence = deps.departureEvidence ? await deps.departureEvidence(member).catch(() => null) : null; @@ -354,6 +369,8 @@ const lastLoggedPerPr = new Map<string, string>(); const lastLoggedWait = new Map<string, string>(); /** Per-project last-logged bookkeeping-only keep (PAN-5356), so it logs only on change. */ const lastLoggedKeep = new Map<string, string>(); +/** Per-project last-logged partially promoted generations (PAN-5995), so it logs only on change. */ +const lastLoggedPartial = new Map<string, string>(); /** * Partition the ready set into per-PR-owned ids and the batch-owned subset. @@ -460,10 +477,34 @@ export async function reconcileUatGenerations( const mergedIds = liveChain.length > 0 && deps.mergedIssueIds ? await deps.mergedIssueIds().catch(() => new Set<string>()) : new Set<string>(); + const partial: UatGeneration[] = []; + /** PAN-5995: the live row as it stands now, after the awaits that preceded the call. */ + const reread = (name: string) => deps.store.listChain(projectRoot, ['ready', 'superseded']).find((g) => g.name === name); + /** + * PAN-5995: the assembly hold, read fresh from the store. A promote in + * flight is skipped by the scan above, and one may stamp a repo during any + * later await, so the hold never trusts that scan. + */ + const heldByPartial = () => deps.store.listChain(projectRoot, ['ready']).some(isUatGenerationPartiallyPromoted); for (const gen of liveChain) { // PAN-5966: a promote owns this generation until its final write. if (isUatGenerationPromoting(gen.name)) continue; + // PAN-5995: a half-landed promote is resumed, never invalidated, and not + // stamped either, even once every repo is contained: the resumed promote + // finalizes it and runs post-merge, which a bare stamp would skip. + if (isUatGenerationPartiallyPromoted(gen)) { + partial.push(gen); + continue; + } if (await deps.isGenerationContainedInMain?.(gen).catch(() => false)) { + // PAN-5995: a promote may have begun, and stamped a repo, during that read. + if (isUatGenerationPromoting(gen.name)) continue; + const current = reread(gen.name); + if (!current) continue; + if (isUatGenerationPartiallyPromoted(current)) { + partial.push(current); + continue; + } log(`[uat-reconciler] stamping ${gen.name} promoted — branch is contained in main`); deps.store.update(gen.name, { status: 'promoted' }); continue; @@ -473,6 +514,14 @@ export async function reconcileUatGenerations( : await staleWhileOff(gen, desiredIds, headShas, mergedIds, deps); if (!staleReason) continue; if (isUatGenerationPromoting(gen.name)) continue; // a promote began during the reads above + // PAN-5995: the row read above predates the awaits; a promote that + // stamped a repo and then stopped in the meantime has cleared its mark. + const current = reread(gen.name); + if (!current) continue; + if (isUatGenerationPartiallyPromoted(current)) { + partial.push(current); + continue; + } log(`[uat-reconciler] invalidating ${gen.name}: ${staleReason}`); deps.store.update(gen.name, { status: 'invalidated', statusReason: staleReason }); invalidated.push(gen.name); @@ -481,6 +530,12 @@ export async function reconcileUatGenerations( }); } + const partialKey = partial.map((gen) => gen.name).join(', '); + if (lastLoggedPartial.get(key) !== partialKey) { + lastLoggedPartial.set(key, partialKey); + if (partialKey) log(`[uat-reconciler] ${partialKey}: ${PARTIALLY_PROMOTED_REASON}`); + } + // 2. Un-wedge crashed assemblies; respect a live one. "Stuck" means NO // PROGRESS (updated_at stale) — the engine patches the row after every // member step, so total age is the wrong signal: a big batch grinding @@ -509,6 +564,12 @@ export async function reconcileUatGenerations( return { action: 'idle', invalidated, perPr }; } + // PAN-5995: hold assembly while a ready generation is partially promoted. + if (heldByPartial()) { + await deps.cleanup().catch(() => {}); + return { action: 'partially-promoted', invalidated, perPr }; + } + // PAN-4753 D4: the batch window picks what to assemble, or says wait. let windowed = false; let toAssemble: readonly ReadyFeature[] = batchReadySet; @@ -602,6 +663,13 @@ export async function reconcileUatGenerations( } } + // PAN-5995: again after the last await before assembly (selectBatch, + // holdsForUat, the base checks): a promote may have stamped a repo since. + if (heldByPartial()) { + await deps.cleanup().catch(() => {}); + return { action: 'partially-promoted', invalidated, perPr }; + } + log(`[uat-reconciler] assembling next generation for ${toAssemble.length} ready feature(s)`); const generation = await deps.assemble(toAssemble); await deps.cleanup().catch(() => {}); diff --git a/src/lib/overdeck/__tests__/schema-topups.test.ts b/src/lib/overdeck/__tests__/schema-topups.test.ts index ce62f37f77e..451d17d78c6 100644 --- a/src/lib/overdeck/__tests__/schema-topups.test.ts +++ b/src/lib/overdeck/__tests__/schema-topups.test.ts @@ -288,6 +288,35 @@ describe('overdeck schema top-ups', () => { expect(columns(getOverdeckDatabase(dbPath))).toContain('voided_by'); }); + it('adds the uat_generations cleanup backoff columns on a fresh and on a pre-existing database (PAN-5995)', () => { + const columns = (db: SqliteDatabase) => db + .prepare('PRAGMA table_info(`uat_generations`)') + .all<{ name: string }>() + .map((column) => column.name); + const dbPath = makeDbPath(); + const fresh = getOverdeckDatabase(dbPath); + expect(columns(fresh)).toEqual(expect.arrayContaining(['cleanup_attempts', 'cleanup_next_attempt_at'])); + fresh.exec('ALTER TABLE `uat_generations` DROP COLUMN `cleanup_attempts`'); + fresh.exec('ALTER TABLE `uat_generations` DROP COLUMN `cleanup_next_attempt_at`'); + closeOverdeckDatabase(); + + expect(columns(getOverdeckDatabase(dbPath))).toEqual(expect.arrayContaining(['cleanup_attempts', 'cleanup_next_attempt_at'])); + }); + + it('adds uat_generation_repos.head_sha on a fresh and on a pre-existing database (PAN-5995)', () => { + const columns = (db: SqliteDatabase) => db + .prepare('PRAGMA table_info(`uat_generation_repos`)') + .all<{ name: string }>() + .map((column) => column.name); + const dbPath = makeDbPath(); + const fresh = getOverdeckDatabase(dbPath); + expect(columns(fresh)).toContain('head_sha'); + fresh.exec('ALTER TABLE `uat_generation_repos` DROP COLUMN `head_sha`'); + closeOverdeckDatabase(); + + expect(columns(getOverdeckDatabase(dbPath))).toContain('head_sha'); + }); + it('logs a missing-table top-up failure while startup and later top-ups continue', () => { const dbPath = makeDbPath(); const initial = getOverdeckDatabase(dbPath); diff --git a/src/lib/overdeck/infra.ts b/src/lib/overdeck/infra.ts index fa1cf6526a1..3e9c1f96bb3 100644 --- a/src/lib/overdeck/infra.ts +++ b/src/lib/overdeck/infra.ts @@ -123,6 +123,9 @@ function ensureRuntimeIndexesSync(db: SqliteDatabase): void { runSchemaTopUp(db, 'ALTER TABLE `uat_generations` ADD COLUMN `status_reason` text'); // PAN-5364: the batch whose promote voided this one, so the board can fold it under that merge. runSchemaTopUp(db, 'ALTER TABLE `uat_generations` ADD COLUMN `voided_by` text'); + // PAN-5995: per-generation backoff for failed cleanups. + runSchemaTopUp(db, 'ALTER TABLE `uat_generations` ADD COLUMN `cleanup_attempts` integer'); + runSchemaTopUp(db, 'ALTER TABLE `uat_generations` ADD COLUMN `cleanup_next_attempt_at` integer'); // PAN-4753: what was scheduled — a feature PR or a strike PR. runSchemaTopUp(db, "ALTER TABLE `pending_auto_merges` ADD COLUMN `kind` text NOT NULL DEFAULT 'feature'"); // PAN-4185: bare conversations (no Overdeck-injected context) and the @@ -587,6 +590,8 @@ function ensureUatGenerationRepoTablesSync(db: SqliteDatabase): void { // build has the tables but not these. runSchemaTopUp(db, "ALTER TABLE `uat_generation_repos` ADD COLUMN `target_branch` text DEFAULT 'main' NOT NULL"); runSchemaTopUp(db, 'ALTER TABLE `uat_generation_repos` ADD COLUMN `merge_sha` text'); + // PAN-5995: the uat branch head assembly pushed, checked by a resumed promote. + runSchemaTopUp(db, 'ALTER TABLE `uat_generation_repos` ADD COLUMN `head_sha` text'); // PAN-3166: assembly-time resolutions are no longer conflict-only — the union // lint also renumbers colliding Flyway migrations. Nullable, so rows written // before this read back as conflict resolutions. diff --git a/src/lib/overdeck/merge-sync-uat.ts b/src/lib/overdeck/merge-sync-uat.ts index ec8bdfe8ce6..2d24a232608 100644 --- a/src/lib/overdeck/merge-sync-uat.ts +++ b/src/lib/overdeck/merge-sync-uat.ts @@ -55,6 +55,9 @@ interface OverdeckUatGenerationRow { /** PAN-4753; absent on a database that predates the top-up. */ status_reason?: string | null; voided_by?: string | null; + /** PAN-5995; absent on a database that predates the top-up. */ + cleanup_attempts?: number | null; + cleanup_next_attempt_at?: number | null; created_at: number; updated_at: number; } @@ -94,6 +97,8 @@ interface OverdeckUatRepoRow { merge_order: number; promoted_at: number | null; merge_sha: string | null; + /** PAN-5995; absent on a database that predates the top-up. */ + head_sha?: string | null; } interface OverdeckUatMemberRepoRow { @@ -177,6 +182,7 @@ function rowToUatGeneration( targetBranch: r.target_branch ?? 'main', worktreePath: r.worktree_path, mergeOrder: r.merge_order, + headSha: r.head_sha ?? null, promotedAt: isoFromMillis(r.promoted_at) ?? null, mergeSha: r.merge_sha ?? null, })) @@ -215,6 +221,8 @@ function rowToUatGeneration( cleanedAt: isoFromMillis(row.cleaned_at) ?? null, statusReason: row.status_reason ?? null, voidedBy: row.voided_by ?? null, + cleanupAttempts: row.cleanup_attempts ?? null, + cleanupNextAttemptAt: isoFromMillis(row.cleanup_next_attempt_at ?? null) ?? null, createdAt: isoFromMillisRequired(row.created_at), updatedAt: isoFromMillisRequired(row.updated_at), }; @@ -311,8 +319,8 @@ function writeUatGenerationRepoRows( const insertRepo = db.prepare(` INSERT INTO uat_generation_repos - (uat_name, repo_key, repo_path, branch, base_sha, target_branch, worktree_path, merge_order, promoted_at, merge_sha) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + (uat_name, repo_key, repo_path, branch, base_sha, target_branch, worktree_path, merge_order, promoted_at, merge_sha, head_sha) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `); for (const r of repos) { insertRepo.run( @@ -326,6 +334,7 @@ function writeUatGenerationRepoRows( r.mergeOrder, r.promotedAt ? millisFromIso(r.promotedAt) : null, r.mergeSha ?? null, + r.headSha ?? null, ); } } @@ -458,10 +467,13 @@ export function listUatGenerationNames(): string[] { return rows.map((r) => r.name); } +/** Patch keys that record cleanup progress only and leave `updated_at` alone. */ +const CLEANUP_BOOKKEEPING_KEYS: ReadonlySet<string> = new Set(['cleanedAt', 'cleanupAttempts', 'cleanupNextAttemptAt']); + /** Drop-in for updateUatGenerationSync() from uat-generations-db.ts. */ export function updateUatGeneration( name: string, - patch: Partial<Pick<UatGeneration, 'status' | 'baseSha' | 'members' | 'heldOut' | 'resolutions' | 'cleanedAt' | 'repos' | 'statusReason' | 'voidedBy'>>, + patch: Partial<Pick<UatGeneration, 'status' | 'baseSha' | 'members' | 'heldOut' | 'resolutions' | 'cleanedAt' | 'repos' | 'statusReason' | 'voidedBy' | 'cleanupAttempts' | 'cleanupNextAttemptAt'>>, ): void { const db = getOverdeckDatabase(); @@ -474,12 +486,20 @@ export function updateUatGeneration( if (patch.cleanedAt !== undefined) { sets.push('cleaned_at = ?'); params.push(millisFromIso(patch.cleanedAt)); } if (patch.statusReason !== undefined) { sets.push('status_reason = ?'); params.push(patch.statusReason); } if (patch.voidedBy !== undefined) { sets.push('voided_by = ?'); params.push(patch.voidedBy); } + if (patch.cleanupAttempts !== undefined) { sets.push('cleanup_attempts = ?'); params.push(patch.cleanupAttempts); } + if (patch.cleanupNextAttemptAt !== undefined) { + sets.push('cleanup_next_attempt_at = ?'); + params.push(patch.cleanupNextAttemptAt ? millisFromIso(patch.cleanupNextAttemptAt) : null); + } if (sets.length > 0) { // PAN-4598: cleaned_at is artifact bookkeeping, not a lifecycle change. // A cleanup-only patch leaves updated_at alone, so on a failed row it // stays the failure time that the reconciler cutoff and the UAT card read. - const cleanupOnly = Object.entries(patch).every(([key, value]) => key === 'cleanedAt' || value === undefined); + // PAN-5995: the cleanup backoff fields are bookkeeping too; a failed + // cleanup must not restart a superseded batch's grace period. + const cleanupOnly = Object.entries(patch).every(([key, value]) => + CLEANUP_BOOKKEEPING_KEYS.has(key) || value === undefined); if (!cleanupOnly) { sets.push('updated_at = ?'); params.push(nowMillis()); diff --git a/src/lib/overdeck/merge-types.ts b/src/lib/overdeck/merge-types.ts index 271e0c09eb5..4f1e3c28a0f 100644 --- a/src/lib/overdeck/merge-types.ts +++ b/src/lib/overdeck/merge-types.ts @@ -66,6 +66,12 @@ export interface UatGenerationRepo { worktreePath: string; /** Publish order during promote; ascending. */ mergeOrder: number; + /** + * PAN-5995: the head of this repo's uat branch as assembly pushed it. A + * resumed promote refuses a pending repo whose uat branch moved off it. Null + * for rows written before the column existed. + */ + headSha?: string | null; /** ISO timestamp once this repo's merge landed on its target branch. */ promotedAt?: string | null; /** @@ -172,6 +178,10 @@ export interface UatGeneration { statusReason?: string | null; /** PAN-5364: name of the batch whose promote voided this one; null otherwise and for rows written earlier. */ voidedBy?: string | null; + /** PAN-5995: failed cleanup attempts since the last success; null when none failed. */ + cleanupAttempts?: number | null; + /** PAN-5995: ISO time before which cleanup does not retry this generation; null when none failed. */ + cleanupNextAttemptAt?: string | null; createdAt: string; /** Last lifecycle change; cleanup does not move it, so a failed row keeps its failure time. */ updatedAt: string; diff --git a/tests/unit/lib/cloister/uat-generation-engine.test.ts b/tests/unit/lib/cloister/uat-generation-engine.test.ts index 6a0ae4c2ad5..4a4a29f8d8f 100644 --- a/tests/unit/lib/cloister/uat-generation-engine.test.ts +++ b/tests/unit/lib/cloister/uat-generation-engine.test.ts @@ -169,6 +169,22 @@ describe('assembleUatGeneration — happy path', () => { expect(store.rows.get(gen.name)!.status).toBe('ready'); }); + it('PAN-5995: never supersedes a partially promoted ready generation', async () => { + const store = makeFakeStore([{ + name: 'uat/pan-otter-0609', worktreePath: '/proj/workspaces/uat-pan-otter-0609', + projectRoot: '/proj', baseSha: 'old', status: 'ready', + members: [], heldOut: [], resolutions: [], stackStartedAt: null, + repos: [{ + repoKey: 'fe', repoPath: '/proj/fe', branch: 'uat/pan-otter-0609', baseSha: 'old', targetBranch: 'main', + worktreePath: '/proj/workspaces/uat-pan-otter-0609/fe', mergeOrder: 0, promotedAt: '2026-06-09T12:00:00.000Z', mergeSha: 'm1', + }], + createdAt: '2026-06-09T00:00:00.000Z', updatedAt: '', + }]); + await assembleUatGeneration(input(), deps(makeFakeGit(), store)); + + expect(store.rows.get('uat/pan-otter-0609')!.status).toBe('ready'); + }); + it('mints a unique daily branch and preserves the prior row on rebuild', async () => { const store = makeFakeStore(); const git = makeFakeGit(); @@ -581,17 +597,21 @@ describe('cleanupUatGenerations', () => { expect(SUPERSEDED_REAP_AFTER_MS).toBe(24 * 3_600_000); }); - it('PAN-5966: leaves cleanedAt unset when a branch delete fails, so the next tick retries', async () => { + it('PAN-5966: leaves cleanedAt unset when a branch delete fails, so a later tick retries', async () => { const store = makeFakeStore([liveGen('uat/pan-d-0610', 'invalidated', '2026-06-10T02:00:00.000Z')]); + let clock = Date.parse('2026-06-10T03:00:00.000Z'); const deps = { store, removeWorktree: async () => {}, deleteBranch: vi.fn(async () => { throw new Error('git push origin --delete uat/pan-d-0610 failed (timed out)'); }), + now: () => clock, }; await cleanupUatGenerations('/proj', deps); expect(store.rows.get('uat/pan-d-0610')!.cleanedAt).toBeFalsy(); + // PAN-5995: the retry waits out the 1-minute backoff. + clock += 60_000; deps.deleteBranch.mockResolvedValueOnce(undefined); await cleanupUatGenerations('/proj', deps); expect(deps.deleteBranch).toHaveBeenCalledTimes(2); diff --git a/tests/unit/lib/cloister/uat-polyrepo-cleanup.test.ts b/tests/unit/lib/cloister/uat-polyrepo-cleanup.test.ts index 2c9e3c79939..312b8507e84 100644 --- a/tests/unit/lib/cloister/uat-polyrepo-cleanup.test.ts +++ b/tests/unit/lib/cloister/uat-polyrepo-cleanup.test.ts @@ -9,13 +9,16 @@ import { describe, it, expect, vi } from 'vitest'; import { + cleanupBackoffMs, cleanupUatGenerations, type GenerationCleanupDeps, type GenerationStorePort, } from '../../../../src/lib/cloister/uat-generation-engine.js'; import { + ALREADY_GONE, buildPolyrepoCleanupGit, buildUatGenerationCleanupGit, + isSafeResidueRepoKey, removeOrAlreadyGone, safeGenerationWorktreePath, } from '../../../../src/lib/cloister/uat-generation-deps.js'; @@ -141,7 +144,8 @@ describe('polyrepo generation cleanup', () => { }, })); - expect(store.patches).toEqual([]); + // PAN-5995: only the backoff is recorded; cleanedAt stays unset. + expect(store.patches.map(([, patch]) => Object.keys(patch as object).sort())).toEqual([['cleanupAttempts', 'cleanupNextAttemptAt']]); expect(rec.logs.join('\n')).toContain('api artifact removal failed'); expect(rec.logs.join('\n')).toContain('branch -D refused'); }); @@ -168,7 +172,8 @@ describe('polyrepo generation cleanup', () => { removeGenerationResidue: async () => { throw new Error('EBUSY'); }, })); - expect(store.patches).toEqual([]); + // PAN-5995: only the backoff is recorded; cleanedAt stays unset. + expect(store.patches.map(([, patch]) => Object.keys(patch as object).sort())).toEqual([['cleanupAttempts', 'cleanupNextAttemptAt']]); expect(rec.logs.join('\n')).toContain('generation folder removal failed'); }); @@ -291,3 +296,158 @@ describe('PAN-5966: a cleanup git step fails unless git says the target is alrea await expect(removeOrAlreadyGone(['push', 'origin', '--delete', 'uat/x-1'], '/repo', gone, run)).rejects.toThrow('timed out'); }); }); + +describe('PAN-5995: cleanup never reaps a partially promoted generation, even after a restart', () => { + it('leaves every worktree, branch and the stack alone when a repo carries promoted_at and the in-process set is empty', async () => { + for (const status of ['superseded', 'failed'] as const) { + // Restart mid-promote: fe landed and was stamped, api was not. Nothing marks + // the generation as promoting any more; only the durable stamp remains. + const gen = generation({ + status, + stackStartedAt: null, + updatedAt: '2026-07-01T00:00:00.000Z', + repos: [{ ...repoRow('fe', 0), promotedAt: '2026-07-27T10:00:00.000Z', mergeSha: 'fe-merge' }, repoRow('api', 1)], + }); + const store = makeStore([gen]); + const rec = recorder(); + + await cleanupUatGenerations(PROJECT_ROOT, makeDeps(store, rec, { now: () => Date.parse('2026-07-28T00:00:00.000Z') })); + + expect(rec.repoArtifacts).toEqual([]); + expect(rec.residue).toEqual([]); + expect(rec.stacks).toEqual([]); + expect(rec.monoBranches).toEqual([]); + expect(store.patches).toEqual([]); + } + }); +}); + +describe('PAN-5995: an abandoned partially promoted generation is reaped like any voided one', () => { + it('removes its uat branches and worktrees, keeps the landed repos\' stamps, and writes only cleanedAt', async () => { + // `pan merge void --abandon-partial` left it invalidated with fe's stamp in place. + const gen = generation({ + status: 'invalidated', + stackStartedAt: null, + statusReason: 'abandoned by the operator while partially promoted (landed: fe@fe-merge; not landed: api): api MR closed', + repos: [{ ...repoRow('fe', 0), promotedAt: '2026-07-27T10:00:00.000Z', mergeSha: 'fe-merge' }, repoRow('api', 1)], + }); + const store = makeStore([gen]); + const rec = recorder(); + + await cleanupUatGenerations(PROJECT_ROOT, makeDeps(store, rec)); + + expect(rec.repoArtifacts.map((a) => a.split(':')[0])).toEqual(['fe', 'api']); + expect(rec.residue).toEqual([GEN_FOLDER]); + expect(store.patches).toHaveLength(1); + expect(Object.keys(store.patches[0]![1] as object)).toEqual(['cleanedAt']); + }); +}); + +describe('PAN-5995: a failed cleanup backs off exponentially per generation', () => { + const T0 = Date.parse('2026-07-28T00:00:00.000Z'); + + it('doubles from 1 minute and caps at 1 hour', () => { + expect([1, 2, 3, 4, 6, 7, 8, 50].map(cleanupBackoffMs)).toEqual([ + 60_000, 120_000, 240_000, 480_000, 1_920_000, 3_600_000, 3_600_000, 3_600_000, + ]); + }); + + it('records the attempt and next time on failure, skips until then, and clears both on success', async () => { + const store = makeStore([generation({ stackStartedAt: null })]); + const rec = recorder(); + let fail = true; + let clock = T0; + const deps = makeDeps(store, rec, { + now: () => clock, + removeRepoArtifacts: async (repo) => { + rec.repoArtifacts.push(repo.repoKey); + if (fail) throw new Error('remote unreachable'); + }, + }); + + await cleanupUatGenerations(PROJECT_ROOT, deps); + expect(store.patches).toEqual([[GEN_NAME, { cleanupAttempts: 1, cleanupNextAttemptAt: new Date(T0 + 60_000).toISOString() }]]); + + // Inside the backoff window: not attempted at all. + rec.repoArtifacts.length = 0; + clock = T0 + 59_000; + await cleanupUatGenerations(PROJECT_ROOT, deps); + expect(rec.repoArtifacts).toEqual([]); + expect(store.patches).toHaveLength(1); + + // Past it: attempted, fails again, and waits twice as long. + clock = T0 + 60_000; + await cleanupUatGenerations(PROJECT_ROOT, deps); + expect(rec.repoArtifacts).toEqual(['fe', 'api']); + expect(store.patches[1]).toEqual([GEN_NAME, { cleanupAttempts: 2, cleanupNextAttemptAt: new Date(T0 + 60_000 + 120_000).toISOString() }]); + + // Success clears the backoff with the cleanedAt write. + fail = false; + clock = T0 + 180_000; + await cleanupUatGenerations(PROJECT_ROOT, deps); + const last = store.patches[store.patches.length - 1]!; + expect(last[1]).toMatchObject({ cleanupAttempts: null, cleanupNextAttemptAt: null }); + expect((last[1] as { cleanedAt?: string }).cleanedAt).toBeTruthy(); + }); + + it('measures the backoff from when the attempt failed, not from the start of the tick', async () => { + const store = makeStore([generation({ stackStartedAt: null })]); + const rec = recorder(); + let clock = T0; + await cleanupUatGenerations(PROJECT_ROOT, makeDeps(store, rec, { + now: () => clock, + removeRepoArtifacts: async () => { + clock += 90_000; // a slow failure + throw new Error('remote unreachable'); + }, + })); + // The tick started at T0; the last failure was at T0 + 180 s. + expect(store.patches).toEqual([[GEN_NAME, { cleanupAttempts: 1, cleanupNextAttemptAt: new Date(T0 + 180_000 + 60_000).toISOString() }]]); + }); + + it('also backs off when the stack teardown fails', async () => { + const store = makeStore([generation()]); + const rec = recorder(); + await cleanupUatGenerations(PROJECT_ROOT, makeDeps(store, rec, { + now: () => T0, + teardownStack: async () => { throw new Error('compose down hung'); }, + })); + expect(rec.repoArtifacts).toEqual([]); + expect(store.patches).toEqual([[GEN_NAME, { cleanupAttempts: 1, cleanupNextAttemptAt: new Date(T0 + 60_000).toISOString() }]]); + }); +}); + +describe('PAN-5995: worktree removal treats only git\'s exact "not a working tree" line as already gone', () => { + const failing = (stderr: string) => async () => { throw Object.assign(new Error('Command failed'), { stderr }); }; + const args = ['worktree', 'remove', '--force', `${GEN_FOLDER}/fe`]; + + it('matches git\'s LC_ALL=C message', async () => { + const run = failing(`fatal: '${GEN_FOLDER}/fe' is not a working tree\n`); + await expect(removeOrAlreadyGone(args, '/repo', ALREADY_GONE.worktree, run)).resolves.toBeUndefined(); + }); + + it('rejects other failures that merely mention a missing file or path', async () => { + for (const stderr of [ + "error: failed to delete '/x/.git/worktrees/fe': No such file or directory", + "fatal: validation failed, cannot remove working tree: '/x/fe' does not exist", + 'fatal: cannot change to /x: No such file or directory', + ]) { + await expect(removeOrAlreadyGone(args, '/repo', ALREADY_GONE.worktree, failing(stderr))).rejects.toThrow('failed'); + } + }); +}); + +describe('PAN-5995: the residue sweep refuses repo keys that could leave the generation folder', () => { + it('accepts plain keys and rejects separators and dot-dot', () => { + for (const key of ['fe', 'api', 'my-repo', 'repo.v2']) expect(isSafeResidueRepoKey(key)).toBe(true); + for (const key of ['', '../uat-other', 'a/b', 'a\\b', '..', 'x..y']) expect(isSafeResidueRepoKey(key)).toBe(false); + }); + + it('refuses the whole sweep before any git call when a configured key is unsafe', async () => { + const git = buildPolyrepoCleanupGit([ + { repoKey: '../uat-other', repoPath: `${PROJECT_ROOT}/other`, required: true } as never, + ], PROJECT_ROOT); + await expect(git.removeGenerationResidue({ name: GEN_NAME, worktreePath: GEN_FOLDER }, [])) + .rejects.toThrow('unsafe repo key'); + }); +}); diff --git a/tests/unit/lib/cloister/uat-polyrepo-engine.test.ts b/tests/unit/lib/cloister/uat-polyrepo-engine.test.ts index 724be0d8e80..c9482fa999e 100644 --- a/tests/unit/lib/cloister/uat-polyrepo-engine.test.ts +++ b/tests/unit/lib/cloister/uat-polyrepo-engine.test.ts @@ -281,6 +281,17 @@ describe('assemblePolyrepoUatGeneration — happy path', () => { expect(api.pushes).toEqual([gen.name]); }); + it('PAN-5995: records each published repo\'s uat head, for a resumed promote to check', async () => { + const gen = await assemblePolyrepoUatGeneration( + input(), + deps(new Map([['fe', makeRepoGit('fe')], ['api', makeRepoGit('api')]]), makeStore()), + ); + + expect(gen.repos.map((r) => [r.repoKey, r.headSha])).toEqual( + gen.repos.map((r) => [r.repoKey, expect.stringMatching(new RegExp(`^${r.repoKey}-head-\\d+$`))]), + ); + }); + it('supersedes older ready generations for the project', async () => { const older = { name: 'uat/min-older-0726', projectRoot: PROJECT_ROOT, status: 'ready', @@ -296,6 +307,23 @@ describe('assemblePolyrepoUatGeneration — happy path', () => { expect(store.rows.get('uat/min-older-0726')!.status).toBe('superseded'); }); + + it('PAN-5995: never supersedes a partially promoted ready generation', async () => { + const older = { + name: 'uat/min-older-0726', projectRoot: PROJECT_ROOT, status: 'ready', + worktreePath: '', baseSha: '', members: [], heldOut: [], resolutions: [], + repos: [{ repoKey: 'fe', repoPath: '', branch: 'uat/min-older-0726', baseSha: '', targetBranch: 'main', worktreePath: '', mergeOrder: 0, promotedAt: '2026-07-26T12:00:00.000Z', mergeSha: 'm1' }], + stackStartedAt: null, cleanedAt: null, createdAt: '', updatedAt: '', + } as unknown as UatGeneration; + const store = makeStore([older]); + + await assemblePolyrepoUatGeneration( + input(), + deps(new Map([['fe', makeRepoGit('fe')], ['api', makeRepoGit('api')]]), store), + ); + + expect(store.rows.get('uat/min-older-0726')!.status).toBe('ready'); + }); }); // PAN-5786: a contribution pinned to its reviewed head merges that commit, and the diff --git a/tests/unit/lib/cloister/uat-promote-polyrepo.test.ts b/tests/unit/lib/cloister/uat-promote-polyrepo.test.ts index 169eb312eac..cf809c494c1 100644 --- a/tests/unit/lib/cloister/uat-promote-polyrepo.test.ts +++ b/tests/unit/lib/cloister/uat-promote-polyrepo.test.ts @@ -28,6 +28,8 @@ function repoRow(repoKey: string, mergeOrder: number, overrides: Partial<UatGene baseSha: `${repoKey}-base`, worktreePath: `${PROJECT_ROOT}/workspaces/uat-min-otter-0727/${repoKey}`, mergeOrder, + // PAN-5995: the uat head assembly pushed; the fake origin reports the same by default. + headSha: `${repoKey}-uat-head`, promotedAt: null, ...overrides, }; @@ -71,6 +73,8 @@ interface FakeRepoOptions { failTargetHead?: boolean; /** Merge commit this repo's uat branch is already contained in, if any. */ alreadyLanded?: string; + /** PAN-5995: the uat branch head on origin; null = gone. Defaults to the recorded head. */ + uatHead?: string | null; } function makeRepoGit(repoKey: string, options: FakeRepoOptions = {}): FakeRepoGit { @@ -99,6 +103,7 @@ function makeRepoGit(repoKey: string, options: FakeRepoOptions = {}): FakeRepoGi }, discardPrepared: async (prepared: PreparedRepoMerge) => { discards.push(prepared.handle); }, findLandedMerge: async () => options.alreadyLanded ?? null, + uatBranchHead: async () => (options.uatHead === undefined ? `${repoKey}-uat-head` : options.uatHead), }; } @@ -269,7 +274,8 @@ describe('polyrepo promote — phase B publishes and resumes', () => { repoRow('fe', 0, { promotedAt: '2026-07-27T12:00:00.000Z', mergeSha: 'fe-merge-sha' }), repoRow('api', 1), ]); - const fe = makeRepoGit('fe'); + // PAN-5995: the stamp is confirmed on fe's target before resuming. + const fe = makeRepoGit('fe', { alreadyLanded: 'fe-merge-sha' }); const api = makeRepoGit('api'); const deps = makeDeps(gen, new Map([['fe', fe], ['api', api]])); @@ -292,8 +298,8 @@ describe('polyrepo promote — phase B publishes and resumes', () => { repoRow('fe', 0, { promotedAt: '2026-07-27T12:00:00.000Z', mergeSha: 'fe-merge-sha' }), repoRow('api', 1, { promotedAt: '2026-07-27T12:00:00.000Z', mergeSha: 'api-merge-sha' }), ]); - const fe = makeRepoGit('fe'); - const api = makeRepoGit('api'); + const fe = makeRepoGit('fe', { alreadyLanded: 'fe-merge-sha' }); + const api = makeRepoGit('api', { alreadyLanded: 'api-merge-sha' }); const deps = makeDeps(gen, new Map([['fe', fe], ['api', api]])); const result = await promoteUatGeneration(GEN_NAME, PROJECT_ROOT, deps); @@ -487,7 +493,7 @@ describe('polyrepo promote — recovering an unstamped but landed repo', () => { repoRow('api', 1, { promotedAt: '2026-07-27T09:00:00.000Z', mergeSha: 'api-merge-sha' }), ]); const fe = makeRepoGit('fe', { alreadyLanded: 'fe-recovered' }); - const deps = makeDeps(gen, new Map([['fe', fe], ['api', makeRepoGit('api')]])); + const deps = makeDeps(gen, new Map([['fe', fe], ['api', makeRepoGit('api', { alreadyLanded: 'api-merge-sha' })]])); const result = await promoteUatGeneration(GEN_NAME, PROJECT_ROOT, deps); diff --git a/tests/unit/lib/cloister/uat-promote-resume-git.test.ts b/tests/unit/lib/cloister/uat-promote-resume-git.test.ts new file mode 100644 index 00000000000..491354ac74b --- /dev/null +++ b/tests/unit/lib/cloister/uat-promote-resume-git.test.ts @@ -0,0 +1,117 @@ +/** + * PAN-5995: `uatBranchHead` against real git. A resumed promote compares this + * head with the one assembly recorded, and trialMerge then merges the local + * `origin/<branch>` ref, so the read must refresh that ref from origin rather + * than answer from a stale one, and trialMerge must merge the SHA it was given. + */ +import { execFile } from 'node:child_process'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { buildPolyrepoUatPromoteGitDeps } from '../../../../src/lib/cloister/uat-promote.js'; + +const run = promisify(execFile); +const git = async (cwd: string, ...args: string[]) => (await run('git', args, { cwd })).stdout.trim(); +const BRANCH = 'uat/min-otter-1203'; + +let root: string; + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'uat-resume-git-')); +}); + +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +async function commit(repo: string, file: string): Promise<string> { + await writeFile(join(repo, file), file); + await git(repo, 'add', file); + await git(repo, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', file); + return git(repo, 'rev-parse', 'HEAD'); +} + +describe('PAN-5995: uatBranchHead', () => { + it('reads the head from a fresh fetch and refreshes the ref trialMerge merges', async () => { + const origin = join(root, 'origin.git'); + await git(root, 'init', '-q', '--bare', '-b', 'main', origin); + const assembler = join(root, 'assembler'); + await git(root, 'clone', '-q', origin, assembler); + await commit(assembler, 'base.txt'); + await git(assembler, 'push', '-q', 'origin', 'HEAD:main'); + await git(assembler, 'checkout', '-q', '-b', BRANCH); + const assembled = await commit(assembler, 'batch.txt'); + await git(assembler, 'push', '-q', 'origin', BRANCH); + + // The promoting checkout fetched the branch at assembly time... + const promoter = join(root, 'promoter'); + await git(root, 'clone', '-q', origin, promoter); + // A real promoting checkout has a committer identity; the trial merge commits. + await git(promoter, 'config', 'user.name', 't'); + await git(promoter, 'config', 'user.email', 't@t'); + expect(await git(promoter, 'rev-parse', `origin/${BRANCH}`)).toBe(assembled); + // ...and then someone pushed to it. + const later = await commit(assembler, 'late.txt'); + await git(assembler, 'push', '-q', 'origin', BRANCH); + + const deps = buildPolyrepoUatPromoteGitDeps([{ repoKey: 'api', repoPath: promoter }]).get('api')!; + + expect(await deps.uatBranchHead!(BRANCH)).toBe(later); + expect(await git(promoter, 'rev-parse', `origin/${BRANCH}`)).toBe(later); + + // Given the verified SHA, the trial merge merges that commit, not what the ref names now. + const prepared = await deps.trialMerge(BRANCH, 'Merge UAT batch', assembled); + try { + expect(await git(prepared.handle, 'rev-parse', 'HEAD^2')).toBe(assembled); + } finally { + await deps.discardPrepared(prepared); + } + }); + + it('findLandedMerge judges the recorded head: a rewritten uat tip that landed is not the tested batch', async () => { + const origin = join(root, 'origin.git'); + await git(root, 'init', '-q', '--bare', '-b', 'main', origin); + const work = join(root, 'work'); + await git(root, 'clone', '-q', origin, work); + await git(work, 'config', 'user.name', 't'); + await git(work, 'config', 'user.email', 't@t'); + await commit(work, 'base.txt'); + await git(work, 'push', '-q', 'origin', 'HEAD:main'); + // Assembly pushed the batch at A and recorded A. + await git(work, 'checkout', '-q', '-b', BRANCH); + const assembled = await commit(work, 'batch.txt'); + await git(work, 'push', '-q', 'origin', BRANCH); + // The uat branch is force-pushed to an unrelated B, and B lands on main. + await git(work, 'checkout', '-q', 'main'); + await git(work, 'checkout', '-q', '-b', 'rewrite'); + const rewritten = await commit(work, 'other.txt'); + await git(work, 'push', '-q', '--force', 'origin', `HEAD:${BRANCH}`); + await git(work, 'checkout', '-q', 'main'); + await git(work, 'merge', '-q', '--no-ff', '-m', 'land B', rewritten); + await git(work, 'push', '-q', 'origin', 'main'); + + const promoter = join(root, 'promoter'); + await git(root, 'clone', '-q', origin, promoter); + const deps = buildPolyrepoUatPromoteGitDeps([{ repoKey: 'api', repoPath: promoter }]).get('api')!; + + // A is not in main, and the tip is not A: not landed. + expect(await deps.findLandedMerge(BRANCH, assembled)).toBeNull(); + // Control: judged at B, the same branch does read as landed. + expect(await deps.findLandedMerge(BRANCH, rewritten)).toMatch(/^[0-9a-f]{40}$/); + }); + + it('answers null when the branch is gone from origin', async () => { + const origin = join(root, 'origin.git'); + await git(root, 'init', '-q', '--bare', '-b', 'main', origin); + const clone = join(root, 'clone'); + await git(root, 'clone', '-q', origin, clone); + await commit(clone, 'base.txt'); + await git(clone, 'push', '-q', 'origin', 'HEAD:main'); + + const deps = buildPolyrepoUatPromoteGitDeps([{ repoKey: 'api', repoPath: clone }]).get('api')!; + + expect(await deps.uatBranchHead!(BRANCH)).toBeNull(); + }); +}); diff --git a/tests/unit/lib/cloister/uat-promote.test.ts b/tests/unit/lib/cloister/uat-promote.test.ts index 0c3831138f3..26e18f0549b 100644 --- a/tests/unit/lib/cloister/uat-promote.test.ts +++ b/tests/unit/lib/cloister/uat-promote.test.ts @@ -133,6 +133,54 @@ describe('promoteUatGeneration — success', () => { ]); }); + it('PAN-5995: never voids a partially promoted sibling', async () => { + const landedFe = [{ + repoKey: 'fe', repoPath: '/proj/fe', branch: 'uat/pan-older-0610', baseSha: 'a', targetBranch: 'main', + worktreePath: '/proj/workspaces/uat-pan-older-0610/fe', mergeOrder: 0, promotedAt: '2026-06-10T02:45:00.000Z', mergeSha: 'm1', + }]; + const deps = makeDeps([ + gen('uat/pan-newest-0610', 'ready', { createdAt: '2026-06-10T03:00:00.000Z' }), + gen('uat/pan-older-0610', 'superseded', { createdAt: '2026-06-10T02:00:00.000Z', repos: landedFe }), + ]); + + const result = await promoteUatGeneration('uat/pan-newest-0610', PROJ, deps); + + expect(result.success).toBe(true); + if (!result.success) return; + expect(result.invalidated).toEqual([]); + expect(deps.map.get('uat/pan-older-0610')!.status).toBe('superseded'); + expect(deps.teardowns).not.toContain('uat/pan-older-0610'); + }); + + it('PAN-5995: re-reads each sibling, so one stamped during an earlier teardown is not voided', async () => { + const deps = makeDeps([ + gen('uat/pan-newest-0610', 'ready', { createdAt: '2026-06-10T03:00:00.000Z' }), + gen('uat/pan-older-0610', 'superseded', { createdAt: '2026-06-10T02:00:00.000Z' }), + gen('uat/pan-oldest-0610', 'superseded', { createdAt: '2026-06-10T01:00:00.000Z' }), + ]); + // While pan-older's stack comes down, a promote of pan-oldest lands its fe repo. + deps.teardownStack = async (g) => { + deps.teardowns.push(g.name); + if (g.name === 'uat/pan-older-0610') { + deps.map.set('uat/pan-oldest-0610', gen('uat/pan-oldest-0610', 'superseded', { + createdAt: '2026-06-10T01:00:00.000Z', + repos: [{ + repoKey: 'fe', repoPath: '/proj/fe', branch: 'uat/pan-oldest-0610', baseSha: 'a', targetBranch: 'main', + worktreePath: '/proj/workspaces/uat-pan-oldest-0610/fe', mergeOrder: 0, promotedAt: '2026-06-10T03:30:00.000Z', mergeSha: 'm1', + }], + })); + } + }; + + const result = await promoteUatGeneration('uat/pan-newest-0610', PROJ, deps); + + expect(result.success).toBe(true); + if (!result.success) return; + expect(result.invalidated).toEqual(['uat/pan-older-0610']); + expect(deps.map.get('uat/pan-oldest-0610')!.status).toBe('superseded'); + expect(deps.teardowns).not.toContain('uat/pan-oldest-0610'); + }); + it('invalidates every other live generation (main moved) and tears their stacks down', async () => { const deps = makeDeps([ gen('uat/pan-newest-0610', 'ready', { createdAt: '2026-06-10T03:00:00.000Z' }), diff --git a/tests/unit/lib/cloister/uat-reconciler.test.ts b/tests/unit/lib/cloister/uat-reconciler.test.ts index d3ddc942720..58da462059e 100644 --- a/tests/unit/lib/cloister/uat-reconciler.test.ts +++ b/tests/unit/lib/cloister/uat-reconciler.test.ts @@ -1123,3 +1123,173 @@ describe('PAN-5966: a generation a promote is merging is never touched', () => { } }); }); + +describe('PAN-5995: a partially promoted generation survives a restart mid-promote', () => { + const name = 'uat/min-otter-1203'; + // A promote landed fe, then the dashboard restarted: fe carries promoted_at, + // api does not, and the in-process promoting set is empty. + const partialGen = (proj: string, status: UatGenerationStatus = 'ready') => gen(proj, name, status, { + repos: [ + { repoKey: 'fe', repoPath: `${proj}/fe`, branch: name, baseSha: 'fe-base', targetBranch: 'main', worktreePath: `${proj}/workspaces/uat-x/fe`, mergeOrder: 0, promotedAt: '2026-06-10T11:30:00.000Z', mergeSha: 'fe-merge' }, + { repoKey: 'api', repoPath: `${proj}/api`, branch: name, baseSha: 'api-base', targetBranch: 'main', worktreePath: `${proj}/workspaces/uat-x/api`, mergeOrder: 1, promotedAt: null, mergeSha: null }, + ], + }); + + it('is neither invalidated nor torn down, train on or off, even with merge evidence for a member', async () => { + for (const enabled of [true, false]) { + const proj = freshProject(); + // PAN-1 left the ready set and its PR reads merged: without the guard both paths invalidate. + const deps = makeDeps(proj, { enabled, rows: [partialGen(proj)], readySet: [READY[1]!] }); + deps.mergedIssueIds = async () => new Set(['PAN-1']); + deps.departureEvidence = async () => 'has no open PR or MR any more (closed or merged)'; + + const result = await reconcileUatGenerations(proj, deps); + + expect(result.invalidated).toEqual([]); + expect(deps.rows.get(name)!.status).toBe('ready'); + expect(deps.teardowns).toEqual([]); + expect(deps.logs).toContain(`[uat-reconciler] ${name}: partially promoted: resume promote`); + } + }); + + it('holds assembly for the project, even when forced, and releases once the promote completes', async () => { + const proj = freshProject(); + const other: ReadyFeature[] = [ + { issueId: 'PAN-3', title: 'Third', branch: 'feature/pan-3' }, + { issueId: 'PAN-4', title: 'Fourth', branch: 'feature/pan-4' }, + ]; + const deps = makeDeps(proj, { rows: [partialGen(proj)], readySet: other }); + + for (const force of [false, true]) { + const result = await reconcileUatGenerations(proj, deps, { force }); + expect(result.action).toBe('partially-promoted'); + } + expect(deps.assembled).toEqual([]); + expect(deps.rows.get(name)!.status).toBe('ready'); + expect(deps.teardowns).toEqual([]); + + // The resumed promote finishes: the row reads promoted, and the hold lifts. + deps.store.update(name, { status: 'promoted' }); + const after = await reconcileUatGenerations(proj, deps); + expect(after.action).toBe('assembled'); + expect(deps.assembled).toEqual([other]); + }); + + it('does not stamp promoted when a promote stamped a repo during the containment read (CodeRabbit 4795343750)', async () => { + const proj = freshProject(); + const plain = gen(proj, name, 'ready', { repos: partialGen(proj).repos!.map((r) => ({ ...r, promotedAt: null, mergeSha: null })) }); + const deps = makeDeps(proj, { rows: [plain], readySet: READY }); + deps.isGenerationContainedInMain = async () => { + deps.rows.set(name, partialGen(proj)); // fe landed and was stamped while git answered + return true; + }; + + await reconcileUatGenerations(proj, deps); + + expect(deps.rows.get(name)!.status).toBe('ready'); + expect(deps.logs).toContain(`[uat-reconciler] ${name}: partially promoted: resume promote`); + }); + + it('holds for a partially promoted batch the scan skipped because its promote is in flight (CodeRabbit 4795343754)', async () => { + const proj = freshProject(); + const other: ReadyFeature[] = [ + { issueId: 'PAN-3', title: 'Third', branch: 'feature/pan-3' }, + { issueId: 'PAN-4', title: 'Fourth', branch: 'feature/pan-4' }, + ]; + const deps = makeDeps(proj, { rows: [partialGen(proj)], readySet: other }); + + const result = await withUatGenerationPromoting(name, () => reconcileUatGenerations(proj, deps)); + + expect(result.action).toBe('partially-promoted'); + expect(deps.assembled).toEqual([]); + }); + + it('holds when a repo is stamped during the batch-window read, the last await before assembly (CodeRabbit 4795343754)', async () => { + const proj = freshProject(); + const plain = gen(proj, name, 'ready', { repos: partialGen(proj).repos!.map((r) => ({ ...r, promotedAt: null, mergeSha: null })) }); + const third: ReadyFeature = { issueId: 'PAN-3', title: 'Third', branch: 'feature/pan-3' }; + const deps = makeDeps(proj, { rows: [plain], readySet: [...READY, third], headShas: { 'feature/pan-3': 'h3' } }); + deps.selectBatch = async (batchReadySet) => { + deps.rows.set(name, partialGen(proj)); // a promote of the live batch stamped fe meanwhile + return { features: [...batchReadySet] }; + }; + + const result = await reconcileUatGenerations(proj, deps); + + expect(result.action).toBe('partially-promoted'); + expect(deps.assembled).toEqual([]); + expect(deps.rows.get(name)!.status).toBe('ready'); + }); + + it('releases the hold once the operator abandons it (invalidated): new batches assemble again', async () => { + const proj = freshProject(); + const other: ReadyFeature[] = [ + { issueId: 'PAN-3', title: 'Third', branch: 'feature/pan-3' }, + { issueId: 'PAN-4', title: 'Fourth', branch: 'feature/pan-4' }, + ]; + const deps = makeDeps(proj, { rows: [partialGen(proj)], readySet: other }); + expect((await reconcileUatGenerations(proj, deps)).action).toBe('partially-promoted'); + + deps.store.update(name, { status: 'invalidated', statusReason: 'abandoned by the operator while partially promoted' }); + const after = await reconcileUatGenerations(proj, deps); + + expect(after.action).toBe('assembled'); + expect(deps.assembled).toEqual([other]); + // Its landed repo's stamp is left as the record. + expect(deps.rows.get(name)!.repos![0]!.promotedAt).toBe('2026-06-10T11:30:00.000Z'); + }); + + it('is not stamped promoted even when every repo is contained: the resumed promote finalizes it and runs post-merge', async () => { + const proj = freshProject(); + const deps = makeDeps(proj, { rows: [partialGen(proj)], readySet: [], containedNames: [name] }); + + await reconcileUatGenerations(proj, deps); + + expect(deps.rows.get(name)!.status).toBe('ready'); + expect(deps.teardowns).toEqual([]); + }); + + it('re-reads the row before invalidating, so a stamp written during the reads keeps it', async () => { + const proj = freshProject(); + const plain = gen(proj, name, 'ready', { repos: partialGen(proj).repos!.map((r) => ({ ...r, promotedAt: null, mergeSha: null })) }); + const deps = makeDeps(proj, { enabled: false, rows: [plain], readySet: [READY[1]!] }); + // A promote stamps fe while the departure read is in flight, then stops. + deps.departureEvidence = async () => { + deps.rows.set(name, partialGen(proj)); + return 'has no open PR or MR any more (closed or merged)'; + }; + + const result = await reconcileUatGenerations(proj, deps); + + expect(result.invalidated).toEqual([]); + expect(deps.rows.get(name)!.status).toBe('ready'); + expect(deps.teardowns).toEqual([]); + }); +}); + +describe('PAN-5995: train off checks the ready set before merge evidence', () => { + it('keeps a batch whose member is ready now, even though an older PR on its reused branch merged', async () => { + const proj = freshProject(); + const name = 'uat/pan-otter-1203'; + const deps = makeDeps(proj, { enabled: false, rows: [gen(proj, name, 'ready')] }); + deps.mergedIssueIds = async () => new Set(['PAN-1']); + + const result = await reconcileUatGenerations(proj, deps); + + expect(result.invalidated).toEqual([]); + expect(deps.rows.get(name)!.status).toBe('ready'); + expect(deps.teardowns).toEqual([]); + }); + + it('still invalidates a member that merged and left the ready set', async () => { + const proj = freshProject(); + const name = 'uat/pan-otter-1203'; + const deps = makeDeps(proj, { enabled: false, rows: [gen(proj, name, 'ready')], readySet: [READY[1]!] }); + deps.mergedIssueIds = async () => new Set(['PAN-1']); + + const result = await reconcileUatGenerations(proj, deps); + + expect(result.invalidated).toEqual([name]); + expect(deps.rows.get(name)!.statusReason).toBe('PAN-1 was merged on its own, outside the batch'); + }); +}); diff --git a/tests/unit/lib/overdeck/merge-sync-uat-generations.test.ts b/tests/unit/lib/overdeck/merge-sync-uat-generations.test.ts index e5711728d0a..5dfe46abf35 100644 --- a/tests/unit/lib/overdeck/merge-sync-uat-generations.test.ts +++ b/tests/unit/lib/overdeck/merge-sync-uat-generations.test.ts @@ -258,6 +258,34 @@ describe('updateUatGeneration patch', () => { expect(Date.parse(getUatGeneration(gen.name)!.updatedAt)).toBeGreaterThan(failedAtMs); }); + it('round-trips the cleanup backoff and never moves updated_at for it (PAN-5995)', () => { + const db = odb.raw(); + seedIssue(db, 'PAN-1'); + seedIssue(db, 'PAN-2'); + + const gen = makeGeneration(); + insertUatGeneration(gen); + updateUatGeneration(gen.name, { status: 'superseded' }); + const supersededAtMs = Date.parse('2026-09-20T18:20:00.000Z'); + db.prepare('UPDATE uat_generations SET updated_at = ? WHERE name = ?').run(supersededAtMs, gen.name); + expect(getUatGeneration(gen.name)).toMatchObject({ cleanupAttempts: null, cleanupNextAttemptAt: null }); + + // A failed cleanup must not restart the superseded grace period. + updateUatGeneration(gen.name, { cleanupAttempts: 2, cleanupNextAttemptAt: '2026-09-20T19:16:00.000Z' }); + expect(getUatGeneration(gen.name)).toMatchObject({ + cleanupAttempts: 2, + cleanupNextAttemptAt: '2026-09-20T19:16:00.000Z', + updatedAt: '2026-09-20T18:20:00.000Z', + }); + + updateUatGeneration(gen.name, { cleanedAt: '2026-09-20T19:20:00.000Z', cleanupAttempts: null, cleanupNextAttemptAt: null }); + expect(getUatGeneration(gen.name)).toMatchObject({ + cleanupAttempts: null, + cleanupNextAttemptAt: null, + updatedAt: '2026-09-20T18:20:00.000Z', + }); + }); + it('writes and reads back voidedBy; a fresh row reads null (PAN-5364)', () => { const db = odb.raw(); seedIssue(db, 'PAN-1'); diff --git a/tests/unit/lib/overdeck/uat-generation-repos.test.ts b/tests/unit/lib/overdeck/uat-generation-repos.test.ts index 6c49903677c..1d7fbedc1de 100644 --- a/tests/unit/lib/overdeck/uat-generation-repos.test.ts +++ b/tests/unit/lib/overdeck/uat-generation-repos.test.ts @@ -326,6 +326,20 @@ describe('per-repo target branch and merge sha', () => { expect(fe.mergeSha).toBe('fe1234567890'); }); + it('round-trips the uat head assembly pushed, and keeps it through a promote stamp (PAN-5995)', async () => { + const db = odb.raw(); + seedIssue(db, 'MIN-901'); + seedIssue(db, 'MIN-902'); + const gen = makePolyrepoGeneration(); + insertUatGeneration({ ...gen, repos: gen.repos!.map((r) => ({ ...r, headSha: `${r.repoKey}-uat-head` })) }); + + markUatGenerationRepoPromoted(gen.name, 'fe', '2026-07-27T10:00:00.000Z', 'fe1234567890'); + + expect(getUatGeneration(gen.name)!.repos!.map((r) => [r.repoKey, r.headSha])).toEqual( + gen.repos!.map((r) => [r.repoKey, `${r.repoKey}-uat-head`]), + ); + }); + it('keeps an existing merge sha when a later stamp omits it', async () => { const db = odb.raw(); seedIssue(db, 'MIN-901');