diff --git a/server/src/__tests__/issue-references-service.test.ts b/server/src/__tests__/issue-references-service.test.ts index ceec46a6477..3954b5dd5b8 100644 --- a/server/src/__tests__/issue-references-service.test.ts +++ b/server/src/__tests__/issue-references-service.test.ts @@ -175,6 +175,49 @@ describeEmbeddedPostgres("issueReferenceService", () => { expect(pap3?.sources.map((source) => source.label)).toEqual(["description"]); }); + it("serializes concurrent syncs for a description with repeated references", async () => { + const companyId = randomUUID(); + const sourceIssueId = randomUUID(); + const targetIssueId = randomUUID(); + + await db.insert(companies).values({ + id: companyId, + name: "Paperclip Concurrent References", + issuePrefix: `C${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, + requireBoardApprovalForNewAgents: false, + }); + + await db.insert(issues).values([ + { + id: sourceIssueId, + companyId, + title: "Source issue", + description: "Coordinate COM-2 and confirm COM-2 again.", + status: "todo", + priority: "medium", + identifier: "COM-1", + }, + { + id: targetIssueId, + companyId, + title: "Target issue", + status: "todo", + priority: "medium", + identifier: "COM-2", + }, + ]); + + await expect(Promise.all( + Array.from({ length: 20 }, () => refs.syncIssue(sourceIssueId)), + )).resolves.toHaveLength(20); + + const mentions = await db + .select() + .from(issueReferenceMentions); + expect(mentions).toHaveLength(1); + expect(mentions[0]?.targetIssueId).toBe(targetIssueId); + }); + it("backfills existing references for a company without requiring write-time sync", async () => { const companyId = randomUUID(); const sourceIssueId = randomUUID(); diff --git a/server/src/services/issue-references.ts b/server/src/services/issue-references.ts index 8d08ccba581..5b5a52d419e 100644 --- a/server/src/services/issue-references.ts +++ b/server/src/services/issue-references.ts @@ -174,8 +174,8 @@ export function issueReferenceService(db: Db) { } } - async function issueById(issueId: string, dbOrTx: any = db) { - return dbOrTx + async function issueById(issueId: string, dbOrTx: any = db, lock = false) { + const query = dbOrTx .select({ id: issues.id, companyId: issues.companyId, @@ -183,13 +183,14 @@ export function issueReferenceService(db: Db) { description: issues.description, }) .from(issues) - .where(eq(issues.id, issueId)) + .where(eq(issues.id, issueId)); + return (lock ? query.for("update") : query) .then((rows: Array<{ id: string; companyId: string; title: string; description: string | null }>) => rows[0] ?? null); } async function syncIssue(issueId: string, dbOrTx: any = db) { const runSync = async (tx: any) => { - const issue = await issueById(issueId, tx); + const issue = await issueById(issueId, tx, true); if (!issue) throw notFound("Issue not found"); await replaceSourceMentions({