Files
PaperClipAI/server/src/__tests__
045cf74081 fix(heartbeat): promote wakes deferred behind a queued run the claim gate withdraws (#20859)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat wake queue parks a wake in `deferred_issue_execution`
while another run holds the task's execution lock. Only the holder's
release drain promotes the parked wake
> - A queued run can hold that lock before it starts. Wake admission
adopts a queued run on the task when the lock column is empty, and
deferred-wake promotion stamps the lock only for the assignee
> - When the claim-time execution gate withdraws that queued run as
stale (for example `issue_assignee_changed`), `claimQueuedRun` clears
the lock and returns. It does not run the release drain
> - The parked wake then waits until an unrelated event, such as a new
comment, arrives. The other pre-start cancellations in the same claim
(the mention gate and the daily cap) already release the task
> - This pull request releases the task after a gate withdrawal, with
the same call that the mention gate uses
> - The benefit is that a parked wake starts as soon as the run it
waited behind is withdrawn

## Linked Issues or Issue Description

No issue describes this exact path, so I describe it here.

**What happened?**

1. Agent A is the assignee of a task. A asks agent B a question on the
task. B's wake is deferred behind A's live run.
2. A's run ends. The release drain promotes B's wake into a run. B is
busy elsewhere, so that run stays `queued`. Promotion does not write the
task lock, because B is not the assignee.
3. B answers the question from another run. The answer wakes A.
Admission finds the lock column empty, adopts B's queued run as the
holder, and parks A's wake in `deferred_issue_execution`.
4. B gets capacity. The claim-time gate withdraws B's queued run
(`issue_assignee_changed`, `startedAt: null`), because the question is
no longer pending. The gate clears the lock.
5. Nothing promotes A's wake. It stays deferred until a new comment
arrives. We saw waits of more than 40 minutes.

**Expected behavior**

When the run that a wake waits behind ends in any state, including a
cancellation before start, the oldest eligible deferred wake is
promoted.

**Steps to reproduce**

The new test
`server/src/__tests__/heartbeat-deferred-wake-after-stale-queued-cancel.test.ts`
reproduces it with the real `heartbeatService` on embedded Postgres. It
covers a plain non-assignee queued run and the answered-question shape
above.

**Related**

- Refs #18838 and #15483. #18838 exempts a never-started gate
cancellation from reconciliation. Without #18838 the release drain
refused to run for the withdrawn run, and the periodic stranded-queue
sweep could not promote the wake either. This pull request adds the
missing release call after that fix.
- Refs #20256: the deferral of an addressee's wake behind a live run. It
is the same adoption path seen from the other agent's side. This pull
request does not change the deferral.
- Refs #16202: a periodic pass that force-releases stale locks held by a
former assignee's non-running run. It is a different mechanism and does
not cover the claim gate.
- Refs #14082, #14879, #1269, #10270: other paths that leave a deferred
wake without a drain.

## What Changed

- `server/src/services/heartbeat/queue.ts`: after `cancelStaleQueuedRun`
returns `cancelled`, `claimQueuedRun` calls
`releaseIssueExecutionAndPromote(run, { suppressImmediateRecovery: true,
deferredPostCommitEffects })`. This is the same call that the
mention-gate cancellation makes in the same function, under the same
agent start lock. A refusal with `execution_reconciliation_required`
does not release, because its saved wakes belong to the existing
execution hold, and the wake-queue drain does not check execution holds.
- Add the regression test
`server/src/__tests__/heartbeat-deferred-wake-after-stale-queued-cancel.test.ts`.
- Add one paragraph to `doc/execution-semantics.md`.

## Verification

From `server/`, with Node 24:

- `npx vitest run
src/__tests__/heartbeat-deferred-wake-after-stale-queued-cancel.test.ts`:
both cases pass. Without the change in `queue.ts`, both cases fail: the
wake stays `deferred_issue_execution` and no run is created for it. With
the change, the promoted run runs to `succeeded`.
- Related suites, one file or module at a time:
`heartbeat-stale-queue-invalidation`,
`heartbeat-lock-release-on-reassignment`,
`satisfied-connection-intents`, `legacy-continuation-authority`,
`heartbeat-undispatched-execution-wait`,
`heartbeat-task-drain-admission-release`,
`heartbeat-dependency-scheduling`, `heartbeat-retry-scheduling`,
`durable-chat-wakeup`, `heartbeat-responsible-user-invariant`,
`agent-conversation-delivery`, `src/modules/run-dispatch` and
`src/modules/wake-queue`: 882 tests pass. A single run of about 76
related files did not finish within 55 minutes on this host, so I ran
them one at a time.
- `npx tsc --noEmit`: 318 errors on this host, the same count as
unmodified `master`, none in the changed files. The host has no `cargo`,
so the runner vendor files do not build.

I did not run `pnpm build`, the full `pnpm test:run` or the browser
suites, because the build needs `cargo`.

## Risks

- Low risk. A withdrawn queued holder now drains the deferred queue, as
a finishing holder already does. A promoted wake still passes every
admission and claim gate (ownership, pause holds, budget, approvals,
dependencies). If it is also stale, the same gate withdraws it.
- The release runs inside the claim, under the agent start lock, like
the mention-gate path. Post-commit effects are collected in
`deferredPostCommitEffects` when the caller supplies it.

## Model Used

- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used as a
coding agent in Claude Code with tool use (shell, file edit) and
extended reasoning. A human owner approved sending this change upstream.

## 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: LiterallyBlah <22526586+LiterallyBlah@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 04:10:07 -08:00
..
…

Server Tests

Server tests that need a real PostgreSQL process must use ./helpers/embedded-postgres.ts instead of constructing embedded-postgres directly.

The shared helper creates a throwaway data directory and a reserved-safe loopback port for each test database. This protects the live Paperclip control-plane Postgres from server vitest runs; see PAP-2033 for the incident that introduced this guard.