Files
PaperClipAI/server/src/services/company-deletion.ts
T
DottaandClaude Opus 5.5 fe93b402ac 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>
2026-11-23 19:26:22 -06:00

203 lines
11 KiB
TypeScript

import { mcpCompanyDeletion } from "./public-mcp/company-deletion.js";
import { notifyStatusCardEvaluation } from "./status-card-notifications.js";
import { notifyExternalObjectRefresh } from "./external-object-refresh-notifications.js";
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { notifyUnsafeWorkspaceExportRecovery } from "./unsafe-workspace-export-notifications.js";
import { notifyCancelledWorkspacePreservation } from "./cancelled-workspace-preservation-notifications.js";
import { notifyInstructionCollection } from "./instruction-collection-notifications.js";
import { notifyDirectoryCleanup } from "./directory-cleanup-notifications.js";
import { notifyInstructionCommit } from "./instruction-commit-notifications.js";
import { notifyScheduledRetryCancellation } from "./scheduled-retry-cancellation-notifications.js";
import { notifyChatCompanyConfiguration } from "./chat-channels/configuration-work-notifications.js";
import { chatCompanyDeletion } from "./chat-channels/company-deletion.js";
import { createTailscaleCompanyDeletion } from "./connectors/tailscale/deletion.js";
import { notifyToolConnectionHealth } from "./tool-connection-health-notifications.js";
import { notifyCompanyRetentionWork } from "./retention-work-notifications.js";
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { agentObservabilityService } from "./agent-observability.js";
import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
import type { Db } from "@paperclipai/db";
import { eq, inArray } from "drizzle-orm";
import { createAgentLifecycle, processAgentLifecycle } from "./agent-lifecycle.js";
import { requestRestorePointDeletion } from "./git-restore-point-ledger.js";
import { requestCompanyStoredObjectDeletion } from "./tool-access/connections/stored-object-deletion.js";
import { queueCompanyGoogleRevocations } from "./tool-access/connections/google-pending-revocation.js";
import { agentLifecycleCompanyDeletion } from "../modules/agent-lifecycle/company-deletion.js";
import { executionAdmissionCompanyDeletion } from "../modules/execution-admission/company-deletion.js";
import {
companies,
agents,
companyLogos,
assets,
agentApiKeys,
agentRuntimeState,
agentTaskSessions,
agentWakeupRequests,
issues,
issueComments,
projects,
executionWorkspaces,
goals,
heartbeatRuns,
runIdentityContexts,
heartbeatRunEvents,
costEvents,
decisionInvocations,
financeEvents,
budgetPolicies,
budgetIncidents,
issueReadStates,
approvalComments,
approvals,
activityLog,
companySecrets,
joinRequests,
invites,
principalPermissionGrants,
companyMemberships,
companySkills,
cases,
documents,
routineRuns,
routineTriggers,
routineRevisions,
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);
const companyAgents = await db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, id));
for (const agent of companyAgents) {
await lifecycle.terminateAgent(agent.id);
await processAgentLifecycle(db, agent.id);
}
const deleted = await withAccountHomeSecretMutationLock(undefined, id, () => db.transaction(async (tx) => {
// Exclude accounting writers before taking child locks. KEY SHARE must
// 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;
await requestCompanyStoredObjectDeletion(tx as unknown as Db, id);
await queueCompanyGoogleRevocations(tx as unknown as Db, id, "company_deleted");
await mcpCompanyDeletion.deleteCompanyData(tx, id);
await notifyExternalObjectRefresh(tx, id);
await notifyIssueRecovery(tx, { companyId: id });
await notifyChatCompanyConfiguration(tx, id);
await chatCompanyDeletion.deleteCompanyData(tx, id);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillPackages);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.routineSchedules);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
await notifyStatusCardEvaluation(tx, id);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id);
await notifyToolReviewChange(tx, id);
await agentObservabilityService(tx as unknown as Db).removeForCompanyDeletion(id);
// Finance can reference costs and both can reference runs. Incidents
// reference policies and approvals; delete these dependents first.
await tx.delete(financeEvents).where(eq(financeEvents.companyId, id));
await tx.delete(decisionInvocations).where(eq(decisionInvocations.companyId, id));
await tx.delete(costEvents).where(eq(costEvents.companyId, id));
await tx.delete(budgetIncidents).where(eq(budgetIncidents.companyId, id));
await tx.delete(budgetPolicies).where(eq(budgetPolicies.companyId, id));
// Cases retain task and agent references. Their dependent handoffs and
// access sources cascade here before those task/agent records are removed.
await tx.delete(cases).where(eq(cases.companyId, id));
// Delete from child tables in dependency order
const companyRunIds = await tx
.select({ id: heartbeatRuns.id })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.companyId, id));
await tx.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.companyId, id));
if (companyRunIds.length > 0) {
await tx
.delete(heartbeatRunEvents)
.where(inArray(heartbeatRunEvents.runId, companyRunIds.map((run) => run.id)));
}
await tx.delete(agentTaskSessions).where(eq(agentTaskSessions.companyId, id));
await tx.delete(activityLog).where(eq(activityLog.companyId, id));
await tx.delete(runIdentityContexts).where(eq(runIdentityContexts.companyId, id));
await notifyScheduledRetryCancellation(tx, { companyId: id });
await notifyInstructionCommit(tx, { companyId: id });
await notifyDirectoryCleanup(tx, { companyId: id });
await notifyInstructionCollection(tx, { companyId: id });
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));
await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.companyId, id));
// Match receipt completion and comment deletion: task before comment.
await tx.select({ id: issues.id }).from(issues)
.where(eq(issues.companyId, id)).orderBy(issues.id).for("no key update");
await tx.delete(issueComments).where(eq(issueComments.companyId, id));
await tx.delete(approvalComments).where(eq(approvalComments.companyId, id));
await notifyCompanyRetentionWork(tx, id);
await tx.delete(approvals).where(eq(approvals.companyId, id));
await tailscaleDeletion.deleteCompanyData(tx, id);
await tx.delete(companySecrets).where(eq(companySecrets.companyId, id));
await tx.delete(joinRequests).where(eq(joinRequests.companyId, id));
await tx.delete(invites).where(eq(invites.companyId, id));
await tx.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, id));
await tx.delete(companyMemberships).where(eq(companyMemberships.companyId, id));
await tx.delete(companySkills).where(eq(companySkills.companyId, id));
await tx.delete(routineRuns).where(eq(routineRuns.companyId, id));
await tx.delete(routineTriggers).where(eq(routineTriggers.companyId, id));
await tx.delete(routineRevisions).where(eq(routineRevisions.companyId, id));
await tx.delete(routines).where(eq(routines.companyId, id));
await tx.delete(issueReadStates).where(eq(issueReadStates.companyId, id));
await tx.delete(documents).where(eq(documents.companyId, id));
await tx.delete(issues).where(eq(issues.companyId, id));
await tx.delete(companyLogos).where(eq(companyLogos.companyId, id));
await tx.delete(assets).where(eq(assets.companyId, id));
await tx.delete(goals).where(eq(goals.companyId, id));
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))
.returning();
return rows[0] ?? null;
}));
await tailscaleDeletion.stopNetworks();
return deleted;
}