From 55644740e30974d05dd52f7e9a764c8cac33cf0a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 18:40:58 -0600 Subject: [PATCH] fix(pm-dispatch): reconcile timed-out queue claim flow --- pm-stack/dispatch/src/queue.ts | 86 +++++++++++++++++++++++++--- pm-stack/dispatch/test/queue.test.ts | 44 ++++++++++++++ 2 files changed, 123 insertions(+), 7 deletions(-) diff --git a/pm-stack/dispatch/src/queue.ts b/pm-stack/dispatch/src/queue.ts index 57374f7b7d..76136b14f7 100644 --- a/pm-stack/dispatch/src/queue.ts +++ b/pm-stack/dispatch/src/queue.ts @@ -20,13 +20,15 @@ // assignLane -> POST /lane {task_id, worker} import type { Packet } from "./packet.ts"; import { REPO_QUEUES } from "./config.ts"; -import { outboundTimeout } from "./fetchTimeout.ts"; +import { OUTBOUND_FETCH_TIMEOUT_MS, outboundTimeout } from "./fetchTimeout.ts"; export class QueueError extends Error { status = 502; constructor( message: string, readonly httpStatus?: number, + /** The request may have committed even though its response was lost. */ + readonly outcomeUnknown = false, ) { super(message); } @@ -62,6 +64,19 @@ function isTaskRow(v: unknown): v is TaskRow { return typeof v === "object" && v !== null && !Array.isArray(v) && typeof (v as { id?: unknown }).id === "number"; } +/** A rich row is proof that this dispatch's claim committed only when + * the live status and the session id both match the request we just made. */ +function claimBelongsToSession(row: TaskRow | null, sessionId: string): row is TaskRow { + if (row?.status !== "claimed") return false; + const progress = row.progress; + return ( + typeof progress === "object" && + progress !== null && + !Array.isArray(progress) && + (progress as Record).session_id === sessionId + ); +} + interface BrokerEnvelope { ok?: unknown; row?: unknown; @@ -73,6 +88,12 @@ interface BrokerEnvelope { export const DISPATCH_WORKER = "dispatch-opencode"; +// claim-flow performs three broker writes (claim, lane, bind) before it +// answers. Give that bounded composite route more time than a read or a +// single write; if the response still gets lost, claimTask reconciles by +// task + session before launch compensation can cancel a committed claim. +const CLAIM_FLOW_TIMEOUT_MS = 30_000; + export class QueueClient { constructor( private brokerUrl: string, @@ -82,8 +103,13 @@ export class QueueClient { /** One broker round trip. Throws QueueError on a transport failure, * a non-OK HTTP status, a non-JSON body, or an {ok: false} envelope * (the broker's verb refusals carry their message in ). */ - private async call(path: string, body: Record): Promise { + private async call( + path: string, + body: Record, + timeoutMs = OUTBOUND_FETCH_TIMEOUT_MS, + ): Promise { let res: Response; + let text: string; try { res = await fetch(`${this.brokerUrl}${path}`, { method: "POST", @@ -92,12 +118,16 @@ export class QueueClient { "Content-Type": "application/json", }, body: JSON.stringify(body), - signal: outboundTimeout(), + signal: outboundTimeout(timeoutMs), }); + text = await res.text(); } catch (e) { - throw new QueueError(`queue broker ${path} unreachable: ${e instanceof Error ? e.message : String(e)}`); + throw new QueueError( + `queue broker ${path} unreachable: ${e instanceof Error ? e.message : String(e)}`, + undefined, + true, + ); } - const text = await res.text(); let parsed: unknown = null; if (text.trim()) { try { @@ -178,14 +208,23 @@ export class QueueClient { * the claim, and a launch whose session is not bound must back out * through the caller's failure compensation. */ async claimTask(task: TaskRow, sessionId: string, launchedBy: string, leaseSeconds: number): Promise { - const env = await this.call("/claim-flow", { + const body = { task_id: task.id, worker: DISPATCH_WORKER, queue: task.queue, session_id: sessionId, launched_by: launchedBy, lease_seconds: leaseSeconds, - }); + }; + let env: BrokerEnvelope; + try { + env = await this.call("/claim-flow", body, CLAIM_FLOW_TIMEOUT_MS); + } catch (e) { + if (e instanceof QueueError && e.outcomeUnknown) { + return await this.reconcileClaimFlow(task.id, sessionId, launchedBy, e); + } + throw e; + } const row = this.envelopeRow(env, "/claim-flow"); if (!row) throw new ClaimLostError(task.id, "queued"); const partial = env.claim_flow_partial; @@ -202,6 +241,39 @@ export class QueueClient { return row; } + /** A lost /claim-flow response is ambiguous: Turso may have committed + * the claim and session bind before the dispatch timeout fired. Read the + * exact task, and recover only when its live claim names this session. + * Reapplying the lane/bind state writes for the same session completes a + * flow that timed out between steps; a different or still-queued claim keeps + * the original error and follows normal launch compensation. */ + private async reconcileClaimFlow( + taskId: number, + sessionId: string, + launchedBy: string, + originalError: QueueError, + ): Promise { + let row: TaskRow | null; + try { + row = await this.getTask(taskId); + } catch { + throw originalError; + } + if (!claimBelongsToSession(row, sessionId)) throw originalError; + + await this.assignLane(taskId); + await this.call("/bind", { + task_id: taskId, + worker: DISPATCH_WORKER, + session_id: sessionId, + launched_by: launchedBy, + }); + + const confirmed = await this.getTask(taskId); + if (!claimBelongsToSession(confirmed, sessionId)) throw originalError; + return confirmed; + } + /** One task by id via the broker's rich list. A failed lookup is * not a missing task: null is reserved for a successful empty * result, so a transient broker failure throws QueueError instead diff --git a/pm-stack/dispatch/test/queue.test.ts b/pm-stack/dispatch/test/queue.test.ts index d6e68568a7..7f358dcfd6 100644 --- a/pm-stack/dispatch/test/queue.test.ts +++ b/pm-stack/dispatch/test/queue.test.ts @@ -100,6 +100,50 @@ describe("broker claimTask (claim-flow, #10737 + #9028)", () => { expect((err as ClaimLostError).taskId).toBe(7); }); + test("a lost claim-flow response reconciles and finishes this session's committed claim", async () => { + const paths: string[] = []; + const bound = { ...row7, status: "claimed", progress: { session_id: "ses_1" } }; + const calls = stubBroker((path) => { + paths.push(path); + if (path === "/claim-flow") throw new DOMException("The operation timed out", "TimeoutError"); + if (path === "/list") return { ok: true, rows: [bound], total: 1 }; + return { ok: true, row: { task_id: 7, session_id: "ses_1" } }; + }); + const client = new QueueClient("http://broker.test", "tok-1"); + + const row = await client.claimTask(row7 as never, "ses_1", "tester", 3600); + + expect(row.status).toBe("claimed"); + expect(paths).toEqual(["/claim-flow", "/list", "/lane", "/bind", "/list"]); + expect(calls.find((c) => c.url.endsWith("/bind"))?.body).toMatchObject({ + task_id: 7, + worker: "dispatch-opencode", + session_id: "ses_1", + launched_by: "tester", + }); + }); + + test("a lost claim-flow response does not adopt another session's claim", async () => { + const paths: string[] = []; + const calls = stubBroker((path) => { + paths.push(path); + if (path === "/claim-flow") throw new DOMException("The operation timed out", "TimeoutError"); + return { + ok: true, + rows: [{ ...row7, status: "claimed", progress: { session_id: "ses_other" } }], + total: 1, + }; + }); + const client = new QueueClient("http://broker.test", "tok-1"); + + const err = await client.claimTask(row7 as never, "ses_1", "tester", 3600).catch((e) => e); + + expect(err).toBeInstanceOf(QueueError); + expect((err as QueueError).outcomeUnknown).toBe(true); + expect(paths).toEqual(["/claim-flow", "/list"]); + expect(calls).toHaveLength(2); + }); + test("a bind-step partial throws — the session binding is the point of the claim", async () => { stubBroker(() => ({ ok: true,