fix(issues): lock the issue before the run when adopting an unowned checkout (#23355)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents change tasks through the issue routes. Before each change,
the server checks that the agent's run owns the task's checkout
(`assertCheckoutOwner`).
> - This check clears terminal run locks and can adopt a checkout. Each
step uses a short transaction that locks rows.
> - The clears and the stale adoption lock the issue first and then the
heartbeat run. The unowned-checkout adoption locked the run first and
then updated the issue.
> - Two requests for the same task can then wait on each other.
PostgreSQL stops one with `deadlock detected`, and the agent's change
fails with a 500.
> - This pull request makes the unowned-checkout adoption lock the issue
before the run.
> - The benefit is one lock order (issue, then run) in all checkout
ownership paths. Concurrent requests now wait in turn and do not
deadlock.

## Linked Issues or Issue Description

**What happened?**
A hosted staging server reported `Error: Failed query: select
"heartbeat_runs"."id" from "heartbeat_runs" where "heartbeat_runs"."id"
= $1 for update`. The chained cause was `PostgresError: deadlock
detected` (40P01). The stack was `assertAgentIssueMutationAllowed` →
`assertCheckoutOwner` → a transaction that locks a heartbeat run.

**Steps to reproduce**
1. Make an `in_progress` task with an agent assignee, no
`checkoutRunId`, and a live `executionRunId` (run A).
2. Run A calls an issue mutation. `assertCheckoutOwner` adopts the
unowned checkout: it locks run A, then updates the issue.
3. At the same time, another run of the same agent (run B) calls an
issue mutation. `clearExecutionRunIfTerminal` locks the issue, then
waits for run A.
4. PostgreSQL detects the cycle and stops run B's request.

**Expected behavior**
Run A adopts the checkout. Run B gets an ordinary 409 ownership
conflict.

**Actual behavior**
Run B's request fails with a 500 that wraps `deadlock detected`.

No public GitHub issue exists. Related earlier work: #5413 and #4258
(they added the adoption paths). No open PR fixes this deadlock.

## What Changed

- `adoptUnownedCheckoutRun` in `server/src/services/issues.ts` now locks
the issue row (`FOR UPDATE`) before it locks the actor's heartbeat run.
This is the same order that `clearExecutionRunIfTerminal`,
`clearCheckoutRunIfTerminal`, and `adoptStaleCheckoutRun` use.
- New test
`server/src/__tests__/issue-checkout-adoption-lock-order.test.ts`. It
pauses the adoption inside its transaction, starts a concurrent
ownership check from a second run, and expects no deadlock.

## Verification

- Red: without the fix, the new test fails. The second request rejects
with `PostgresError 40P01 deadlock detected` on `select
"heartbeat_runs"."id" ... for update`. This is the same error that
Sentry reported.
- Green: with the fix, the new test passes. Run A adopts the checkout,
and run B gets a 409.
- `npx vitest run
src/__tests__/issue-checkout-adoption-lock-order.test.ts` (server): 1
passed.
- `npx vitest run src/__tests__/issues-service.test.ts -t
"checkout|adopt|ownership"` (server): 14 passed.

## Risks

- Low risk. The adoption transaction now also takes the issue row lock.
The transaction then updates the same row, so it already needed this
lock. The only change is the order of the locks.
- No schema, API, or UI change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 09:30:46 +00:00
1 parent 0666aff4a4
commit acb52955b7
2 files changed
+108

No files matched your search

@@ -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<typeof import("../services/status-card-notifications.js")>();
return {
...actual,
notifyStatusCardIssueChange: async (...args: Parameters<typeof actual.notifyStatusCardIssueChange>) => {
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<typeof createDb>;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | 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<void>((resolve) => { pauseGate.reached = resolve; });
pauseGate.release = new Promise<void>((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);
});
+6
View File
@@ -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`,
);