Files
PaperClipAI/server/src/__tests__/plugin-workspace-terminal-retry.integration.test.ts
T
Nicky LeachandClaude Opus 5.5 960a2b781e perf(workspaces): hold kept plugin workspaces instead of re-inspecting them every sweep (#22054)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Workspace storage plugins hold task workspaces, and Core's terminal
workspace sweep removes them after their tasks finish
> - The sweep inspects each candidate workspace through the provider. A
provider inspection can start a sandbox or call a remote API, so each
one has a real cost
> - When an inspection fails, the sweep backs off. When an inspection
succeeds but keeps the workspace (local data, or work that is not
merged), there is no backoff, so the sweep inspects the same workspace
again on every pass, forever
> - Kept workspaces also kept a past-due sweep deadline, so targeted
sweeps came back to them every few minutes, not only once per hourly
rotation
> - With many closed workspaces, this repeated work grows without limit
and gives the same answer each time
> - This pull request records a hold after an inspection keeps a
provider workspace, and skips the provider inspection while nothing that
could change the answer has changed
> - The benefit is far fewer provider operations for kept workspaces,
with no delay for workspaces that can be removed

## Linked Issues or Issue Description

**Subsystem affected**
Server: the terminal workspace sweep for workspace storage plugins
(`server/src/services/execution-workspaces.ts`).

**Problem or motivation**
The terminal workspace sweep inspects every kept plugin workspace again
on every pass. For a workspace kept for local data, the answer cannot
change until something changes the workspace. For a clean, unmerged
workspace, the answer changes only when the remote changes. Each
repeated inspection is a provider operation, which can start a sandbox
or call a remote API.

**Proposed solution**
After an inspection keeps a plugin workspace, Core records a hold. A
workspace kept for local data is not inspected again until it or its
task tree changes, or a change notice names it. A clean, unmerged
workspace is checked again after 1 hour, then on an interval that
doubles up to 24 hours. Workspaces that can be removed are removed as
before.

**Alternatives considered**
An in-memory hold only. It is lost on restart, and the existing
in-memory inspection cache holds only 256 entries, so a large set of
kept workspaces would be inspected again after every restart.

## What Changed

- `server/src/services/terminal-workspace-retry.ts`: add the
`terminalInspectionHold` workspace metadata record (generation,
fingerprint, reason, HEAD, check count, check time, next check time).
The write is fenced on the lifecycle generation. Add the recheck delay:
1 hour, doubling, capped at 24 hours.
- `server/src/services/execution-workspaces.ts`
(`sweepTerminalWorkspaces`):
- Before it inspects a plugin workspace, the sweep compares a
fingerprint of the inputs that can change the answer: the row's
`updatedAt`, status, provider ref, repository, branch, base ref,
provider binding, delivery candidate, and the task tree's terminal
state. The lifecycle generation scopes the record. While the hold
applies, the sweep skips the inspection and counts the workspace as
`skippedBackoff`.
- After an inspection keeps the workspace, the sweep records a
`local_data` hold (dirty or untracked files, or local-only data; no
recheck time) or an `unmerged` hold (growing recheck interval). A new
inspected HEAD, a new fingerprint, or a change notice restarts the
interval.
- A kept workspace now gets a sweep deadline at its recheck time, or
none. Before, it kept its past-due archive deadline, so targeted sweeps
came back to it every few minutes.
- A provider refresh notice (`plugin-workspaces`: activation, upgrade,
capability change, company re-enablement) ends every hold, because it
can change how any plugin workspace inspects.
- A `workspace:` or `issue:` change notice ends the holds that it names
(the workspace, or a workspace whose task tree or linked tasks contain
the issue). A notice without a scope ends every hold. The next sweep
visit clears an ended hold from the row, so the reset survives a
restart. The in-memory notice entries are pruned after the next full
rotation.
- When an inspection finds the workspace removable, the sweep clears the
hold and continues to removal as before.
- The hold applies only to plugin workspaces. Local Git worktree
inspections are cheap, and a person can change those folders directly,
so they keep the current behavior.
- Core owns the new metadata key. Workspace metadata updates keep it,
like `terminalCleanupRetry`.
- `doc/plugins/PLUGIN_RUNNER_EXECUTION.md`: describe the hold for
provider authors.
- Optional item not done: `removePluginWorkspace` still inspects again
before it removes. That inspection runs right before a destructive
operation, passes the recovery PR hint to the provider, and checks
`remotelyRecoverable`, which the sweep's inspection result does not
carry. Skipping it is not clearly safe.

## Verification

- `npx vitest run
src/__tests__/plugin-workspace-terminal-hold.integration.test.ts` (new,
embedded Postgres):
- Local-data hold: no inspection after 30 days; a workspace notice, an
issue notice, a generation bump, a metadata update, a new task
completion time, and a provider refresh notice each cause exactly one
new inspection; no sweep deadline is left. The provider refresh step
fails without its fix (6 inspections, not 7).
- Unmerged backoff: recheck delays are 1, 2, 4, 8, 16, 24, 24 hours; a
new HEAD resets to 1 hour; a workspace notice resets to 1 hour.
- Removable workspaces: a clean merged workspace is removed on its first
sweep (inspection count unchanged at 2); a held dirty workspace is
removed on the next sweep after a notice, and the hold is cleared; a
closed held workspace is removed after an unscoped notice.
- Failure backoff: delays stay 5 and 10 minutes, and a failed inspection
does not record a hold.
- Red check: the five new tests fail against the unchanged service and
pass with the change.
- Related suites pass locally (10 files, 204 tests):
`execution-workspaces-service`, `plugin-workspaces.integration`,
`terminal-workspace-deadlines`, `terminal-workspace-idle`,
`terminal-workspace-page-batch`, `terminal-workspace-rotation-limits`,
`terminal-workspace-work`, `workspace-delivery-cleanup.integration`,
`plugin-workspace-terminal-retry.integration`, and the new file.
- A scratch check confirmed the old deadline behavior: after a sweep
kept a workspace, the old code left it due with a past deadline. The new
code leaves no deadline.
- `plugin-workspace-terminal-retry.integration.test.ts`: one step now
sends a workspace notice before it checks that a new failure restarts
the backoff at 1, because the preceding successful inspection now holds
the dirty workspace.
- `cd server && npx tsc --noEmit -p .` passes.

## Risks

- A held `local_data` workspace is inspected again only after a change.
If a change notice is lost (for example a restart between the commit and
the notice) and the change does not touch the workspace row, its
generation, binding, status, delivery candidate, or task tree terminal
state, the workspace stays held until one of those changes. Runs end
with an `issue:` notice and new task completion times, so the normal
paths are covered.
- An `unmerged` workspace that becomes merged on the remote waits until
its next recheck (at most 24 hours), not the next hourly rotation.
- Each sweep page now runs one extra query for the linked tasks of held
workspaces. Each kept workspace gets one metadata write per inspection.
- No schema migration. The record is in existing workspace metadata.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, 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
- [x] All Paperclip CI gates are green
- [x] 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>
2026-11-17 13:40:35 -08:00

255 lines
15 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { eq, sql } from "drizzle-orm";
import { createDb, executionWorkspaces, heartbeatRuns, issues } from "@paperclipai/db";
import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES } from "@paperclipai/plugin-sdk";
import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js";
import { inspectPluginWorkspace, preparePluginWorkspace, removePluginWorkspace, type WorkspaceWorkers } from "../services/plugin-workspaces.js";
import { executionWorkspaceService } from "../services/execution-workspaces.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const MINUTE = 60_000;
function providerRefusal() {
return new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, message: "private provider text",
data: { schema: "paperclip/workspace-operation-error/v1", reason: "unsupported_operation" } });
}
(support.supported ? describe : describe.skip)("plugin workspace terminal cleanup retry", () => {
let db: ReturnType<typeof createDb>, stopDb: (() => Promise<void>) | undefined;
beforeAll(async () => {
const started = await startEmbeddedPostgresTestDatabase("plugin-workspace-terminal-retry");
db = createDb(started.connectionString, { maxConnections: 1 });
stopDb = started.cleanup;
});
afterAll(async () => {
await db?.$client.end();
await stopDb?.();
});
async function setup() {
const f = await createPluginWorkspaceFixture(db);
const failures = { prepare: false, inspect: false, remove: false, unboundRemove: false, reopenFirst: false };
const workers = { ...f.workers, call: async (...args: Parameters<WorkspaceWorkers["call"]>) => {
const params = args[2] as { agentId: string | null; operation: { kind: string; binding?: unknown } };
if (params.operation.kind === "prepare" && failures.prepare) {
f.calls.push(params);
throw providerRefusal();
}
if (params.operation.kind === "remove" && params.operation.binding === null) {
f.calls.push(params);
if (failures.unboundRemove) throw providerRefusal();
if (failures.remove) throw new Error("lost removal");
return { kind: "removed" };
}
if ((params.operation.kind === "inspect" && failures.inspect) || (params.operation.kind === "remove" && failures.remove)) {
f.calls.push(params);
if (failures.reopenFirst) await db.update(executionWorkspaces).set({ metadata: sql`jsonb_set(${executionWorkspaces.metadata},
'{lifecycleGeneration}', to_jsonb(coalesce((${executionWorkspaces.metadata}->>'lifecycleGeneration')::int, 0) + 1))` })
.where(eq(executionWorkspaces.id, (params as unknown as { executionWorkspaceId: string }).executionWorkspaceId));
throw new Error("provider outage");
}
return f.workers.call(...args);
} } as WorkspaceWorkers;
const read = async (id: string) => (await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)))[0]!;
const finishTask = async () => {
await db.update(issues).set({ status: "done", completedAt: new Date() }).where(eq(issues.id, f.issueId));
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
};
const abandonReservation = async () => {
f.lose();
await expect(preparePluginWorkspace(db, workers, f.input)).rejects.toThrow("incomplete");
const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId));
const reservation = await read(task.executionWorkspaceId!);
expect(reservation.providerRef).toBeNull();
await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, f.issueId));
const replacement = await preparePluginWorkspace(db, workers, f.input);
expect(replacement!.id).not.toBe(reservation.id);
return reservation;
};
const callsFor = (id: string, kind: string) => f.calls.filter(call => call.executionWorkspaceId === id && call.operation.kind === kind);
return { f, workers, failures, read, finishTask, abandonReservation, callsFor };
}
it("retires an unbound reservation of a finished task through an agent-free remove and archives it", async () => {
const s = await setup();
const reservation = await s.abandonReservation();
await s.finishTask();
s.f.dirty();
await executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0 }).sweepTerminalWorkspaces(100);
expect(s.callsFor(reservation.id, "prepare")).toHaveLength(1);
expect(s.callsFor(reservation.id, "remove")).toEqual([expect.objectContaining({ agentId: null, runId: null,
operation: { kind: "remove", binding: null, expectedHeadSha: null } })]);
const retired = await s.read(reservation.id);
expect(retired).toMatchObject({ status: "archived", cleanupReason: "issue_terminal",
metadata: { workspaceProviderRemoved: true, workspaceProviderRemoval: null } });
expect(retired.closedAt).not.toBeNull();
expect(retired.metadata?.lifecycleGeneration).toBe(((reservation.metadata?.lifecycleGeneration as number) ?? 0) + 1);
});
it("replays a failed reservation removal with the same identity and backs it off", async () => {
const s = await setup();
const reservation = await s.abandonReservation();
await s.finishTask();
s.f.dirty();
s.failures.remove = true;
let clock = Date.now();
const svc = executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0, now: () => new Date(clock) });
await svc.sweepTerminalWorkspaces(100);
const pending = await s.read(reservation.id);
expect(pending).toMatchObject({ status: "archived",
metadata: { workspaceProviderRemoval: { operation: { kind: "remove", binding: null } } } });
expect(pending.metadata?.terminalCleanupRetry).toMatchObject({ failures: 1, generation: pending.metadata?.lifecycleGeneration,
retryAt: new Date(clock + 5 * MINUTE).toISOString(), failure: { kind: "transport" } });
const retryAt = Date.parse((pending.metadata?.terminalCleanupRetry as { retryAt: string }).retryAt);
clock = Date.now() + 1;
await svc.sweepTerminalWorkspaces(100);
expect(s.callsFor(reservation.id, "remove")).toHaveLength(1);
s.failures.remove = false;
clock = retryAt;
await svc.sweepTerminalWorkspaces(100);
const removes = s.callsFor(reservation.id, "remove");
expect(removes).toHaveLength(2);
expect(new Set(removes.map(call => call.operationId)).size).toBe(1);
expect(s.callsFor(reservation.id, "prepare")).toHaveLength(1);
const retired = await s.read(reservation.id);
expect(retired).toMatchObject({ status: "archived", metadata: { workspaceProviderRemoved: true } });
expect(retired.metadata).not.toHaveProperty("terminalCleanupRetry");
});
it("keeps the reservation a task still points at and records why its reconciliation failed", async () => {
const s = await setup();
s.f.lose();
await expect(preparePluginWorkspace(db, s.workers, s.f.input)).rejects.toThrow("incomplete");
const [task] = await db.select().from(issues).where(eq(issues.id, s.f.issueId));
await s.finishTask();
s.failures.prepare = true;
const clock = Date.now();
await executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0, now: () => new Date(clock) })
.sweepTerminalWorkspaces(100);
expect(s.callsFor(task.executionWorkspaceId!, "remove")).toHaveLength(0);
expect(s.callsFor(task.executionWorkspaceId!, "prepare")).toHaveLength(2);
const kept = await s.read(task.executionWorkspaceId!);
expect(kept.status).not.toBe("archived");
expect(kept.providerRef).toBeNull();
expect(kept.metadata?.terminalCleanupRetry).toMatchObject({ failures: 1, retryAt: new Date(clock + 5 * MINUTE).toISOString(),
failure: { kind: "provider", reason: "unsupported_operation", message: expect.not.stringContaining("private") } });
});
it("does not retire a reservation whose task is still open", async () => {
const s = await setup();
const reservation = await s.abandonReservation();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, s.f.runId));
s.failures.prepare = true;
await expect(inspectPluginWorkspace(db, s.workers, reservation)).rejects.toThrow();
expect(s.callsFor(reservation.id, "remove")).toHaveLength(0);
expect(s.callsFor(reservation.id, "prepare")).toHaveLength(2);
const kept = await s.read(reservation.id);
expect(kept.status).toBe(reservation.status);
expect(kept.metadata?.workspaceProviderRemoval).toBeUndefined();
});
it("backs off and keeps the reason when the provider rejects an unbound removal", async () => {
const s = await setup();
const reservation = await s.abandonReservation();
await s.finishTask();
s.f.dirty();
s.failures.unboundRemove = true;
let clock = Date.now();
const svc = executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0, now: () => new Date(clock) });
await svc.sweepTerminalWorkspaces(100);
const refused = await s.read(reservation.id);
expect(refused).toMatchObject({ status: "archived", metadata: { workspaceProviderRemoval: { operation: { binding: null } } } });
expect(refused.metadata?.workspaceProviderRemoved).not.toBe(true);
expect(refused.metadata?.terminalCleanupRetry).toMatchObject({ failures: 1, retryAt: new Date(clock + 5 * MINUTE).toISOString(),
generation: refused.metadata?.lifecycleGeneration,
failure: { kind: "provider", reason: "unsupported_operation", message: expect.not.stringContaining("private") } });
clock = Date.now() + 1;
await svc.sweepTerminalWorkspaces(100);
expect(s.callsFor(reservation.id, "remove")).toHaveLength(1);
expect(s.callsFor(reservation.id, "prepare")).toHaveLength(1);
});
it("backs off repeated inspection failures, records the reason, and resets after a success", async () => {
const s = await setup();
const workspace = (await preparePluginWorkspace(db, s.workers, s.f.input))!;
await s.finishTask();
s.f.dirty();
s.failures.inspect = true;
let clock = Date.now();
const svc = executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0, now: () => new Date(clock) });
const retryAfter = async () => {
const retry = (await s.read(workspace.id)).metadata?.terminalCleanupRetry as { failures: number; retryAt: string } | undefined;
return retry && { failures: retry.failures, delay: Date.parse(retry.retryAt) - clock };
};
await svc.sweepTerminalWorkspaces(100);
expect(await retryAfter()).toEqual({ failures: 1, delay: 5 * MINUTE });
expect((await s.read(workspace.id)).metadata?.terminalCleanupRetry).toMatchObject({
failure: { kind: "transport", reason: null, message: "Workspace storage operation is incomplete; retry the same workspace" } });
expect((await svc.sweepTerminalWorkspaces(100)).skippedBackoff).toBeGreaterThanOrEqual(1);
expect(s.callsFor(workspace.id, "inspect")).toHaveLength(1);
clock += 5 * MINUTE;
await svc.sweepTerminalWorkspaces(100);
expect(await retryAfter()).toEqual({ failures: 2, delay: 10 * MINUTE });
clock += 10 * MINUTE;
await svc.sweepTerminalWorkspaces(100);
expect(await retryAfter()).toEqual({ failures: 3, delay: 20 * MINUTE });
svc.terminalWorkspaceWorkSettled();
await svc.sweepTerminalWorkspaces(100);
expect(s.callsFor(workspace.id, "inspect")).toHaveLength(3);
const edited = await executionWorkspaceService(db).update(workspace.id, { metadata: { note: "operator edit" } });
expect(edited!.metadata).toMatchObject({ note: "operator edit", terminalCleanupRetry: { failures: 3 } });
clock += 20 * MINUTE;
s.failures.inspect = false;
await svc.sweepTerminalWorkspaces(100);
expect(s.callsFor(workspace.id, "inspect")).toHaveLength(4);
expect(await retryAfter()).toBeUndefined();
// The successful inspection kept the dirty workspace on hold; a change notice ends the hold.
svc.terminalWorkspaceWorkSettled(new Set([`workspace:${workspace.id}`]), { targeted: true });
s.failures.inspect = true;
clock += MINUTE;
await svc.sweepTerminalWorkspaces(100);
expect(await retryAfter()).toEqual({ failures: 1, delay: 5 * MINUTE });
});
it("drops a cleanup failure when the workspace moves to a new lifecycle before it is recorded", async () => {
const s = await setup();
const workspace = (await preparePluginWorkspace(db, s.workers, s.f.input))!;
await s.finishTask();
s.f.dirty();
s.failures.inspect = true;
s.failures.reopenFirst = true;
await executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0 }).sweepTerminalWorkspaces(100);
expect(s.callsFor(workspace.id, "inspect")).toHaveLength(1);
const moved = await s.read(workspace.id);
expect(moved.metadata?.lifecycleGeneration).toBe(((workspace.metadata?.lifecycleGeneration as number) ?? 0) + 1);
expect(moved.metadata).not.toHaveProperty("terminalCleanupRetry");
});
it("backs off a pending storage removal that keeps failing", async () => {
const s = await setup();
const workspace = (await preparePluginWorkspace(db, s.workers, s.f.input))!;
await s.finishTask();
s.failures.remove = true;
await expect(removePluginWorkspace(db, s.workers, workspace, "a".repeat(40))).rejects.toThrow();
await db.update(executionWorkspaces).set({ status: "cleanup_failed", closedAt: new Date() }).where(eq(executionWorkspaces.id, workspace.id));
let clock = Date.now();
const svc = executionWorkspaceService(db, { pluginWorkerManager: s.workers, workspaceReaperCooldownDays: 0, now: () => new Date(clock) });
const delays: number[] = [];
for (let attempt = 0; attempt < 3; attempt++) {
await svc.sweepTerminalWorkspaces(100);
const retry = (await s.read(workspace.id)).metadata?.terminalCleanupRetry as { failures: number; retryAt: string };
expect(retry.failures).toBe(attempt + 1);
delays.push(Date.parse(retry.retryAt) - clock);
clock = Date.parse(retry.retryAt);
}
expect(delays).toEqual([5 * MINUTE, 10 * MINUTE, 20 * MINUTE]);
expect(s.callsFor(workspace.id, "remove")).toHaveLength(4);
s.failures.remove = false;
await svc.sweepTerminalWorkspaces(100);
const removed = await s.read(workspace.id);
expect(removed).toMatchObject({ status: "archived", metadata: { workspaceProviderRemoved: true } });
expect(removed.metadata).not.toHaveProperty("terminalCleanupRetry");
});
});