diff --git a/server/src/__tests__/company-deletion-concurrent-activity.test.ts b/server/src/__tests__/company-deletion-concurrent-activity.test.ts new file mode 100644 index 00000000000..b1e3e025340 --- /dev/null +++ b/server/src/__tests__/company-deletion-concurrent-activity.test.ts @@ -0,0 +1,139 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq, sql } from "drizzle-orm"; +import { activityLog, agents, companies, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +const hook = vi.hoisted(() => ({ duringDelete: null as null | (() => Promise) })); + +vi.mock("../services/scheduled-retry-cancellation-notifications.js", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + notifyScheduledRetryCancellation: async (...args: Parameters) => { + const run = hook.duringDelete; + hook.duringDelete = null; + await run?.(); + return original.notifyScheduledRetryCancellation(...args); + }, + }; +}); + +const { deleteCompany } = await import("../services/company-deletion.ts"); +const { logActivity } = await import("../services/activity-log.ts"); + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +if (!embeddedPostgresSupport.supported) { + console.warn( + `Skipping embedded Postgres company deletion activity tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, + ); +} + +type Seeded = { companyId: string; agentId: string; runId: string }; +type LateEntry = { agentId?: string; runId?: string }; + +describeEmbeddedPostgres("company deletion with a concurrent activity writer", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-deletion-activity-"); + db = createDb(tempDb.connectionString); + }, 20_000); + + afterEach(async () => { + hook.duringDelete = null; + await db.delete(activityLog); + await db.delete(heartbeatRuns); + await db.delete(agents); + await db.delete(companies); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + async function seedCompany(): Promise { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Deleted", issuePrefix: `D${companyId.replaceAll("-", "").slice(0, 8)}` }); + const [agent] = await db.insert(agents).values({ companyId, name: "Lead", status: "terminated", lifecycleState: "terminated" }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent!.id, status: "succeeded" }).returning(); + await logActivity(db, { companyId, actorType: "user", actorId: "board", action: "company.created", entityType: "company", entityId: companyId }); + return { companyId, agentId: agent!.id, runId: run!.id }; + } + + function recordRecovery(runner: Db, companyId: string, entry: LateEntry = {}) { + return logActivity(runner, { + companyId, actorType: "system", actorId: "system", action: "issue.updated", entityType: "issue", entityId: randomUUID(), + ...entry, details: { source: "recovery.reconcile_stranded_assigned_issue" }, + }); + } + + async function expectGone(seeded: Seeded) { + expect(await db.select().from(companies).where(eq(companies.id, seeded.companyId))).toEqual([]); + expect(await db.select().from(activityLog).where(eq(activityLog.companyId, seeded.companyId))).toEqual([]); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId))).toEqual([]); + expect(await db.select().from(agents).where(eq(agents.id, seeded.agentId))).toEqual([]); + } + + async function waitForDeleteToWaitOnLock() { + const deadline = Date.now() + 10_000; + for (;;) { + const waiting = await db.execute(sql`select 1 from pg_stat_activity + where wait_event_type = 'Lock' and pid <> pg_backend_pid()`); + if (waiting.length > 0) return; + if (Date.now() > deadline) throw new Error("The company delete never waited on the writer"); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + } + + async function deleteWhileWriterHoldsEntry(seeded: Seeded, entry: LateEntry) { + let writer: Promise = Promise.resolve(); + let release!: () => void; + const released = new Promise((resolve) => { release = resolve; }); + hook.duringDelete = async () => { + let inserted!: () => void; + const insertedSignal = new Promise((resolve) => { inserted = resolve; }); + writer = db.transaction(async (tx) => { + await recordRecovery(tx as unknown as Db, seeded.companyId, entry); + inserted(); + await released; + }); + await insertedSignal; + }; + const deleted = deleteCompany(db, seeded.companyId); + try { + await waitForDeleteToWaitOnLock(); + } finally { + release(); + await Promise.allSettled([deleted, writer]); + } + await writer; + return deleted; + } + + it("deletes the company when a background writer commits an activity entry after the activity sweep", async () => { + const seeded = await seedCompany(); + hook.duringDelete = async () => { await recordRecovery(db, seeded.companyId); }; + + expect(await deleteCompany(db, seeded.companyId)).toMatchObject({ id: seeded.companyId }); + await expectGone(seeded); + }); + + it.each([ + ["the company", {}], + ["a run of the company", { run: true }], + ["an agent of the company", { agent: true }], + ])("deletes the company when a writer still holds an activity entry that names %s", async (_label, refs: { run?: boolean; agent?: boolean }) => { + const seeded = await seedCompany(); + const entry: LateEntry = { ...(refs.run ? { runId: seeded.runId } : {}), ...(refs.agent ? { agentId: seeded.agentId } : {}) }; + + expect(await deleteWhileWriterHoldsEntry(seeded, entry)).toMatchObject({ id: seeded.companyId }); + await expectGone(seeded); + }); +}); diff --git a/server/src/services/company-deletion.ts b/server/src/services/company-deletion.ts index e6502bc363a..d07af8dfee4 100644 --- a/server/src/services/company-deletion.ts +++ b/server/src/services/company-deletion.ts @@ -65,6 +65,30 @@ import { routines, } from "@paperclipai/db"; +type DeletionTx = Parameters[0]>[0]; + +async function sweepLateActivity(tx: DeletionTx, companyId: string) { + await tx.delete(activityLog).where(eq(activityLog.companyId, companyId)); +} + +async function lockRunsAndSweepLateActivity(tx: DeletionTx, companyId: string) { + await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(eq(heartbeatRuns.companyId, companyId)).orderBy(heartbeatRuns.id).for("update"); + await sweepLateActivity(tx, companyId); +} + +async function lockAgentsAndSweepLateActivity(tx: DeletionTx, companyId: string) { + await tx.select({ id: agents.id }).from(agents) + .where(eq(agents.companyId, companyId)).orderBy(agents.id).for("update"); + await sweepLateActivity(tx, companyId); +} + +async function lockCompanyAndSweepLateActivity(tx: DeletionTx, companyId: string) { + await tx.select({ id: companies.id }).from(companies) + .where(eq(companies.id, companyId)).for("update"); + await sweepLateActivity(tx, companyId); +} + export async function deleteCompany(db: Db, id: string) { const tailscaleDeletion = createTailscaleCompanyDeletion(); const lifecycle = createAgentLifecycle(db); @@ -75,8 +99,12 @@ export async function deleteCompany(db: Db, id: string) { } const deleted = await withAccountHomeSecretMutationLock(undefined, id, () => db.transaction(async (tx) => { // Exclude accounting writers before taking child locks. KEY SHARE must - // remain compatible: native writers can already hold a child row while - // saving a company-scoped result. FOR UPDATE would deadlock that save. + // remain compatible here: native writers can already hold a child row + // while saving a company-scoped result, so FOR UPDATE now would deadlock + // that save. Runs, agents and the company row are locked FOR UPDATE only + // immediately before each is deleted, where the DELETE needs that + // conflicting lock anyway; each lock is followed by a sweep of activity + // entries that writers committed after the first sweep. const [existing] = await tx.select({ id: companies.id }).from(companies) .where(eq(companies.id, id)).for("no key update"); if (!existing) return null; @@ -127,6 +155,7 @@ export async function deleteCompany(db: Db, id: string) { await notifyCancelledWorkspacePreservation(tx, { companyId: id }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: id }); await executionAdmissionCompanyDeletion.deleteCompanyData(tx, id); + await lockRunsAndSweepLateActivity(tx, id); await tx.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, id)); await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, id)); await tx.delete(agentApiKeys).where(eq(agentApiKeys.companyId, id)); @@ -158,8 +187,10 @@ export async function deleteCompany(db: Db, id: string) { await requestRestorePointDeletion(tx, { companyId: id }); await tx.delete(executionWorkspaces).where(eq(executionWorkspaces.companyId, id)); await tx.delete(projects).where(eq(projects.companyId, id)); + await lockAgentsAndSweepLateActivity(tx, id); await agentLifecycleCompanyDeletion.deleteCompanyData(tx, id); await notifyToolConnectionHealth(tx, id); + await lockCompanyAndSweepLateActivity(tx, id); const rows = await tx .delete(companies) .where(eq(companies.id, id))