diff --git a/pm-stack/dispatch/src/launch_failure.ts b/pm-stack/dispatch/src/launch_failure.ts index 2ea70c36eb..65c7b1c030 100644 --- a/pm-stack/dispatch/src/launch_failure.ts +++ b/pm-stack/dispatch/src/launch_failure.ts @@ -8,13 +8,11 @@ // both paths now call this one helper, and the async path cannot // drift from the synchronous one again. // -// Both steps are best-effort: a cancellation failure does not suppress -// the issue note, and neither failure suppresses the other. The note -// reports each step's actual outcome: it claims the task was cancelled -// only when the cancellation succeeded; when cancellation failed it -// says so and names the cancellation error, so a task that may still -// be queued or claimed is never recorded as cleaned up. The message -// is returned so the wait:true path can put it in its 502. +// Failure handling records cancellation first, then attempts session +// cleanup, then notes the issue. Each is best-effort: failure of one does +// not suppress the next. The note reports the cancellation and cleanup +// outcomes, and the original launch error is returned for the wait:true +// path's 502. /** The slice of the queue client launch-failure handling needs. */ export interface LaunchFailureQueue { @@ -26,6 +24,25 @@ export interface LaunchFailureGitHub { comment(repo: string, issueNumber: number, body: string): Promise; } +/** Mutable context shared by launchSession and its failure handler. */ +export interface LaunchFailureContext { + sessionId: string | null; +} + +/** + * Run the part of a launch that follows successful session creation. + * Retain the new session ID so the failure handler can record it before + * attempting cleanup. + */ +export async function withCreatedSession( + sessionId: string, + context: LaunchFailureContext, + launch: () => Promise, +): Promise { + context.sessionId = sessionId; + return launch(); +} + export async function handleLaunchFailure( queue: LaunchFailureQueue, github: LaunchFailureGitHub, @@ -33,20 +50,42 @@ export async function handleLaunchFailure( taskId: number, issueNumber: number | null, e: unknown, + sessionId: string | null = null, + deleteSession?: (sessionId: string) => Promise, ): Promise { const msg = e instanceof Error ? e.message : String(e); + const sessionContext = sessionId == null + ? "" + : `; OpenCode session ${sessionId} may still be live`; let cancelError: string | null = null; try { - await queue.cancelTask(taskId, `dispatch launch failed: ${msg}`); + await queue.cancelTask(taskId, `dispatch launch failed: ${msg}${sessionContext}`); } catch (ce) { /* cancellation failed too — the note below must say so, not claim success */ cancelError = ce instanceof Error ? ce.message : String(ce); } + let cleanupError: string | null = null; + if (sessionId != null) { + if (!deleteSession) { + cleanupError = "session deletion callback unavailable"; + } else { + try { + await deleteSession(sessionId); + } catch (de) { + cleanupError = de instanceof Error ? de.message : String(de); + } + } + } if (issueNumber != null) { + const sessionNote = sessionId == null + ? "" + : cleanupError == null + ? `\n\nOpenCode session ${sessionId} may still be live; session cleanup succeeded.` + : `\n\nOpenCode session ${sessionId} may still be live; session cleanup failed: ${cleanupError}`; const note = cancelError == null - ? `Dispatch launch FAILED and queue task #${taskId} was cancelled.\n\nError: ${msg}` - : `Dispatch launch FAILED and cancelling queue task #${taskId} FAILED — the task may still be queued or claimed and needs cleanup.\n\nError: ${msg}\nCancellation error: ${cancelError}`; + ? `Dispatch launch FAILED and queue task #${taskId} was cancelled.${sessionNote}\n\nError: ${msg}` + : `Dispatch launch FAILED and cancelling queue task #${taskId} FAILED — the task may still be queued or claimed and needs cleanup.${sessionNote}\n\nError: ${msg}\nCancellation error: ${cancelError}`; try { await github.comment(repo, issueNumber, note); } catch { diff --git a/pm-stack/dispatch/src/opencode.ts b/pm-stack/dispatch/src/opencode.ts index 5bb628a834..9a94be4eeb 100644 --- a/pm-stack/dispatch/src/opencode.ts +++ b/pm-stack/dispatch/src/opencode.ts @@ -70,6 +70,10 @@ export class OpenCodeClient { await this.api("POST", `/api/session/${encodeURIComponent(sessionId)}/prompt`, { text }); } + async deleteSession(sessionId: string): Promise { + await this.api("DELETE", `/api/session/${encodeURIComponent(sessionId)}`); + } + async listSessions(): Promise { return this.api("GET", "/api/session"); } diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index df548d7ef7..d3e9cf79f8 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -31,7 +31,7 @@ import { validatePayload, } from "./packet.ts"; import { QueueClient, QueueError, type TaskRow } from "./queue.ts"; -import { handleLaunchFailure } from "./launch_failure.ts"; +import { handleLaunchFailure, withCreatedSession, type LaunchFailureContext } from "./launch_failure.ts"; import { annotateLaunch } from "./launch_annotations.ts"; import { GitHubClient } from "./github.ts"; import { OpenCodeClient } from "./opencode.ts"; @@ -113,6 +113,7 @@ async function launchSession( issue: IssueRef | null, directory: string, warnings: string[], + failureContext: LaunchFailureContext, ): Promise { const session = await opencode.createSession({ directory, @@ -120,26 +121,32 @@ async function launchSession( model: req.model, }); const prefix = `[dispatch] Queue task #${task.id} · Issue ${issue ? issue.url : "none"} · Repo ${req.repo}`; - await opencode.sendPrompt(session.id, `${prefix}\n\n${req.prompt}`); - - // Assign immediately: PATCH the exact row the enqueue created (the - // claim RPC claims the next task in a queue, not a specific one). The - // worker identity must exist in agent.workers first (worker_id is an - // FK), so register it idempotently. - await requireQueue().ensureWorker(); - const now = new Date(); - await requireQueue().patchTask(task.id, { - status: "claimed", - worker_id: "dispatch-opencode", - claimed_at: now.toISOString(), - lease_until: new Date(now.getTime() + LEASE_SECONDS * 1000).toISOString(), - progress: { - lane: "opencode", - session_id: session.id, - issue_number: issue?.number ?? null, - launched_by: caller, + await withCreatedSession( + session.id, + failureContext, + async () => { + await opencode.sendPrompt(session.id, `${prefix}\n\n${req.prompt}`); + + // Assign immediately: PATCH the exact row the enqueue created (the + // claim RPC claims the next task in a queue, not a specific one). The + // worker identity must exist in agent.workers first (worker_id is an + // FK), so register it idempotently. + await requireQueue().ensureWorker(); + const now = new Date(); + await requireQueue().patchTask(task.id, { + status: "claimed", + worker_id: "dispatch-opencode", + claimed_at: now.toISOString(), + lease_until: new Date(now.getTime() + LEASE_SECONDS * 1000).toISOString(), + progress: { + lane: "opencode", + session_id: session.id, + issue_number: issue?.number ?? null, + launched_by: caller, + }, + }); }, - }); + ); // Lane ledger: the same assignment the queue workers record after a // claim, so a later completion can record the executed lane. The @@ -232,14 +239,24 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise { try { - await launchSession(caller, body, task, issue, directory, warnings); + await launchSession(caller, body, task, issue, directory, warnings, failureContext); } catch (e) { // Mirror the wait:true failure path exactly (#2901): cancel the // task and note the failure on the issue — never leave a queued // task behind for a session that did not launch. - await handleLaunchFailure(requireQueue(), github, body.repo, task.id, issue?.number ?? null, e); + await handleLaunchFailure( + requireQueue(), + github, + body.repo, + task.id, + issue?.number ?? null, + e, + failureContext.sessionId, + (sessionId) => opencode.deleteSession(sessionId), + ); } })(); return json(202, { @@ -252,13 +269,23 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise opencode.deleteSession(sessionId), + ); return json(502, { task_id: task.id, error: msg, ...(warnings.length ? { warnings } : {}) }); } diff --git a/pm-stack/dispatch/test/launch_failure.test.ts b/pm-stack/dispatch/test/launch_failure.test.ts index 55994a5400..23e72eb0bc 100644 --- a/pm-stack/dispatch/test/launch_failure.test.ts +++ b/pm-stack/dispatch/test/launch_failure.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { handleLaunchFailure } from "../src/launch_failure.ts"; +import { handleLaunchFailure, withCreatedSession } from "../src/launch_failure.ts"; // Regression tests for #2901: a wait:false launch failure used to only // PATCH last_error onto the task, leaving it queued forever. Both wait @@ -68,4 +68,92 @@ describe("handleLaunchFailure", () => { expect(calls.comments[0][2]).toContain("Cancellation error: queue unreachable"); expect(calls.comments[0][2]).not.toContain("was cancelled"); }); + + async function assertCreatedSessionFailure(stage: "sendPrompt" | "claim patch") { + const sessionId = "session/created-42"; + const launchError = new Error(`${stage} failed`); + const context = { sessionId: null as string | null }; + const calls = { + deleted: [] as string[], + cancels: [] as [number, string][], + comments: [] as [string, number, string][], + events: [] as string[], + }; + const opencode = { + async createSession(): Promise<{ id: string }> { + return { id: sessionId }; + }, + async sendPrompt(): Promise { + if (stage === "sendPrompt") throw launchError; + }, + async deleteSession(id: string): Promise { + calls.events.push("delete"); + calls.deleted.push(id); + throw new Error("delete failed"); + }, + }; + const queue = { + async ensureWorker(): Promise {}, + async patchTask(): Promise { + if (stage === "claim patch") throw launchError; + }, + async cancelTask(id: number, reason: string): Promise { + calls.events.push("cancel"); + calls.cancels.push([id, reason]); + }, + }; + const github = { + async comment(repo: string, issueNumber: number, body: string): Promise { + calls.events.push("comment"); + calls.comments.push([repo, issueNumber, body]); + }, + }; + + // Model the real order: session creation succeeds before the guarded + // prompt / worker / claim steps run. + const session = await opencode.createSession(); + let thrown: unknown; + try { + await withCreatedSession(session.id, context, async () => { + await opencode.sendPrompt(); + await queue.ensureWorker(); + await queue.patchTask(); + }); + } catch (e) { + thrown = e; + } + + expect(thrown).toBe(launchError); + expect(context.sessionId).toBe(sessionId); + expect(calls.deleted).toEqual([]); + + const msg = await handleLaunchFailure( + queue, + github, + "developing-today/code", + 4135, + 2901, + thrown, + context.sessionId, + (id) => opencode.deleteSession(id), + ); + expect(msg).toBe(launchError.message); + expect(calls.cancels).toEqual([ + [4135, `dispatch launch failed: ${launchError.message}; OpenCode session ${sessionId} may still be live`], + ]); + expect(calls.comments).toHaveLength(1); + expect(calls.comments[0][2]).toContain(`OpenCode session ${sessionId} may still be live`); + expect(calls.comments[0][2]).toContain("session cleanup failed: delete failed"); + expect(calls.comments[0][2]).toContain(launchError.message); + expect(calls.deleted).toEqual([sessionId]); + expect(calls.events).toEqual(["cancel", "delete", "comment"]); + } + + test("created session is cleaned up and reported after sendPrompt fails", async () => { + await assertCreatedSessionFailure("sendPrompt"); + }); + + test("created session is cleaned up and reported after claim patch fails", async () => { + await assertCreatedSessionFailure("claim patch"); + }); });