Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 49 additions & 10 deletions pm-stack/dispatch/src/launch_failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -26,27 +24,68 @@ export interface LaunchFailureGitHub {
comment(repo: string, issueNumber: number, body: string): Promise<void>;
}

/** 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<T>(
sessionId: string,
context: LaunchFailureContext,
launch: () => Promise<T>,
): Promise<T> {
context.sessionId = sessionId;
return launch();
}

export async function handleLaunchFailure(
queue: LaunchFailureQueue,
github: LaunchFailureGitHub,
repo: string,
taskId: number,
issueNumber: number | null,
e: unknown,
sessionId: string | null = null,
deleteSession?: (sessionId: string) => Promise<void>,
): Promise<string> {
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 {
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/dispatch/src/opencode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ export class OpenCodeClient {
await this.api("POST", `/api/session/${encodeURIComponent(sessionId)}/prompt`, { text });
}

async deleteSession(sessionId: string): Promise<void> {
await this.api("DELETE", `/api/session/${encodeURIComponent(sessionId)}`);
}

async listSessions(): Promise<unknown> {
return this.api("GET", "/api/session");
}
Expand Down
75 changes: 51 additions & 24 deletions pm-stack/dispatch/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -113,33 +113,40 @@ async function launchSession(
issue: IssueRef | null,
directory: string,
warnings: string[],
failureContext: LaunchFailureContext,
): Promise<string> {
const session = await opencode.createSession({
directory,
title: req.title ?? titleFromPrompt(req.prompt),
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
Expand Down Expand Up @@ -232,14 +239,24 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise<Res
// 3-5. Launch + assign. wait=false: answer after the enqueue and finish
// the launch asynchronously, recording the outcome on the task row.
if (!body.wait) {
const failureContext: LaunchFailureContext = { sessionId: null };
void (async () => {
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, {
Expand All @@ -252,13 +269,23 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise<Res
}

let sessionId: string;
const failureContext: LaunchFailureContext = { sessionId: null };
try {
sessionId = await launchSession(caller, body, task, issue, directory, warnings);
sessionId = await launchSession(caller, body, task, issue, directory, warnings, failureContext);
} catch (e) {
// Never leave a queued/claimed task behind for a session that did
// not launch: cancel it and note the failure on the issue (the
// shared handler the wait:false path also uses, #2901).
const msg = await handleLaunchFailure(requireQueue(), github, body.repo, task.id, issue?.number ?? null, e);
const msg = await handleLaunchFailure(
requireQueue(),
github,
body.repo,
task.id,
issue?.number ?? null,
e,
failureContext.sessionId,
(sessionId) => opencode.deleteSession(sessionId),
);
return json(502, { task_id: task.id, error: msg, ...(warnings.length ? { warnings } : {}) });
}

Expand Down
90 changes: 89 additions & 1 deletion pm-stack/dispatch/test/launch_failure.test.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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<void> {
if (stage === "sendPrompt") throw launchError;
},
async deleteSession(id: string): Promise<void> {
calls.events.push("delete");
calls.deleted.push(id);
throw new Error("delete failed");
},
};
const queue = {
async ensureWorker(): Promise<void> {},
async patchTask(): Promise<void> {
if (stage === "claim patch") throw launchError;
},
async cancelTask(id: number, reason: string): Promise<void> {
calls.events.push("cancel");
calls.cancels.push([id, reason]);
},
};
const github = {
async comment(repo: string, issueNumber: number, body: string): Promise<void> {
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");
});
});
Loading