fix(companies): delete a company when a late activity entry commits during the delete (#22719)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A board user can delete a company. `deleteCompany` removes the
company rows in one transaction.
> - The transaction removes activity entries early. It then removes many
other rows, and it removes the company row last.
> - The transaction holds only a `NO KEY UPDATE` lock on the company
row. This lock does not stop the `KEY SHARE` lock that a foreign key
check takes. A background writer can add an activity entry for the
company while the delete runs.
> - The delete itself starts such a writer. It terminates the company's
agents first. Termination wakes stranded-task recovery, which marks the
agent's open task as blocked and writes an `issue.updated` activity
entry.
> - When that entry commits after the early sweep, the final delete
fails on `activity_log_company_id_companies_id_fk`, and the user gets a
500 error.
> - This pull request locks the company row `FOR UPDATE` just before the
final delete, and then removes the activity entries again.
> - The benefit is that company deletion works when a background writer
adds an activity entry during the delete.

## Linked Issues or Issue Description

Refs #22714

**What happened?**
`DELETE /api/companies/:id` sometimes returned 500. The log showed:
`update or delete on table "companies" violates foreign key constraint
"activity_log_company_id_companies_id_fk" on table "activity_log"`. The
e2e test `tests/e2e/plan-task-fixture.spec.ts` failed this way 8 times
in CI between 2026-11-20 and 2026-11-23 (for example on #22714). Each
time, a rerun passed. The failures started before #22636 and #22669, so
those changes did not cause it.

**What did you expect to happen?**
Company deletion succeeds every time. A background writer for the
company does not make the delete fail.

**Steps to reproduce**
1. Create a company with two agents that use the `process` adapter, and
pause both agents.
2. Create a task that is assigned to one of the agents.
3. Wait 300 to 1000 ms, then delete the company.
4. Repeat. On a local server, 2 of 80 deletes failed with the error
above. The failed company still had an `issue.updated` entry from
`recovery.reconcile_stranded_assigned_issue`.

## What Changed

- `server/src/services/company-deletion.ts`: three named steps lock rows
`FOR UPDATE` immediately before the `DELETE` of the same rows, and then
remove the company's activity entries again:
- `lockRunsAndSweepLateActivity` before the company's runs are deleted,
- `lockAgentsAndSweepLateActivity` before the company's agents are
deleted,
  - `lockCompanyAndSweepLateActivity` before the company row is deleted.
Each lock waits for writers that hold `KEY SHARE` on those rows and
blocks new ones. So a late activity entry that names the company, a run
or an agent cannot make the next `DELETE` fail.
- The existing comment at the start of the transaction now explains both
kinds of lock: why the first lock stays `NO KEY UPDATE`, and why the
later `FOR UPDATE` locks are safe.
- New test
`server/src/__tests__/company-deletion-concurrent-activity.test.ts`
(embedded Postgres). A second connection adds an activity entry while
the delete runs. Case 1: the writer commits after the first sweep. Cases
2 to 4: the writer keeps its transaction open, with an entry that names
the company, a run, or an agent. The test polls `pg_stat_activity` until
the delete waits on a lock, and then releases the writer. There is no
fixed sleep. The release is in a `finally` block.

## Verification

- Red: without the fix, the tests fail with
`activity_log_company_id_companies_id_fk`, the same error as in CI.
- Each lock was removed in turn. Without the run and agent locks, the
run and agent cases fail with `activity_log_run_id_heartbeat_runs_id_fk`
and `activity_log_agent_id_agents_id_fk`. Without the company lock, the
company case fails with `activity_log_company_id_companies_id_fk`. The
other cases still pass each time.
- Green: `cd server && npx vitest run
src/__tests__/company-deletion-concurrent-activity.test.ts` passes (4
tests).
- Related suites pass (413 tests): `git-restore-point-ledger`,
`tool-connection-content-deletion-canary`, `agent-observability`,
`decision-target-work`, `google-managed-connection-removal`,
`task-workspace-binding`, `tool-gateway-service` and the new test.
- `cd server && npx tsc --noEmit -p .` passes.
- Local server reproduction (the steps above, API calls only, first
commit of this PR): before the fix 2 of 80 deletes failed. After the fix
0 of 280 deletes failed, and the server log had no foreign key errors.

## Risks

- Low risk. Each new `FOR UPDATE` lock is taken immediately before a
`DELETE` of the same rows. That `DELETE` already takes a lock that
conflicts with `KEY SHARE`. So the change adds no new wait and no new
deadlock path. The first lock on the company stays `NO KEY UPDATE`, so a
native save that holds a child row is not blocked early.
- A writer that adds an activity entry after the delete commits gets a
foreign key error in its own transaction, as before. Stranded-task
recovery and the Google retry worker check that the company exists or
catch the error. In the reproduction, no worker logged an error.
- Not changed: the `activity_log` foreign keys. Only activity entries
are swept again. A late row in another table that has no cascade can
still conflict with a delete. No CI log showed that case.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use (shell, file edit, embedded Postgres tests, local server).

## 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: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 19:26:22 -06:00
1 parent 37cbad2cd5
commit fe93b402ac
2 files changed
+172 -2

No files matched your search

@@ -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<void>) }));
vi.mock("../services/scheduled-retry-cancellation-notifications.js", async (importOriginal) => {
const original = await importOriginal<typeof import("../services/scheduled-retry-cancellation-notifications.js")>();
return {
...original,
notifyScheduledRetryCancellation: async (...args: Parameters<typeof original.notifyScheduledRetryCancellation>) => {
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<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | 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<Seeded> {
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<unknown> = Promise.resolve();
let release!: () => void;
const released = new Promise<void>((resolve) => { release = resolve; });
hook.duringDelete = async () => {
let inserted!: () => void;
const insertedSignal = new Promise<void>((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);
});
});
+33 -2
View File
@@ -65,6 +65,30 @@ import {
routines,
} from "@paperclipai/db";
type DeletionTx = Parameters<Parameters<Db["transaction"]>[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))