diff --git a/server/src/__tests__/issue-checkout-adoption-lock-order.test.ts b/server/src/__tests__/issue-checkout-adoption-lock-order.test.ts new file mode 100644 index 00000000000..5b2e337273c --- /dev/null +++ b/server/src/__tests__/issue-checkout-adoption-lock-order.test.ts @@ -0,0 +1,102 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +// Pause the first transaction that announces a status-card change. In the +// unowned-checkout adoption, that happens between the run lock and the issue +// update, which is the window where a concurrent issue -> run locker can join. +const pauseGate = vi.hoisted(() => ({ armed: false, reached: () => {}, release: Promise.resolve() })); +vi.mock("../services/status-card-notifications.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + notifyStatusCardIssueChange: async (...args: Parameters) => { + if (pauseGate.armed) { + pauseGate.armed = false; + pauseGate.reached(); + await pauseGate.release; + } + return actual.notifyStatusCardIssueChange(...args); + }, + }; +}); + +const { issueService } = await import("../services/issues.js"); + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; + +describeEmbeddedPostgres("checkout adoption lock order", () => { + let db!: ReturnType; + let database: Awaited> | null = null; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-checkout-adoption-lock-"); + db = createDb(database.connectionString); + }, 30_000); + + afterAll(async () => { + await database?.cleanup(); + }); + + const lockWaiters = async () => (await db.execute<{ count: number }>(sql`select count(*)::int as count + from pg_stat_activity where datname = current_database() and wait_event_type = 'Lock'`))[0]?.count ?? 0; + + it("adopting an unowned checkout does not deadlock with a concurrent ownership check", async () => { + const companyId = randomUUID(); + const agentId = randomUUID(); + const executionRunId = randomUUID(); + const otherRunId = randomUUID(); + const issueId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Paperclip", + issuePrefix: `L${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, + requireBoardApprovalForNewAgents: false, + }); + await db.insert(agents).values({ + id: agentId, companyId, name: "Assignee", role: "engineer", status: "active", + adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {}, + }); + await db.insert(heartbeatRuns).values([executionRunId, otherRunId].map((id) => ({ + id, companyId, agentId, status: "running", invocationSource: "manual" as const, startedAt: new Date(), + }))); + // The execution run holds the issue but has not claimed checkout yet, so + // its first mutation adopts the checkout. + await db.insert(issues).values({ + id: issueId, companyId, title: "Adoption race", status: "in_progress", priority: "medium", + assigneeAgentId: agentId, checkoutRunId: null, executionRunId, executionLockedAt: new Date(), + }); + + const svc = issueService(db); + let release!: () => void; + const reached = new Promise((resolve) => { pauseGate.reached = resolve; }); + pauseGate.release = new Promise((resolve) => { release = resolve; }); + pauseGate.armed = true; + + const adoption = svc.assertCheckoutOwner(issueId, agentId, executionRunId); + void adoption.catch(() => undefined); + // Surface an early failure of the adoption instead of waiting for a pause it never reaches. + await Promise.race([reached, adoption.then(() => { + throw new Error("adoption finished before it reached the paused notification"); + })]); + + // Another request for the same task clears terminal locks first: it locks + // the issue and then the execution run. + const concurrent = svc.assertCheckoutOwner(issueId, agentId, otherRunId); + void concurrent.catch(() => undefined); + await vi.waitFor(async () => expect(await lockWaiters()).toBeGreaterThan(0), { timeout: 10_000, interval: 25 }); + release(); + + const [adopted, other] = await Promise.allSettled([adoption, concurrent]); + expect(adopted).toMatchObject({ status: "fulfilled", value: { checkoutRunId: executionRunId, executionRunId } }); + // The live owner stays protected; the other run gets an ordinary conflict, not a deadlock. + expect(other).toMatchObject({ status: "rejected", reason: { status: 409 } }); + + const [row] = await db.select({ checkoutRunId: issues.checkoutRunId, executionRunId: issues.executionRunId }) + .from(issues).where(eq(issues.id, issueId)); + expect(row).toEqual({ checkoutRunId: executionRunId, executionRunId }); + }, 30_000); +}); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 0141b3b5374..8b9aad4f84d 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -8241,6 +8241,12 @@ export function issueService(db: Db) { actorRunId: string; }) { return db.transaction(async (tx) => { + // Lock the issue before the run, like the terminal-lock clears and stale + // adoption. Locking the run first deadlocks with a concurrent ownership + // check that holds this issue and waits for this run. + await tx.execute( + sql`select ${issues.id} from ${issues} where ${issues.id} = ${input.issueId} for update`, + ); await tx.execute( sql`select ${heartbeatRuns.id} from ${heartbeatRuns} where ${heartbeatRuns.id} = ${input.actorRunId} for update`, );