diff --git a/pm-stack/dispatch/src/queue.ts b/pm-stack/dispatch/src/queue.ts index 239889da3..f273cf3a9 100644 --- a/pm-stack/dispatch/src/queue.ts +++ b/pm-stack/dispatch/src/queue.ts @@ -7,8 +7,12 @@ // for the other fleet repos. The RPC returns the created row (incl. id); // NOTE it dedupes on dedupe_key against ALL tasks incl. done ones, so a // returned row whose dedupe_key was already consumed is the OLD task — -// callers get the row as-is and the canonical-key flows anchor to fresh -// issues, which cannot collide. +// callers get the row as-is. The create-an-issue canonical-key flow +// anchors to a fresh issue, which cannot collide; the issue_number +// ATTACH flow anchors to an existing issue whose canonical key may +// already be consumed (live or terminal), so attach callers MUST detect +// a pre-existing row and must never report it as newly queued — see +// enqueueDispatchTask in server.ts (issue #2677). import type { Packet } from "./packet.ts"; import { REPO_QUEUES } from "./config.ts"; diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index e729f6895..55c2f7332 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -22,7 +22,7 @@ import { type SessionRequest, type TaskRequest, } from "./validate.ts"; -import { buildPacket, canonicalDedupeKey, describeCaller, dispatchDedupeKey, validatePayload } from "./packet.ts"; +import { buildPacket, canonicalDedupeKey, describeCaller, dispatchDedupeKey, randomDispatchSuffix, validatePayload } from "./packet.ts"; import { QueueClient, QueueError, type TaskRow } from "./queue.ts"; import { handleLaunchFailure } from "./launch_failure.ts"; import { GitHubClient } from "./github.ts"; @@ -263,11 +263,99 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise Promise; + dedupeKey: string; + attach: boolean; + callerSuppliedKey: boolean; + requestStartedAt: Date; +}): Promise { + const first = await args.enqueue(args.dedupeKey); + if (!isPreExistingTaskRow(first, args.requestStartedAt)) { + return { task: first, preExisting: false, retried: false, warnings: [] }; + } + if (!args.attach || args.callerSuppliedKey) { + return { + task: first, + preExisting: true, + retried: false, + warnings: [ + `dedupe key already in use: task #${first.id} already exists with status "${first.status}"; returning the existing task — no new task was queued`, + ], + }; + } + const retryKey = `${args.dedupeKey}:dispatch:${randomDispatchSuffix()}`; + const second = await args.enqueue(retryKey); + if (!isPreExistingTaskRow(second, args.requestStartedAt)) { + return { + task: second, + preExisting: false, + retried: true, + warnings: [ + `task #${first.id} already exists for this issue with status "${first.status}"; this dispatch was queued as a distinct task #${second.id} with a dispatch-scoped dedupe key`, + ], + }; + } + return { + task: second, + preExisting: true, + retried: true, + warnings: [ + `task #${first.id} already exists for this issue with status "${first.status}", and the dispatch-scoped retry also returned a pre-existing task #${second.id} with status "${second.status}"; no new task was queued`, + ], + }; +} + // --------------------------------------------------------------------------- // POST /v1/tasks // --------------------------------------------------------------------------- async function handleTasks(req: Request, caller: CallerIdentity): Promise { + const requestStartedAt = new Date(); const body: TaskRequest = parseTaskRequest(await readJsonBody(req)); assertCallerRepo(caller, body.repo, cfg.repoAllowlist); const warnings: string[] = []; @@ -293,28 +381,40 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise { + const p = key === dedupeKey ? packet : buildPacket(packetInput, key); + const errs = validatePayload(p.payload); + if (errs.length) throw new QueueError(`internal packet validation failed: ${errs.join("; ")}`); + return requireQueue().enqueue(p, body.repo); + }, + dedupeKey, + attach: body.issueNumber !== undefined, + callerSuppliedKey: body.dedupeKey !== undefined, + requestStartedAt, + }); } catch (e) { + if (e instanceof QueueError && e.message.startsWith("internal packet validation failed")) { + return json(500, { error: e.message }); + } return json(502, { error: e instanceof Error ? e.message : String(e), issue_number: issue?.number ?? null, @@ -322,6 +422,8 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise): TaskRow { + return { + id: 1, + queue: "repo-health-code-pilot", + status: "queued", + dedupe_key: CANONICAL, + created_at: AFTER, + ...partial, + }; +} + +/** Stubbed queue: canonical key returns `first`, any other key `second`. */ +function stubQueue(first: TaskRow, second?: TaskRow) { + const keys: string[] = []; + const enqueue = async (key: string): Promise => { + keys.push(key); + if (key === CANONICAL) return first; + if (second) return second; + throw new Error(`unexpected enqueue key in test: ${key}`); + }; + return { enqueue, keys }; +} + +describe("isPreExistingTaskRow (#2677)", () => { + test("a row created before the request started is pre-existing", () => { + expect(isPreExistingTaskRow(row({ created_at: BEFORE }), START)).toBe(true); + }); + + test("a terminal row is pre-existing even with a fresh created_at", () => { + for (const status of ["done", "cancelled", "failed"]) { + expect(isPreExistingTaskRow(row({ status, created_at: AFTER }), START)).toBe(true); + } + }); + + test("a fresh live row is newly queued", () => { + expect(isPreExistingTaskRow(row({ status: "queued", created_at: AFTER }), START)).toBe(false); + expect(isPreExistingTaskRow(row({ status: "claimed", created_at: AFTER }), START)).toBe(false); + }); +}); + +describe("enqueueDispatchTask attach flow (#2677)", () => { + test("second attach against a TERMINAL canonical-key task gets its own task", async () => { + const old = row({ id: 111, status: "done", created_at: BEFORE }); + const fresh = row({ id: 222, status: "queued", created_at: AFTER }); + const { enqueue, keys } = stubQueue(old, fresh); + + const out = await enqueueDispatchTask({ + enqueue, + dedupeKey: CANONICAL, + attach: true, + callerSuppliedKey: false, + requestStartedAt: START, + }); + + expect(keys.length).toBe(2); + expect(keys[1]).toStartWith(`${CANONICAL}:dispatch:`); + expect(out.task.id).toBe(222); + expect(out.preExisting).toBe(false); + expect(out.retried).toBe(true); + expect(out.warnings.join(" ")).toContain("#111"); + expect(out.warnings.join(" ")).toContain('"done"'); + }); + + test("second attach against a LIVE canonical-key task gets its own task", async () => { + const old = row({ id: 111, status: "queued", created_at: BEFORE }); + const fresh = row({ id: 333, status: "queued", created_at: AFTER }); + const { enqueue, keys } = stubQueue(old, fresh); + + const out = await enqueueDispatchTask({ + enqueue, + dedupeKey: CANONICAL, + attach: true, + callerSuppliedKey: false, + requestStartedAt: START, + }); + + expect(keys.length).toBe(2); + expect(keys[1]).toStartWith(`${CANONICAL}:dispatch:`); + expect(out.task.id).toBe(333); + expect(out.preExisting).toBe(false); + expect(out.retried).toBe(true); + expect(out.warnings.join(" ")).toContain("#111"); + }); + + test("attach retry that also returns pre-existing warns explicitly, never silent-new", async () => { + const old = row({ id: 111, status: "done", created_at: BEFORE }); + const alsoOld = row({ id: 111, status: "done", created_at: BEFORE }); + const { enqueue, keys } = stubQueue(old, alsoOld); + + const out = await enqueueDispatchTask({ + enqueue, + dedupeKey: CANONICAL, + attach: true, + callerSuppliedKey: false, + requestStartedAt: START, + }); + + expect(keys.length).toBe(2); + expect(out.preExisting).toBe(true); + expect(out.retried).toBe(true); + expect(out.warnings.join(" ")).toContain("no new task was queued"); + }); +}); + +describe("enqueueDispatchTask non-attach flows (#2677)", () => { + test("caller-supplied dedupe_key repeat returns the existing task WITH a warning naming its status", async () => { + const old = row({ id: 444, status: "claimed", created_at: BEFORE }); + const { enqueue, keys } = stubQueue(old); + + const out = await enqueueDispatchTask({ + enqueue, + dedupeKey: CANONICAL, + attach: false, + callerSuppliedKey: true, + requestStartedAt: START, + }); + + expect(keys.length).toBe(1); // no retry for non-attach repeats + expect(out.task.id).toBe(444); + expect(out.preExisting).toBe(true); + expect(out.retried).toBe(false); + expect(out.warnings.join(" ")).toContain('"claimed"'); + expect(out.warnings.join(" ")).toContain("no new task was queued"); + }); + + test("a fresh enqueue passes through untouched", async () => { + const fresh = row({ id: 555, status: "queued", created_at: AFTER }); + const { enqueue, keys } = stubQueue(fresh); + + const out = await enqueueDispatchTask({ + enqueue, + dedupeKey: CANONICAL, + attach: true, + callerSuppliedKey: false, + requestStartedAt: START, + }); + + expect(keys.length).toBe(1); + expect(out.task.id).toBe(555); + expect(out.preExisting).toBe(false); + expect(out.retried).toBe(false); + expect(out.warnings).toEqual([]); + }); +}); + +describe("enqueueDispatchTask caller-supplied key on an attach request (#2677, Codex P2)", () => { + test("issue_number + explicit dedupe_key repeat returns the existing task — no dispatch-scoped retry", async () => { + const old = row({ id: 777, status: "queued", created_at: BEFORE }); + const { enqueue, keys } = stubQueue(old); + + const out = await enqueueDispatchTask({ + enqueue, + dedupeKey: CANONICAL, + attach: true, + callerSuppliedKey: true, + requestStartedAt: START, + }); + + expect(keys.length).toBe(1); // the caller chose the key: a repeat is an intentional dedupe + expect(out.task.id).toBe(777); + expect(out.preExisting).toBe(true); + expect(out.retried).toBe(false); + expect(out.warnings.join(" ")).toContain("no new task was queued"); + }); +});