From d6d886751f0f1feb0b1f943c27d421263e479297 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 11:51:26 -0500 Subject: [PATCH 1/2] =?UTF-8?q?fix(pm-dispatch):=20detect=20pre-existing?= =?UTF-8?q?=20enqueue=20row=20=E2=80=94=20attach=20dispatch=20must=20not?= =?UTF-8?q?=20silently=20vanish=20(#2677)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/dispatch/src/queue.ts | 8 +- pm-stack/dispatch/src/server.ts | 141 +++++++++++++--- .../test/dispatch_preexisting.test.ts | 155 ++++++++++++++++++ 3 files changed, 283 insertions(+), 21 deletions(-) create mode 100644 pm-stack/dispatch/test/dispatch_preexisting.test.ts 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..1ebd10013 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,96 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise Promise; + dedupeKey: string; + attach: 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) { + 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 +378,39 @@ 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, + 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 +418,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, + 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, + 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, + 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, + 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, + 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([]); + }); +}); From 97e60a7ebf9da657d7ce2cd4899f34c58c3d9804 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 11:58:31 -0500 Subject: [PATCH 2/2] fix(pm-dispatch): preserve caller-supplied dedupe keys on attach requests (#2677, Codex P2) --- pm-stack/dispatch/src/server.ts | 16 +++++++----- .../test/dispatch_preexisting.test.ts | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index 1ebd10013..55c2f7332 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -298,24 +298,27 @@ export interface EnqueueDispatchOutcome { /** * Enqueue with pre-existing-row handling (issue #2677): - * - attach flow (issue_number): a pre-existing canonical row means the - * caller's distinct dispatch gets its own task via a dispatch-scoped - * suffix key; if the retry also returns a pre-existing row, warn - * explicitly instead of reporting a silent 201-as-new. - * - any other flow (incl. a caller-supplied dedupe_key repeat): return + * - attach flow (issue_number) with the CANONICAL key: a pre-existing + * canonical row means the caller's distinct dispatch gets its own task + * via a dispatch-scoped suffix key; if the retry also returns a + * pre-existing row, warn explicitly instead of a silent 201-as-new. + * - any other flow (incl. a caller-supplied dedupe_key repeat — also + * when combined with issue_number: the caller explicitly chose that + * key, so a repeat is an intentional dedupe, never a retry): return * the existing task WITH a warning naming its actual status. */ export async function enqueueDispatchTask(args: { enqueue: (dedupeKey: string) => 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) { + if (!args.attach || args.callerSuppliedKey) { return { task: first, preExisting: true, @@ -405,6 +408,7 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise { enqueue, dedupeKey: CANONICAL, attach: true, + callerSuppliedKey: false, requestStartedAt: START, }); @@ -85,6 +86,7 @@ describe("enqueueDispatchTask attach flow (#2677)", () => { enqueue, dedupeKey: CANONICAL, attach: true, + callerSuppliedKey: false, requestStartedAt: START, }); @@ -105,6 +107,7 @@ describe("enqueueDispatchTask attach flow (#2677)", () => { enqueue, dedupeKey: CANONICAL, attach: true, + callerSuppliedKey: false, requestStartedAt: START, }); @@ -124,6 +127,7 @@ describe("enqueueDispatchTask non-attach flows (#2677)", () => { enqueue, dedupeKey: CANONICAL, attach: false, + callerSuppliedKey: true, requestStartedAt: START, }); @@ -143,6 +147,7 @@ describe("enqueueDispatchTask non-attach flows (#2677)", () => { enqueue, dedupeKey: CANONICAL, attach: true, + callerSuppliedKey: false, requestStartedAt: START, }); @@ -153,3 +158,24 @@ describe("enqueueDispatchTask non-attach flows (#2677)", () => { 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"); + }); +});