mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - During a release swap, the outgoing server drains. It must not start new runs, because its own exit would cut them off. > - The drain gate (run admission closed at SIGTERM) and the hand-over gate (#21127, yield to a replacement that already dispatches) were checked only by the queued-run dispatch passes. > - Other start paths (executeRun of a queued run, delivered continuations, immediate wake starts) went straight to `claimQueuedRun`, so an outgoing server could still start runs after traffic moved. > - Also, a system continuation queued while its task was open started after another run had finished the task, and took an extra turn on a done task. > - This pull request makes `claimQueuedRun`, which every start path uses, honour the drain and hand-over gate, and cancel a system continuation whose task closed while it was queued. > - The benefit is fewer runs cut off by a swap, and no extra turns on finished tasks. ## Linked Issues or Issue Description Refs #21127, #21135 **What happened?** 1. An outgoing server kept starting runs minutes after traffic moved to its replacement. Each such run was cut off when the old server exited. The run start went through `executeRun` of a queued run, which called `claimQueuedRun` without the drain or hand-over check. 2. In release-swap waves, a continuation (execution reconciliation delivery, invariant or recovery continuation, blocker-stall wake) was queued while its task was open. Another run then finished the task. The continuation still started and took an extra turn on a done task. **Expected behavior** A draining or yielding server leaves a queued run queued for the serving server, on every start path. A system continuation does not start on a task that was closed while it was queued. A person's message on a done task still runs. **Steps to reproduce** 1. Close run admission (drain) or set the hand-over yield on a server. 2. Start a queued run through `executeRun` (for example a delivered continuation). 3. See the run claimed and started on the draining server. ## What Changed - `claimQueuedRun` (`server/src/services/heartbeat/queue.ts`) refreshes and checks the run-admission gate first. When admission is closed (draining or yielding), it leaves the run queued and returns. The dispatch passes already did this check; now every start path does. - `claimQueuedRun` re-reads the task for a system continuation (`issue_recovery_action_restored`, `issue_continuation_needed`, `issue_assignment_recovery`, blocker-stall wake). If the task is `done` or `cancelled`, it cancels the run as `issue_closed_before_start`, skips its wake, and releases the task. Other wake reasons, including a person's message, are not affected. - That cancel never consumes a person's message. Admission can attach deferred comments to a queued system continuation without changing its wake reason. The cancel locks the run's wake and the run (the order admission's coalescing uses), reads the run's current comment ids, and if any is a person's comment that no run of this agent has received yet (read-only use of `deliveredQueuedCommentIds`, which includes the history-read rule), the run is not cancelled: it is claimed as that person's follow-up, which may reopen the task through the normal path. A comment attached concurrently is either seen under the lock or, after the cancel commits, saved behind the cancelled run by admission. - Admission is checked again inside each claim transaction (ordinary claim, queued-comment claim, native review claim), right after the write that moves the run to `running`. If admission closed during the awaited checks, the transaction rolls back: the run stays queued with no `startedAt`, its wake and the task's execution lock are untouched, and nothing is charged. - Every cancellation `claimQueuedRun` makes from the caller's copy of the run is now a compare-and-set from `queued` (`setRunStatusFromLive(..., ["queued"])` through a new `cancelRunIfStillQueued` helper): the closed-task cancel, the refused-interaction cancel, the missing-@mention cancel, the daily-cap cancel and the blocked-dependency cancel. A run another dispatcher already started or finished keeps its status and result, and no wake or release follows. The queue module no longer receives the unconditional `setRunStatus`. - The closed-task cancel takes its decision under the wake and run locks, then cancels through `setRunStatusFromLive` fenced on the row version (`xmin`) the decision read. That saves the same never-started proof (`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`) as every other queued-run cancel, so task release promotes a person's message saved behind it. A message attached after the decision changes the run, the cancel matches nothing and the decision is taken again. `HeartbeatRecoveryDependencies.setRunStatusFromLive` (`recovery.ts`) now types its existing `cancellationCondition` parameter as `SQL`. - The dispatch ranking in `startNextQueuedRunForAgent` is not changed. ### What I checked in `claimQueuedRun` for writes from the caller's copy - Cancellations through `setRunStatus`: all five now conditional on `queued` (above). - The final claims (ordinary, queued-comment, native review) already lock and re-read the run and update `where status = 'queued'`. - The case-handoff cancel and the chat-control stop already lock the run and update `where status = 'queued'`. - The budget-stamp update already writes `where status = run.status` (`queued`). - `cancelRunInternal` (agent removed, agent not invokable, board-owned budget stop, pause hold, budget cancel) re-reads the run and only cancels a non-terminal status, so it cannot overwrite a finished result. It can still stop a run another server has just started; that is a policy stop (agent removed, budget, hold) that would apply to that run anyway, and it is unchanged here. - `cancelStaleQueuedRun` already takes `expectedStatus: "queued"`. ## Verification Red-to-green tests in `server/src/services/heartbeat/queue.test.ts`: - "claims no queued run once run admission is closed, whatever path asks (draining or yielding server)": red before the gate was added to `claimQueuedRun`, green after. - "does not start a %s run whose task another run already finished": `issue_continuation_needed` and `issue_recovery_action_restored` are cancelled as `issue_closed_before_start`; `issue_commented` (a person's message, carrying its `wakeCommentId`) is claimed and the stored run is `running`. - "answers a person's message attached to a system continuation on a closed task once": still undelivered, the continuation is claimed and is the only unfinished run (red when the cancel ignores comment ids, green after); already received by the closing run, the continuation is cancelled as `issue_closed_before_start` and no other run exists. - "keeps the result of a continuation another dispatcher already started and finished": the stale queued copy is passed after the run succeeded; the stored run stays `succeeded` with its result, and no wake or release follows. Red before the compare-and-set (the run was overwritten to `cancelled`), green after. - "returns the claim to the queue when run admission closes while the claim is being checked": admission closes inside an awaited check; the run stays `queued` with no `startedAt`, the task's execution lock and the wake are unchanged. Red before the in-transaction re-check, green after. Red-to-green test through the real release path, in `server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts`: - "delivers a person's message saved behind a system continuation cancelled at claim because its task closed": a never-started legacy continuation on a done task, with a person's deferred message behind it. Red before the fix: the cancelled run had `resultJson: null`, with no never-started proof. Green after: the proof is present, the wake is skipped, and the message is promoted and runs once. Test expectations changed because they asserted the old behaviour: - `server/src/services/agent-interaction-delivery.test.ts` "cancels refused queued runs through the public queue claim without dispatch": now expects the cancel through `setRunStatusFromLive(runId, "cancelled", ["queued"], …)` instead of `setRunStatus`. - `server/src/services/heartbeat/queue.test.ts` (refused-assignment held case): asserts `setRunStatusFromLive` is not called, instead of `setRunStatus`. - The `issue_commented` case of "does not start a %s run…" now asserts the run is claimed and `running` (it previously asserted only that the error code was not `issue_closed_before_start`). Local command, on this branch based on current master (includes #21234; the dispatch ranking it changed is untouched here): - `cd server && pnpm exec vitest run src/services/heartbeat/queue.test.ts src/__tests__/recovery-wake-herd.test.ts`: 102 tests passed. After the proof fix, `queue.test.ts` again passed 97/97, and the new stale-queue test passed. (The file's `afterAll` database cleanup hook times out on this loaded machine on master too; it is not related to this change.) Why the local release-swap wave does not show the yield fix: - The "yield to the replacement" signal exists only when the run-start handover is created (`server/src/index.ts`, about line 1320). That happens only when a direct deployment listen URL exists, that is, with `PAPERCLIP_EPHEMERAL_SERVER=true` and `PAPERCLIP_DATABASE_LISTEN_URL` (the volume-free configuration). - The local short form of the wave leaves `--ephemeral-server` out, so the handover is disabled and `isRunAdmissionClosed()` becomes true only at SIGTERM. The wave therefore cannot exercise the yield. - The evidence for this fix is the unit test above and the reasoning that every start path now reaches the same gate in `claimQueuedRun`. Hosted confirmation must come from a volume-free instance. - The closed-task fix was found in release-swap waves (an extra turn on a done task in two tasks). ## Risks - `claimQueuedRun` can now await an admission refresh. The refresh returns at once when the cached state is fresh, so the normal path adds no wait before `turn.start`. - A system continuation for a closed task is cancelled. This matches admission, which already refuses such wakes for a closed task. - No migration. No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use (shell, file edit, test runs). ## 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 - [ ] I have updated relevant documentation to reflect my changes (no documented behavior or command 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>