Files
PaperClipAI/server
DottaandClaude Opus 5.5 54cde3353b perf(recovery): back off assigned-work re-checks that find the same refused state (#21691)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The assigned-work sweep checks every open task assigned to an agent
(`todo`, `in_progress`, `blocked`). When a task has nothing running,
nothing pending and no one else's move, it claims one automatic
continuation and asks the wake queue to start it.
> - When the wake queue refuses that continuation, the claim is recorded
as "not started" and the task is checked again 90 seconds later. The
per-task spacing (2, 4, 8, then 15 minutes) lets it claim again. The
refusal is not counted toward the hourly cap, so this never ends.
> - Each cycle reads all of the task's facts, writes an activity entry
and saves a skipped wake row. For 10 such tasks this is about 5,000
statements and 50 claims per hour, forever, on an idle server.
> - This pull request stores a fingerprint of the task's facts with each
refused continuation. A later check that finds the same facts waits,
with reads only, on a backoff that doubles to a 6-hour ceiling.
> - The benefit is that a task that cannot progress costs almost nothing
while idle, and any real change on the task is still picked up within
seconds.

## Linked Issues or Issue Description

No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.

**What happened?**

`act` in `server/src/services/recovery/assigned-work-sweep.ts` repairs a
`no_pending_path` or `retry_offered` task with `deps.enqueueWakeup`.
When admission refuses (for example the assignee has `wakeOnDemand:
false`), `act` returns `enqueue_refused` with `retryAt` 90 seconds
later. The next check claims again as soon as `continuationAllowance`
allows: 2, 4, 8, then 15 minutes. Refused claims do not count toward
`CONTINUATION_CAP`, so the task is re-claimed forever. Each claim writes
an `issue.assigned_work_continued` activity entry ("could not start yet.
It will try again shortly."), and each wake attempt saves a skipped wake
row.

Census on a staging-shaped fixture (real PostgreSQL, real report): 60
tasks in review, 10 running, 5 assigned to a paused agent and 10 whose
continuation is refused. Only the 10 refused tasks are violations
(`retry_offered`). Tasks in review are not in the sweep's scope at all,
and a paused assignee is an "agent paused" wait. So on a hosted instance
where most open tasks are in review, only the tasks whose continuation
is refused pay this cost. One claim check costs 102 statements. A
backed-off re-check costs 34 statements and writes nothing.

**Expected behavior**

A re-check that finds the same state as the last refused continuation
stores nothing and backs off. A real change on the task (a run finishes,
a status change, an assignment, a budget or pause change, a new wake)
re-checks it promptly.

**Steps to reproduce**

1. Create 10 tasks in `in_progress`, assigned to an agent with
`runtimeConfig.heartbeat = { enabled: false, wakeOnDemand: false }`,
each with a failed run.
2. Start the issue-state recovery work (it registers the assigned-work
sweep).
3. Leave the instance idle. The sweep claims and is refused about every
2 to 15 minutes per task, forever.

**Paperclip version or commit**

master at 3eabdd6d10.

## What Changed

- `server/src/services/recovery/assigned-work-sweep.ts`:
- `act` computes a fingerprint of the task's facts and the violation
(`stateKey`, without the task's `updatedAt`, which a refused claim on a
blocked task rewrites). Before it claims, it reads the task's latest
continuation entries (`refusalsInState`, one indexed read). When the
newest entries are refused continuations with the same fingerprint, it
waits until the last refusal plus 2 minutes, doubled per refusal, up to
6 hours. That check returns the new outcome `waiting_unchanged` and
writes nothing.
- A refused continuation (the ordinary path and the stalled-run
replacement) stores `stateKey` and `refusedAt` in its activity entry.
From the second refusal in the same state, the entry says "Paperclip
still could not start this task. It will keep trying, less often each
time, and right away when something on the task changes."
- The agent fact now carries the agent's `updatedAt`, so a change to the
agent's configuration changes the fingerprint.
- `server/src/services/recovery/work.ts`: a task that waits on
`waiting_unchanged` is marked on its queue entry. When an event reloads
the task, the entry becomes due at once instead of keeping the later
deadline. A backstop reload keeps the deadline.
- `server/src/services/recovery/assigned-work-invariant.ts`: the new
activity text, and the optional `updatedAt` on the agent fact.
- `server/src/__tests__/assigned-work-invariant.test.ts`: the "too soon"
check after a refusal now reports `waiting_unchanged` instead of
`deferred_rate_limit`.
- `server/src/__tests__/assigned-work-recheck-idle.test.ts`: three new
tests on real PostgreSQL with the real coordinator, the real issue-state
recovery work and a fake clock.

What the user sees: the first refused continuation still says "could not
start yet. It will try again shortly." Later refusals in the same state
say Paperclip keeps trying less often. The task stays assigned, and any
Retry the task shows is unchanged.

About `retry_offered`: the request was to treat it as "a person was
offered Retry, so nothing re-checks until they act". The code does not
support that reading. `retry_offered` is defined as "the visible state
offers a Retry that only the system can act on", and the sweep continues
it so that the person does not need to press Retry. A rule that stops
after one refusal would turn every transient refusal into a task that
needs a person. So this pull request gives `retry_offered` the same
backoff as `no_pending_path`. A person's Retry or message is still an
event that re-checks the task at once.

## Verification

- `pnpm exec vitest run src/__tests__/assigned-work-recheck-idle.test.ts
src/__tests__/assigned-work-invariant.test.ts` (in `server/`), 35 tests
pass.
- `backs off while every check finds the same refused state`: 10 refused
tasks, measured on the fake clock.

| Window | master claims | master statements | this branch claims | this
branch statements |
    | --- | --- | --- | --- | --- |
    | first idle hour | 50 | 5,060 | 40 | 5,078 |
    | idle hours 1 to 6 | 1,460 | 147,752 | 21 | 2,866 |

The master numbers after the first hour are inflated by the test: the
cap and spacing read activity `created_at`, which comes from the
database clock, not the fake clock, so after one fake hour master spaces
claims by only 2 minutes. At the production spacing (15 minutes, about 6
claims per task per hour), master would do about 300 claims and 25,000
statements in the same 5 hours. The assertion (at most 30 claims and
fewer than 5,000 statements in hours 1 to 6) fails on master and passes
on this branch.
- `re-checks a backed-off task within two minutes when one of its runs
finishes`: after 3 idle hours, a new failed run of one task is notified.
Within 2 minutes (the 90-second settling grace) the sweep claims that
task again. Without the `work.ts` change, the event keeps the backed-off
deadline and this test fails.
- `leaves review work alone and re-checks a refused task with reads only
while it waits`: the census above, plus one claim check (102 statements,
writes an activity entry) and one backed-off re-check (34 statements, no
insert, update or delete).
- Neighbouring suites pass locally: `assigned-work-sweep-round-trips`,
`assigned-work-stalled-queued-run`,
`failed-continuation-continues-again`,
`automatic-run-brake-recovery-passes`,
`issue-recovery-recorded-decision-idle`, `recovery-wake-herd`,
`issue-recovery-signal-fanout`, `saved-work-recovery-overdue`.
- `npx tsc --noEmit -p server/tsconfig.json` passes.

## Risks

- A refusal whose cause clears without any change to the task's facts or
a reloading event (for example a scheduling suppression that lifts) is
retried on the backoff, at most 6 hours later, instead of within 15
minutes. Changes to the task, its runs, its wakes, the agent row, budget
or company pause change the fingerprint and claim at once.
- The fingerprint covers the full fact set. A fact that changes on every
check would turn the backoff off for that task and keep the master
behavior. The idle test shows that the refused fixture keeps a stable
fingerprint.
- An event that reloads a backed-off task now re-checks it at once. That
check is read-only while the state is the same (34 statements).
- No schema or API change. The new fields live in the existing activity
`details` JSON.
- Separate finding, not changed here: a task whose pending continuation
counts as its pending path is not re-checked when that continuation's
bound ends unless something reloads it. With continuation delivery
running this is rare, but it is a missed re-check rather than a loop.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, local PostgreSQL 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
- [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

Related: #21687, #21621, #21674, #21675, #21676, #21617.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:42:25 -06:00
..