fix(setup-token): back off cleanup retries after failed sweeps (#19446)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A setup-token login keeps a durable cleanup record. The setup-token
reaper releases its provider lease and removes the record
> - A sweep that fails keeps the record and retries on the next
30-second tick, for as long as the failure lasts
> - During a provider outage, that is a steady stream of provider calls
and log lines with no recovery benefit
> - This pull request backs off consecutive failed sweeps from 30
seconds to 30 minutes and resets after a successful sweep
> - The benefit is less load and log noise during outages, with the same
recovery once the provider is back

## Linked Issues or Issue Description

Refs #14777 (fixed by #15200 and #22667; this pull request adds the
retry backoff that the report also asked about).

This pull request was rebased onto `master` and reduced to the backoff.
#15200 already makes a blank lease lookup return null, and #22667
already logs the failure class and code and covers a restart with a
PostgreSQL test. The earlier redacted-message logging is removed,
because the reaper now logs no error message.

**What happened?**

When a setup-token cleanup sweep fails, for example because the sandbox
provider is down, the cleanup worker retries every 30 seconds until the
failure ends. Each retry calls the provider again and logs again.

**Expected behavior**

Repeated failures back off. A successful sweep returns to the normal
interval.

**Steps to reproduce**

1. Make `releaseById` fail for a reapable setup-token record.
2. Watch the setup-token cleanup worker. It retries the release every 30
seconds without a limit.

## What Changed

- `setup-token-reaper.ts`: count consecutive failed sweeps (a sweep with
a failed record, or a sweep that throws). `retryDelayMs()` returns 30 s,
60 s, 120 s and so on up to 30 min, and 0 after a successful sweep.
- `login-cleanup-work.ts` and `index.ts`: the setup-token cleanup duty
passes `retryDelayMs` to the shared scheduler. The next run waits for
the larger of the configured interval and the backoff delay.
- `setup-token-session.ts`: skip the provider call for a reapable record
with no lease id and remove the record directly.
- `index.ts`: the sweep log line says "cleared records", because a
record without a lease is cleared with no release.
- `setup-token-session.ts`: the failure log line says "a cleanup
failed", because a failure can now come from removing the record as well
as from the provider release.
- `doc/heartbeat-internals.md`: document the retry behavior.
- Tests: backoff to the cap and reset (`setup-token-reaper.test.ts`),
backoff after a thrown sweep, removal of records without a lease, and
the scheduler honoring the backoff across notifications for both a sweep
with failed records and a sweep that throws
(`login-cleanup-work.test.ts`).

## Verification

- `pnpm exec vitest run server/src/services/setup-token-reaper.test.ts
server/src/__tests__/login-cleanup-work.test.ts
server/src/services/setup-token-session.test.ts`: 3 files, 98 tests
passed.
- The seven new tests fail without the source changes.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- The backoff applies to the whole setup-token cleanup worker. While one
record keeps failing, new cleanup can wait up to 30 minutes. Records
stay in the database, so nothing is lost.
- The failure count lives in memory and resets on restart. The retained
rows rebuild the cleanup work.

## Model Used

- Original change by the pull request author. Rebased and reduced by
Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file
edit, and code execution tools.

## 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
This commit is contained in:
Dotta authored and GitHub committed 2026-11-23 13:15:08 -08:00
1 parent 8ce422e45d
commit 4434d12e2f
7 files changed
+152 -14

No files matched your search

@@ -64,6 +64,64 @@ describe("login cleanup lifecycle", () => {
release(); await vi.advanceTimersByTimeAsync(30_000);
expect(run).toHaveBeenCalledTimes(3); expect(c.nextWakeAt()).toBeNull();
});
it("honors setup-token backoff across notifications, then becomes quiet", async () => {
vi.useFakeTimers();
const owner = fakeOwner();
const c = coordinator(owner);
let failures = 0;
let pending = true;
const reaper = createSetupTokenReaper({
store: {
listReapable: async () => pending ? [{ sessionId: "retry", companyId: "company", ownerUserId: "user", adapterType: "claude_local", environmentId: "env", leaseId: "lease", state: "failed", deadline: 0, boundAt: null }] : [],
remove: async () => { pending = false; },
},
leases: { releaseById: async () => { failures += 1; if (failures < 3) throw new Error("provider down"); } },
});
const run = vi.fn(reaper.sweep);
await registerLoginCleanupWork(c, [{ queue: DELIVERY_QUEUES.setupTokenCleanup, run, next: async () => pending ? Date.now() : null, retryDelayMs: reaper.retryDelayMs }], () => true).ready;
expect(run).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(30_000);
expect(run).toHaveBeenCalledTimes(2);
await owner.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.setupTokenCleanup));
await vi.advanceTimersByTimeAsync(59_999);
expect(run).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1);
expect(run).toHaveBeenCalledTimes(3);
await vi.advanceTimersByTimeAsync(120_000);
expect(c.nextWakeAt()).toBeNull();
expect(run).toHaveBeenCalledTimes(3);
});
it("backs off a setup-token sweep that throws through the worker, then becomes quiet", async () => {
vi.useFakeTimers();
const owner = fakeOwner();
const failures: unknown[] = [];
const c = coordinator(owner, () => true, error => failures.push(error));
let outages = 2;
const reaper = createSetupTokenReaper({
store: {
listReapable: async () => { if (outages > 0) { outages -= 1; throw new Error("database unavailable"); } return []; },
remove: async () => {},
},
leases: { releaseById: async () => {} },
});
const started = Date.now();
const attempts: number[] = [];
const run = vi.fn(async () => { attempts.push(Date.now() - started); return reaper.sweep(); });
await registerLoginCleanupWork(c, [{ queue: DELIVERY_QUEUES.setupTokenCleanup, run, next: async () => outages > 0 ? Date.now() : null, retryDelayMs: reaper.retryDelayMs }], () => true).ready;
expect(attempts).toEqual([0]);
await vi.advanceTimersByTimeAsync(30_000);
expect(attempts).toEqual([0, 30_000]);
await owner.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.setupTokenCleanup));
await vi.advanceTimersByTimeAsync(59_999);
expect(attempts).toEqual([0, 30_000]);
await vi.advanceTimersByTimeAsync(1);
expect(attempts).toEqual([0, 30_000, 90_000]);
await vi.advanceTimersByTimeAsync(120_000);
expect(attempts).toHaveLength(3);
expect(reaper.retryDelayMs()).toBe(0);
expect(failures).toHaveLength(2);
expect(c.nextWakeAt()).toBeNull();
});
it("does not block another cleanup worker and awaits in-flight work on shutdown", async () => {
vi.useFakeTimers(); const c = coordinator(fakeOwner()); let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
+2 -2
View File
@@ -1772,7 +1772,7 @@ async function startServerWithDatabaseTeardown(
result: Awaited<ReturnType<typeof setupTokenReaper.sweep>>,
) => {
if (result.released > 0 || result.failed > 0) {
logger.info(result, "setup-token login reaper released leases");
logger.info(result, "setup-token login reaper cleared records");
}
};
@@ -2036,7 +2036,7 @@ async function startServerWithDatabaseTeardown(
const loginSchedule = loginCleanupSchedule(db, config.heartbeatSchedulerIntervalMs);
await step("login_cleanup_workers", () => registerLoginCleanupWork(deliveryWork, [
{ queue: DELIVERY_QUEUES.adapterLoginCleanup, run: () => adapterLoginReaper.sweep().then(logAdapterLoginReaperResult), next: loginSchedule.adapter },
{ queue: DELIVERY_QUEUES.setupTokenCleanup, run: () => setupTokenReaper.sweep().then(logSetupTokenReaperResult), next: loginSchedule.setupToken },
{ queue: DELIVERY_QUEUES.setupTokenCleanup, run: () => setupTokenReaper.sweep().then(logSetupTokenReaperResult), next: loginSchedule.setupToken, retryDelayMs: setupTokenReaper.retryDelayMs },
], () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped, config.heartbeatSchedulerIntervalMs).ready);
// Retry any orphan sandbox teardown left by a failed acquire before a
// server restart, so a leaked sandbox does not stay allocated.
+6 -3
View File
@@ -4,7 +4,7 @@ import { LOGIN_CLEANUP_RETRY_MS } from "./login-cleanup-state.js";
export function registerLoginCleanupWork(
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
duties: ReadonlyArray<{ queue: LoginCleanupQueue; run: () => Promise<unknown>; next: () => Promise<number | null> }>,
duties: ReadonlyArray<{ queue: LoginCleanupQueue; run: () => Promise<unknown>; next: () => Promise<number | null>; retryDelayMs?: () => number }>,
canRun: () => boolean,
retryMs = LOGIN_CLEANUP_RETRY_MS,
) {
@@ -25,8 +25,11 @@ export function registerLoginCleanupWork(
return;
}
const generation = ++requested;
earliestRunAt = now + retryMs;
await duty.run();
try {
await duty.run();
} finally {
earliestRunAt = Date.now() + Math.max(retryMs, duty.retryDelayMs?.() ?? 0);
}
const deadline = await duty.next();
next = deadline === null ? null : Math.max(deadline, earliestRunAt);
reconciled = generation;
+56 -3
View File
@@ -78,6 +78,59 @@ describe("setup-token reaper", () => {
expect(store.rows.size).toBe(0);
});
it.each(["failed", "cancelled", "completed"] as const)("removes a %s record without a lease", async state => {
const store = createMemoryStore();
store.seed({ sessionId: "no-lease", leaseId: "", state });
const leases = createFakeLeases({ releaseImpl: async () => { throw new Error("invalid uuid"); } });
const reaper = createSetupTokenReaper({ store, leases, now: () => NOW });
expect(await reaper.sweep()).toEqual({ released: 1, failed: 0 });
expect(leases.releaseByIdCalls).toEqual([]);
expect(store.rows.size).toBe(0);
expect(await reaper.sweep()).toEqual({ released: 0, failed: 0 });
});
it("backs off repeated failures to a cap and resets after recovery", async () => {
const store = createMemoryStore();
store.seed({ sessionId: "retry", leaseId: "lease-retry" });
let failing = true;
const logs: string[] = [];
const leases = createFakeLeases({ releaseImpl: async () => { if (failing) throw new Error("provider down"); } });
const reaper = createSetupTokenReaper({ store, leases, log: line => logs.push(line) });
for (const delay of [30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]) {
expect((await reaper.sweep()).failed).toBe(1);
expect(reaper.retryDelayMs()).toBe(delay);
expect(store.rows.has("retry")).toBe(true);
}
expect(logs[0]).toContain("Cause: Error.");
expect(logs.join("\n")).not.toContain("provider down");
failing = false;
expect((await reaper.sweep()).released).toBe(1);
expect(reaper.retryDelayMs()).toBe(0);
expect(store.rows.size).toBe(0);
});
it("backs off thrown sweeps and resets after the store recovers", async () => {
let unavailable = true;
const error = new Error("database unavailable");
const reaper = createSetupTokenReaper({
store: {
listReapable: async () => { if (unavailable) throw error; return []; },
remove: async () => {},
},
leases: createFakeLeases(),
});
for (const delay of [30_000, 60_000]) {
await expect(reaper.sweep()).rejects.toBe(error);
expect(reaper.retryDelayMs()).toBe(delay);
}
unavailable = false;
expect(await reaper.sweep()).toEqual({ released: 0, failed: 0 });
expect(reaper.retryDelayMs()).toBe(0);
});
it("holds a live, unexpired, unconsumed record and never releases its lease", async () => {
const store = createMemoryStore();
store.seed({
@@ -137,7 +190,7 @@ describe("setup-token reaper", () => {
expect((await reaper.sweep()).failed).toBe(1);
expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: PostgresError (22P02)."]);
expect(lines).toEqual(["[paperclip] Setup-token reaper: a cleanup failed; it stays retryable. Cause: PostgresError (22P02)."]);
});
it("logs the database error that a query wrapper carries as its cause", async () => {
@@ -151,7 +204,7 @@ describe("setup-token reaper", () => {
await reaper.sweep();
expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: DrizzleQueryError > PostgresError (22P02)."]);
expect(lines).toEqual(["[paperclip] Setup-token reaper: a cleanup failed; it stays retryable. Cause: DrizzleQueryError > PostgresError (22P02)."]);
});
it("logs a generic cause for a thrown value that is not an error", async () => {
@@ -163,7 +216,7 @@ describe("setup-token reaper", () => {
await reaper.sweep();
expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: unknown error."]);
expect(lines).toEqual(["[paperclip] Setup-token reaper: a cleanup failed; it stays retryable. Cause: unknown error."]);
});
it("reaps every reapable record in one sweep and stays idempotent on the next", async () => {
+11 -2
View File
@@ -35,10 +35,19 @@ export interface SetupTokenReaperDeps {
*/
export function createSetupTokenReaper(deps: SetupTokenReaperDeps) {
const now = deps.now ?? Date.now;
let failures = 0;
async function sweep(): Promise<SetupTokenReapResult> {
return reapSetupTokenLeases({ store: deps.store, leases: deps.leases, log: deps.log }, now());
try {
const result = await reapSetupTokenLeases({ store: deps.store, leases: deps.leases, log: deps.log }, now());
failures = result.failed > 0 ? Math.min(failures + 1, 7) : 0;
return result;
} catch (error) {
failures = Math.min(failures + 1, 7);
throw error;
}
}
return { sweep };
const retryDelayMs = () => failures === 0 ? 0 : Math.min(30_000 * 2 ** (failures - 1), 30 * 60_000);
return { sweep, retryDelayMs };
}
export type SetupTokenReaper = ReturnType<typeof createSetupTokenReaper>;
+6 -4
View File
@@ -314,9 +314,9 @@ export interface SetupTokenCleanupStore {
/** The counts one reaper sweep produced over the durable cleanup store. */
export interface SetupTokenReapResult {
/** The reapable records whose lease released and whose row cleared. */
/** The reapable records cleared after releasing any lease they held. */
released: number;
/** The reapable records whose lease release failed. The row stays for a retry. */
/** The reapable records whose cleanup failed. The row stays for a retry. */
failed: number;
}
@@ -357,7 +357,9 @@ export async function reapSetupTokenLeases(
let failed = 0;
for (const record of records) {
try {
await deps.leases.releaseById(record.leaseId);
if (record.leaseId) {
await deps.leases.releaseById(record.leaseId);
}
await deps.store.remove({
sessionId: record.sessionId,
companyId: record.companyId,
@@ -367,7 +369,7 @@ export async function reapSetupTokenLeases(
released += 1;
} catch (error) {
failed += 1;
log(`[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: ${releaseFailureCause(error)}.`);
log(`[paperclip] Setup-token reaper: a cleanup failed; it stays retryable. Cause: ${releaseFailureCause(error)}.`);
}
}
return { released, failed };