Skip to content
Draft
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
86 changes: 79 additions & 7 deletions pm-stack/dispatch/src/queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<string, unknown>).session_id === sessionId
);
}

interface BrokerEnvelope {
ok?: unknown;
row?: unknown;
Expand All @@ -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,
Expand All @@ -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<string, unknown>): Promise<BrokerEnvelope> {
private async call(
path: string,
body: Record<string, unknown>,
timeoutMs = OUTBOUND_FETCH_TIMEOUT_MS,
): Promise<BrokerEnvelope> {
let res: Response;
let text: string;
try {
res = await fetch(`${this.brokerUrl}${path}`, {
method: "POST",
Expand All @@ -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 {
Expand Down Expand Up @@ -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<TaskRow> {
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;
Expand All @@ -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<TaskRow> {
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
Expand Down
44 changes: 44 additions & 0 deletions pm-stack/dispatch/test/queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down