Files
PaperClipAI/server
df371acc77 fix(recovery): give fresh runs a grace period before the issue-terminal sweep (#13883)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The control plane keeps issue ownership and run liveness in separate
rows, and a recovery sweep reconciles them.
> - That sweep can terminalize a `running` heartbeat row on two
authorities: a dead process, or a terminal issue above a live row.
> - The issue-terminal authority infers orphanhood from the issue status
alone. It does not observe the run.
> - A reassignment hand-off satisfies that inference while it is
healthy: one request sets the issue to `done` and reassigns it, so the
receiving agent's run starts while the issue is momentarily terminal and
still holds the lock columns.
> - The sweep then kills a run that is seconds old and releases the
checkout it just acquired.
> - This pull request requires the row to have stayed `running` for 60
seconds before the issue-terminal authority applies.
> - The benefit is that a reassignment hand-off completes instead of
failing with an ownership conflict on a checkout that returned 200.

## Linked Issues or Issue Description

No public GitHub issue exists for this bug.

Related pull requests:

- Refs #13271. That pull request makes a live in-memory executor
authoritative over both authorities. It fixes the case where one run
sets its own issue terminal and keeps writing. It does not close the
window this pull request closes. See "Relationship to #13271" below.

**What happened?**

An agent set an issue to `done` and reassigned it in the same `PATCH`.
The server started the receiving agent's run. The issue was still
terminal and still held `checkout_run_id` and `execution_run_id`. The
stale-lock sweep read the terminal issue as proof that the new run was
orphaned. The sweep marked the run terminal after about 700 ms and
cleared the lock columns. The receiving agent had already received `200`
from its checkout. Every later status write from that agent failed with
an ownership conflict.

**Expected behavior**

The sweep must not terminalize a run that is seconds old on the strength
of the issue status alone. A run that just acquired a checkout must keep
it.

**Steps to reproduce**

1. Assign an issue to agent A and let its run check the issue out.
2. Send one `PATCH` that sets the issue to `done` and reassigns it to
agent B.
3. Let the server start agent B's run. The issue still holds both lock
columns.
4. Run the stale issue-lock sweep inside the first seconds of that run.
5. See the sweep mark agent B's run `succeeded` with error code
`orphaned_running_run_issue_terminal`.
6. Send a status write from agent B. See the ownership conflict.

**Paperclip version or commit**

`master` at `60c7c9cd1`.

**Deployment mode**

Self-hosted server with PostgreSQL. The defect is in the shared run
lifecycle. It is not specific to an adapter.

## What Changed

- Added `ISSUE_TERMINAL_MIN_RUN_AGE_MS` (60 seconds) to
`server/src/services/recovery/service.ts`.
- Suppressed the issue-terminal authority in
`terminalizeOrphanedRunningRun` while the run row is younger than that
age, and logged a warning when the suppression fires.
- Left the process-death authority unchanged, so a dead process is still
swept immediately at any run age.
- Made the two reuse-lease tests seed an aged run row, because an orphan
is by definition a row that stayed `running`.
- Added a test for the reassignment hand-off. It asserts that the fresh
run survives and that both lock columns survive.
- Added a test for a fresh run with a dead recorded pid. It asserts that
the sweep still terminalizes the run as `interrupted` and still clears
the locks.

## Relationship to #13271

#13271 moves the `liveRunExecutions` check to an early return, so it
covers both authorities. That is a good change and this pull request
composes with it. It does not cover this window, for two reasons.

1. The run row reaches `running` before the execution registers itself.
`activeRunExecutions.add(run.id)` runs inside the execution body, after
awaited database work. A sweep that fires in that gap sees no live
execution. The run also has no recorded pid yet, so the process-death
authority stays silent by design. The issue-terminal authority is the
only one left, and it fires.
2. `activeRunExecutions` is a module-scope `Set`. It is per server
process. A sweep on one process cannot see an execution owned by
another.

The grace period covers both, because run age is in the row itself.

## Verification

- `node scripts/run-vitest-stable.mjs
server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts` is the
target suite. I could not run it in my environment: the suite needs
embedded PostgreSQL, and my sandbox has no host for it. I ask CI to be
the check here. Please do not merge on a red run.
- I did verify the guard logic directly. I extracted the compiled guard
and drove it against seven cases: a 700 ms run under a `done` issue, a
59 s run, a 61 s run, a one-hour run under a `cancelled` issue, a row
with no usable timestamp, an ISO string timestamp, and a null issue
status. All seven matched the intended outcome, and the warning fired
only on the three suppressed cases.
- I traced the single call site. `sweepStaleIssueLocks` builds `runRows`
with `db.select()` and no projection, so `run.createdAt` is always
present at run time. There is no other caller.
- Reviewers can reproduce the bug with the six steps above. The new
hand-off test fails on `master` and passes with this change.

## Risks

Low, and the direction of the failure is the safe one.

- A genuinely orphaned run now keeps its lock for up to one extra sweep
tick. The sweep is periodic, so the next tick clears it. Nothing is
stranded.
- The guard fails open. If the row carries no usable timestamp, the
sweep behaves as it does today.
- The process-death authority is untouched. A hard crash is still reaped
at once.
- Two existing tests changed their fixture, not their assertions. They
still assert that the sweep terminalizes the run and clears the lock.
- The 60 second value is a constant, so an operator who needs a
different window changes one line.

## Model Used

Claude Opus 4.7 (`claude-opus-4-7`) by Anthropic, through Claude Code
with tool use and extended thinking.

## 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
- [ ] I have run tests locally and they pass — the suite needs embedded
PostgreSQL, which my environment cannot start. See Verification.
- [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 — pending the first CI run
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
pending review
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Builder <builder@nublo.net>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-12-04 17:37:31 -08:00
..