Files
PaperClipAI/server
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
..