From 0bff5abd049fd5bf41bb0d9a57dc0cd11d31a755 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 23 Nov 2026 11:52:43 -0800 Subject: [PATCH] fix(setup-token): log why a reaper release fails and guard restart cleanup (#22667) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A Claude subscription login in a sandbox environment runs `claude setup-token` and keeps a durable cleanup row with the session and its provider lease > - The setup-token reaper releases the lease and removes the row when the session is terminal, past its deadline, or consumed > - #14777 reports a reaper that failed to release the same leases every 30 seconds forever after a restart, and logged no cause > - #15200 later fixed the cause: a session with no lease had a blank lease id, and the UUID lookup for it failed on every sweep > - The reaper still discards the error, so the next permanent failure will be just as hard to diagnose, and no test covers the restart case > - This pull request logs the error class and code, and adds a PostgreSQL regression test for the reported restart case > - The benefit is that operators can see why a release fails, and the restart cleanup stays fixed ## Linked Issues or Issue Description Fixes #14777 Refs #15200 (the blank lease id fix). Overlapping open pull requests for the same issue: #15363 (logs the full error message), #16663, #18706, #19446, #18088, #14236. ## What Changed - `setup-token-session.ts`: when a lease release fails, the reaper logs `Cause: ()` for the error and up to three of its causes, for example `DrizzleQueryError > PostgresError (22P02)`. It does not log the error message, because a database or provider message can quote input values. A thrown value that is not an `Error` logs `unknown error`. The record stays retryable, as before. - `setup-token-reaper.test.ts`: three tests for the log line, including a database error wrapped by the query layer. They check that the message text is not logged. - `login-cleanup-work.test.ts`: a PostgreSQL test with the production reaper. A restart left two sandbox setup-token sessions in `submitting` past their deadline, one with no lease and one with a lease. One sweep releases both, the lease goes through the environment driver, and the next sweep finds nothing. With the #15200 guard removed, this test fails with `{ released: 1, failed: 1 }`, which is the reported symptom. What the issue reported, and where it stands on `master`: | Report | State | |---|---| | Release fails every 30 s forever | Fixed by #15200. This PR adds the regression test. | | Reaper swallows the cause | Fixed here. | | Cancel answers `200 {}` and cancels nothing after a restart | The route now falls back to a durable cancel for `starting` and `awaiting_code`. A `submitting` session is not cancellable on purpose (a credential write may be in progress), and the route keeps its uniform `200` answer. Such a session leaves `/active` when its 5-minute deadline passes, and the next sweep releases it. | | No cancel in the UI | The UI now calls the cancel route. | | Local subscription logins | They now use a separate flow (`local-ai-login.ts`). This reaper skips `local_subscription` rows. | ## Verification - `pnpm exec vitest run server/src/services/setup-token-session.test.ts server/src/services/setup-token-reaper.test.ts server/src/__tests__/login-cleanup-work.test.ts`: 3 files, 90 tests passed. - The two log tests fail on `master`. The restart test fails when the #15200 guard is removed. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Low risk. The change adds a log field and tests. - This pull request does not add a startup sweep that ends every live session at boot. In a rolling deploy, an old process can still be completing a login while the new one starts, so the 5-minute deadline stays the recovery path. ## Model Used - 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 --- .../src/__tests__/login-cleanup-work.test.ts | 27 +++++++++++- .../src/services/setup-token-reaper.test.ts | 42 +++++++++++++++++++ server/src/services/setup-token-session.ts | 19 ++++++++- 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/server/src/__tests__/login-cleanup-work.test.ts b/server/src/__tests__/login-cleanup-work.test.ts index 081fc6eece6..f5ea6d84dea 100644 --- a/server/src/__tests__/login-cleanup-work.test.ts +++ b/server/src/__tests__/login-cleanup-work.test.ts @@ -12,7 +12,7 @@ import { loginCleanupSchedule, orphanLoginLeases } from "../services/login-clean import { createDbAdapterAuthSessionStore, LOGIN_LEASE_SESSION_TAG_KEY } from "../services/device-login-service.js"; import { createDeviceLoginReaper, createProductionLoginSessionReaperRuntime } from "../services/device-login-reaper.js"; import { createDbSetupTokenCleanupStore, transitionSetupTokenSessionToStored } from "../services/setup-token-session.js"; -import { createSetupTokenReaper } from "../services/setup-token-reaper.js"; +import { createProductionSetupTokenReaper, createSetupTokenReaper } from "../services/setup-token-reaper.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; const coordinators: ReturnType[] = []; @@ -193,6 +193,31 @@ describe.skipIf(!support.supported)("durable login cleanup", () => { await vi.advanceTimersByTimeAsync(10_000); expect(driver.releaseRunLease).toHaveBeenCalledTimes(1); failedDelete = false; await quiet(c); expect(driver.releaseRunLease).toHaveBeenCalledTimes(2); }); + it("clears setup-token sessions a restart left in submitting, with and without a lease", async () => { + const expired = new Date(Date.now() - 1_000); + const orphan = async (providerLeaseId: string | null) => { + const sessionId = randomUUID(); + await db.insert(adapterAuthSessions).values({ companyId, environmentId, adapterType: "claude_local", startedByUserId: randomUUID(), + publicSessionId: sessionId, status: "submitting", providerLeaseId, expiresAt: expired }); + return sessionId; + }; + const withoutLease = await orphan(null); + const leaseSession = randomUUID(); + const leaseId = await lease(leaseSession); + const withLease = await orphan(leaseId); + const lines: string[] = []; + const reaper = createProductionSetupTokenReaper({ db: observed, environmentRuntime: { getDriver: () => driver } as any, log: line => lines.push(line) }); + + expect(await reaper.sweep()).toEqual({ released: 2, failed: 0 }); + expect(await reaper.sweep()).toEqual({ released: 0, failed: 0 }); + + const remaining = await db.select().from(adapterAuthSessions).where(eq(adapterAuthSessions.companyId, companyId)); + expect(remaining.map(row => row.publicSessionId)).not.toEqual(expect.arrayContaining([withoutLease])); + expect(remaining.map(row => row.publicSessionId)).not.toEqual(expect.arrayContaining([withLease])); + expect(driver.releaseRunLease).toHaveBeenCalledTimes(1); + expect(driver.releaseRunLease.mock.calls[0]![0].lease.id).toBe(leaseId); + expect(lines).toEqual([]); + }); it.each([false, true])("keeps nested producer intent until outer settlement (rollback=%s)", async rollback => { const c = await adapterWorker(); await quiet(c); let release!: () => void, written!: () => void, id!: string; diff --git a/server/src/services/setup-token-reaper.test.ts b/server/src/services/setup-token-reaper.test.ts index e74ee4acd3c..1d7d1f6a2e9 100644 --- a/server/src/services/setup-token-reaper.test.ts +++ b/server/src/services/setup-token-reaper.test.ts @@ -124,6 +124,48 @@ describe("setup-token reaper", () => { expect(store.rows.size).toBe(0); }); + it("logs the class and code of a failed release without its message", async () => { + const store = createMemoryStore(); + store.seed({ sessionId: "orphan-3", leaseId: "lease-orphan-3", state: "failed" }); + const leases = createFakeLeases({ + releaseImpl: async () => { + throw Object.assign(new Error("invalid input syntax for type uuid: \"sk-ant-oat01-should-not-log\""), { name: "PostgresError", code: "22P02" }); + }, + }); + const lines: string[] = []; + const reaper = createSetupTokenReaper({ store, leases, now: () => NOW, log: (line) => lines.push(line) }); + + expect((await reaper.sweep()).failed).toBe(1); + + expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: PostgresError (22P02)."]); + }); + + it("logs the database error that a query wrapper carries as its cause", async () => { + const store = createMemoryStore(); + store.seed({ sessionId: "orphan-5", leaseId: "lease-orphan-5", state: "failed" }); + const database = Object.assign(new Error("invalid input syntax for type uuid: \"sk-ant-oat01-should-not-log\""), { name: "PostgresError", code: "22P02" }); + const wrapped = Object.assign(new Error("Failed query: select ... params: sk-ant-oat01-should-not-log", { cause: database }), { name: "DrizzleQueryError" }); + const leases = createFakeLeases({ releaseImpl: async () => { throw wrapped; } }); + const lines: string[] = []; + const reaper = createSetupTokenReaper({ store, leases, now: () => NOW, log: (line) => lines.push(line) }); + + await reaper.sweep(); + + expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: DrizzleQueryError > PostgresError (22P02)."]); + }); + + it("logs a generic cause for a thrown value that is not an error", async () => { + const store = createMemoryStore(); + store.seed({ sessionId: "orphan-4", leaseId: "lease-orphan-4", state: "failed" }); + const leases = createFakeLeases({ releaseImpl: async () => { throw "provider text"; } }); + const lines: string[] = []; + const reaper = createSetupTokenReaper({ store, leases, now: () => NOW, log: (line) => lines.push(line) }); + + await reaper.sweep(); + + expect(lines).toEqual(["[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: unknown error."]); + }); + it("reaps every reapable record in one sweep and stays idempotent on the next", async () => { const store = createMemoryStore(); store.seed({ sessionId: "orphan-a", leaseId: "lease-a", state: "failed" }); diff --git a/server/src/services/setup-token-session.ts b/server/src/services/setup-token-session.ts index 6de393af020..53dca34265f 100644 --- a/server/src/services/setup-token-session.ts +++ b/server/src/services/setup-token-session.ts @@ -320,6 +320,21 @@ export interface SetupTokenReapResult { failed: number; } +function releaseFailureLink(error: unknown): string { + const name = error instanceof Error && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(error.name) ? error.name : "unknown error"; + const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined; + return typeof code === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(code) ? `${name} (${code})` : name; +} + +function releaseFailureCause(error: unknown): string { + const links: string[] = []; + for (let current = error, depth = 0; current !== undefined && current !== null && depth < 4; depth++) { + links.push(releaseFailureLink(current)); + current = current instanceof Error ? current.cause : undefined; + } + return links.join(" > "); +} + /** * The shared setup-token reap logic. It reads the durable store and releases any * lease whose session is terminal, past its deadline, or already consumed. It @@ -350,9 +365,9 @@ export async function reapSetupTokenLeases( adapterType: record.adapterType, }); released += 1; - } catch { + } catch (error) { failed += 1; - log("[paperclip] Setup-token reaper: a lease release failed; it stays retryable."); + log(`[paperclip] Setup-token reaper: a lease release failed; it stays retryable. Cause: ${releaseFailureCause(error)}.`); } } return { released, failed };