fix(workspaces): start a new remote workspace when the task's saved one is retired (#23655)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Before a run starts, Paperclip prepares the task's execution
workspace. With remote workspace storage, it reserves the task's saved
remote workspace.
> - A task stays bound to its workspace after that workspace is archived
or its cleanup fails.
> - For a retired host workspace, the next run already creates a new
workspace. For a retired remote workspace, preparation sent the retired
workspace to the reservation. The reservation refused it with "Workspace
ownership changed." (`remote_workspace_retired`, since #23582).
> - So the task could never run again. Each wake, recovery, or Retry
failed in setup with the same conflict.
> - This pull request makes a retired remote workspace act like a
retired host workspace: the run starts a new remote workspace.
> - The benefit is that a reopened task with an archived remote
workspace runs again, and the retired workspace and its saved snapshot
stay unchanged.

## Linked Issues or Issue Description

**What happened**
A task's own remote workspace was archived by hand (no terminal-cleanup
reason) and later moved to remote storage. When the task was opened
again, every run failed in setup with "Workspace ownership changed." The
task was then escalated for recovery, and the next wake failed in the
same way.

**Expected behavior**
A retired workspace is not reused. The run starts a new workspace for
the task, as it does for a host workspace. A native recovery or a saved
Retry that is bound to the retired workspace still stops with the
conflict.

**Steps to reproduce**
1. Bind a task to its own remote-storage workspace. Set the workspace
status to `archived` or `cleanup_failed`.
2. Start a run for the task with a Paperclip Runner agent in a sandbox
environment.
3. Setup fails with a 409 conflict, "Workspace ownership changed."
(`remote_workspace_retired`).

**Paperclip version or commit**
master at 0208bbfbf7.

Refs #23582 (gave this conflict its stable code). Related: #21954
(releases a binding to *another* task's closed workspace; this change is
about the task's *own* retired remote workspace).

## What Changed

- `remote-workspaces.ts`: add `isRetiredExecutionWorkspaceStatus`
(`archived` or `cleanup_failed`). When the caller requests no workspace,
`reserveRemoteWorkspace` does not fall back to an issue binding to a
retired workspace. It creates a new workspace and moves the issue
binding to it. An explicitly requested retired workspace still gets the
`remote_workspace_retired` conflict.
- `heartbeat/workspace-preparation.ts`: do not offer a retired
remote-storage workspace for reuse. The retired workspace still decides
the storage authority, so the task stays on remote storage even when the
instance does not enroll new tasks. This does not apply to a native
recovery, a persisted native execution input, or a saved Retry/fresh
attempt. Those stay bound to the workspace that they admitted.
- Tests: three preparation tests (`archived`, `cleanup_failed`, and
`archived` with new-task remote storage off) and one native-recovery
safety test in `workspace-preparation.test.ts`. Two reservation tests in
`remote-workspaces.integration.test.ts`.

## Verification

- Red before the fix: `cd server && npx vitest run
src/services/heartbeat/workspace-preparation.test.ts -t "saved remote
workspace is"` failed with `Workspace ownership changed.` for both
statuses. With only the reservation change removed, the two new
`remote-workspaces.integration.test.ts` tests also failed with
`Workspace ownership changed.`
- Green after the fix: `npx vitest run
src/services/heartbeat/workspace-preparation.test.ts
src/services/remote-workspaces.integration.test.ts -t "saved remote
workspace is|native recovery bound to a task workspace|stable conflict
code|when no workspace is requested"`: 8 of 8 pass. The storage-off case
failed before the follow-up commit (the run fell back to the host path).
- The tests check that the new workspace is active and bound to the
task, that the binding revision goes up by one, and that the retired row
and its snapshot metadata do not change. The existing explicit-request
conflict test still passes, and a native recovery still gets the
conflict.
- Full files: `npx vitest run
src/services/heartbeat/workspace-preparation.test.ts
src/services/remote-workspaces.integration.test.ts
src/services/workspace-recovery-admission.test.ts`: 433 of 433 pass
(Linux x64, Node 24.23.0, embedded Postgres).

## Risks

- Behavior change: a task whose own remote workspace is retired now
continues in a new workspace. Files that were only in the retired
workspace's snapshot are not restored into the new workspace. This is
the same as for a retired host workspace. The retired snapshot is not
deleted.
- A native recovery or a saved Retry still stops on a retired workspace,
so a run that is in progress does not change its workspace silently.
- No schema or API change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution
in a sandbox.

## 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
- [ ] 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-03 13:45:10 -08:00
1 parent 1fb8ddb740
commit 7e025ae65f
4 files changed
+137 -4

No files matched your search

@@ -302,6 +302,90 @@ describe.skipIf(!support.supported && !externalDatabaseUrl)("heartbeat workspace
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(workspace.id);
});
it.each([
{ status: "archived", storageEnabled: true },
{ status: "cleanup_failed", storageEnabled: true },
{ status: "archived", storageEnabled: false },
] as const)("starts a new remote workspace for a task whose own saved remote workspace is $status (new-task remote storage: $storageEnabled)", async ({ status, storageEnabled }) => {
const { input, source, issue, envOrchestrator } = await fixture(true);
// The task already uses remote storage, so it stays there even when the
// instance no longer enrolls new tasks.
input.environment.resolvedInstanceSettings.experimental.remoteWorkspaceStorageEnabled = storageEnabled;
const [savedEnvironment] = await db.insert(environments).values({ name: `Remote ${randomUUID()}`,
driver: "sandbox", status: "active", config: { provider: "daytona" } }).returning();
await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, input.agent.id));
input.agent.adapterType = "paperclip_runner";
input.environment.selectedEnvironmentForConfig = await environmentService(db).getById(savedEnvironment.id);
input.environment.selectedEnvironmentId = savedEnvironment.id;
await db.update(projectWorkspaces).set({ cwd: null, sourceType: "git", repoUrl: "https://github.com/example/remote.git", repoRef: "main" })
.where(eq(projectWorkspaces.id, issue.projectWorkspaceId!));
await rm(source, { recursive: true });
// A task workspace archived by hand (no terminal-cleanup reason) and later
// imported into remote storage. Its saved snapshot must stay untouched.
const remoteWorkspace = { schema: "paperclip.remote-workspace.v1", epoch: 1, snapshotId: randomUUID(),
source: { kind: "git", repoUrl: "https://github.com/example/remote.git", ref: "0123456789abcdef0123456789abcdef01234567",
branchName: "test-WSP-1" }, location: null, writerRunId: null, dirty: false };
const [retired] = await db.insert(executionWorkspaces).values({ companyId: issue.companyId,
sourceIssueId: issue.id, projectId: issue.projectId, projectWorkspaceId: issue.projectWorkspaceId,
name: "Retired sandbox workspace", cwd: `/workspaces/${randomUUID()}`, providerType: "cloud_sandbox", strategyType: "git_worktree",
mode: "isolated_workspace", status, closedAt: new Date(), cleanupReason: null, metadata: { remoteWorkspace } }).returning();
const [boundIssue] = await db.update(issues).set({ executionWorkspaceId: retired.id, executionWorkspacePreference: "reuse_existing" })
.where(eq(issues.id, issue.id)).returning();
input.task.issueRef = boundIssue;
input.reuse.workspaceReuseRequest = resolveExecutionWorkspaceReuseRequestForIssue({ issueExecutionWorkspaceId: retired.id,
issueExecutionWorkspacePreference: "reuse_existing", existingExecutionWorkspaceStatus: status });
input.reuse.requestedShouldReuseExisting = input.reuse.workspaceReuseRequest.requestedShouldReuseExisting;
input.reuse.existingExecutionWorkspace = toExecutionWorkspace(retired);
input.reuse.reusableExistingExecutionWorkspace = input.reuse.workspaceReuseRequest.existingExecutionWorkspaceAvailable
? toExecutionWorkspace(retired) : null;
let acquiredWorkspaceId: string | null = null;
vi.spyOn(envOrchestrator, "acquireForRun").mockImplementation(async args => {
acquiredWorkspaceId = args.persistedExecutionWorkspace?.id ?? null;
throw new Error("reached remote acquisition");
});
configureRemotePersistence();
process.env.PAPERCLIP_EPHEMERAL_SERVER = storageEnabled ? "true" : "false";
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toThrow("reached remote acquisition");
expect(acquiredWorkspaceId).not.toBeNull();
expect(acquiredWorkspaceId).not.toBe(retired.id);
const [replacement] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, acquiredWorkspaceId!));
expect(replacement).toMatchObject({ sourceIssueId: issue.id, status: "active", providerType: "cloud_sandbox", mode: "isolated_workspace" });
expect(replacement.metadata?.remoteWorkspace).toMatchObject({ epoch: 1, snapshotId: null, writerRunId: input.run.id,
source: { kind: "git", repoUrl: "https://github.com/example/remote.git", ref: "main", branchName: "test-WSP-1" } });
expect(await readIssue(issue.id)).toMatchObject({ executionWorkspaceId: replacement.id,
workspaceBindingRevision: boundIssue.workspaceBindingRevision + 1 });
const [unchanged] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, retired.id));
expect(unchanged).toMatchObject({ status, cleanupReason: null, metadata: retired.metadata });
});
it("keeps refusing a native recovery bound to a task workspace that was archived", async () => {
const { input, issue } = await fixture(true);
const [savedEnvironment] = await db.insert(environments).values({ name: `Remote ${randomUUID()}`,
driver: "sandbox", status: "active", config: { provider: "daytona" } }).returning();
input.agent.adapterType = "paperclip_runner";
input.environment.selectedEnvironmentForConfig = await environmentService(db).getById(savedEnvironment.id);
input.environment.selectedEnvironmentId = savedEnvironment.id;
const remoteWorkspace = { schema: "paperclip.remote-workspace.v1", epoch: 1, snapshotId: randomUUID(),
source: { kind: "empty" }, location: null, writerRunId: null, dirty: false };
const [retired] = await db.insert(executionWorkspaces).values({ companyId: issue.companyId,
sourceIssueId: issue.id, projectId: issue.projectId, projectWorkspaceId: issue.projectWorkspaceId,
name: "Retired sandbox workspace", cwd: `/workspaces/${randomUUID()}`, providerType: "cloud_sandbox", strategyType: "git_worktree",
mode: "isolated_workspace", status: "archived", closedAt: new Date(), metadata: { remoteWorkspace } }).returning();
await db.update(issues).set({ executionWorkspaceId: retired.id, executionWorkspacePreference: "reuse_existing" })
.where(eq(issues.id, issue.id));
input.reuse.existingExecutionWorkspace = toExecutionWorkspace(retired);
input.reuse.nativeRecoveryExecutionWorkspaceId = retired.id;
configureRemotePersistence();
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({ status: 409,
details: { code: "remote_workspace_retired" } });
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(retired.id);
expect(await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces)
.where(eq(executionWorkspaces.sourceIssueId, issue.id))).toHaveLength(1);
});
it.each([
{ kind: "empty", repoUrl: null, branchMode: null, fresh: false, strategyChange: false, ephemeral: true },
{ kind: "git", repoUrl: "https://github.com/example/remote.git", branchMode: null, fresh: false, strategyChange: false },
@@ -1,7 +1,7 @@
import { NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH, remoteRecoveryLeaseMismatch } from "../native-runtime/remote-recovery-lease-mismatch.js";
import { readInheritedRunnerRetainedSandbox } from "../native-runtime/native-inherited-runner-retry.js";
import { resolveProviderApiPlacement } from "../native-runtime/provider-api-placement.js";
import { assertEphemeralWorkspaceExecution, readRemoteWorkspaceAuthority, RemoteWorkspaceWriterActiveError, reserveRemoteWorkspace, shouldUseRemoteWorkspaces, supportsRemoteWorkspaceExecution } from "../remote-workspaces.js";
import { assertEphemeralWorkspaceExecution, isRetiredExecutionWorkspaceStatus, readRemoteWorkspaceAuthority, RemoteWorkspaceWriterActiveError, reserveRemoteWorkspace, shouldUseRemoteWorkspaces, supportsRemoteWorkspaceExecution } from "../remote-workspaces.js";
import { assertProjectStorageEnvironment, listProjectWorkspaceProviders, projectStorageForEnvironment } from "../project-workspace-provider.js";
import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js";
import { REMOTE_WORKSPACE_ENVIRONMENT_INCOMPATIBLE } from "../remote-workspace-environment-reason.js";
@@ -253,6 +253,21 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
isDotRun,
runOptions,
} = input.reuse;
// A retired remote task workspace is not reused, as for a retired host
// workspace: the run starts a new one. The task still uses remote storage,
// so the retired workspace keeps deciding the storage authority. A native
// recovery or a saved Retry stays bound to the workspace it admitted and
// still gets the conflict.
const boundTaskWorkspace = reusableExistingExecutionWorkspace ?? existingExecutionWorkspace;
let retiredRemoteWorkspace: ExecutionWorkspace | null = null;
if (boundTaskWorkspace && isRetiredExecutionWorkspaceStatus(boundTaskWorkspace.status)
&& readRemoteWorkspaceAuthority(boundTaskWorkspace.metadata)
&& !nativeRecoveryExecutionWorkspaceId && !persistedNativeExecutionInput && !input.task.freshWorkspace) {
retiredRemoteWorkspace = boundTaskWorkspace;
existingExecutionWorkspace = null;
reusableExistingExecutionWorkspace = null;
requestedShouldReuseExisting = false;
}
// An ordinary clean task directory already has a new per-attempt identity.
// It is not a repository source and must not pass through Git copy admission.
const controllerOnly = isDotRun || providerApiPlacement !== null;
@@ -281,7 +296,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
{ reason: "remote_workspace_migration_in_progress" });
}
}
const enrolledRemoteWorkspace = reusableExistingExecutionWorkspace ?? existingExecutionWorkspace;
const enrolledRemoteWorkspace = reusableExistingExecutionWorkspace ?? existingExecutionWorkspace ?? retiredRemoteWorkspace;
const enrolledRemoteAuthority = readRemoteWorkspaceAuthority(enrolledRemoteWorkspace?.metadata) !== null;
if (!controllerOnly && enrolledRemoteAuthority
&& !supportsRemoteWorkspaceExecution(agent.adapterType, selectedEnvironmentForConfig?.driver ?? null)) {
@@ -310,7 +325,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
experimentalEnabled: (process.env.PAPERCLIP_EPHEMERAL_SERVER === "true" || resolvedInstanceSettings.experimental.remoteWorkspaceStorageEnabled) && Boolean(issueId && issueRef)
&& !projectExecutionWorkspacePolicy?.storageProviderPluginId,
existingWorkspace: reusableExistingExecutionWorkspace ?? existingExecutionWorkspace,
existingWorkspace: enrolledRemoteWorkspace,
});
const projectStorageEnvironmentIncompleteFailure = (details: {
message: string;
@@ -313,6 +313,27 @@ suite("remote workspace lifecycle with real Postgres and independent filesystem
status: 409, message: "Workspace ownership changed.", details: { code: "remote_workspace_retired" } });
});
it.each(["archived", "cleanup_failed"] as const)("replaces a task's binding to its own %s workspace when no workspace is requested", async status => {
const reserved = await reserve({ kind: "empty" });
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, ids.run));
const [retired] = await db.update(executionWorkspaces).set({ status }).where(eq(executionWorkspaces.id, reserved.id)).returning();
const [before] = await db.select().from(issues).where(eq(issues.id, ids.issue));
expect(before.executionWorkspaceId).toBe(retired.id);
const nextRun = randomUUID();
await db.insert(heartbeatRuns).values({ id: nextRun, companyId: ids.company, agentId: ids.agent,
nativeIssueId: ids.issue, runtimeMode: "native", status: "running" });
const replacement = await reserveRemoteWorkspace({ db, storage, companyId: ids.company, issueId: ids.issue,
runId: nextRun, agentId: ids.agent, environmentId: ids.environment, projectId: null, projectWorkspaceId: null,
existingWorkspaceId: null, source: { kind: "empty" } });
expect(replacement.id).not.toBe(retired.id);
expect(replacement).toMatchObject({ status: "active", sourceIssueId: ids.issue,
metadata: { remoteWorkspace: { epoch: 1, snapshotId: null, writerRunId: nextRun } } });
const [after] = await db.select().from(issues).where(eq(issues.id, ids.issue));
expect(after).toMatchObject({ executionWorkspaceId: replacement.id, workspaceBindingRevision: before.workspaceBindingRevision + 1 });
const [unchanged] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, retired.id));
expect(unchanged).toMatchObject({ status, metadata: retired.metadata });
});
it.each(["initial", "follow-up"] as const)("edits and cold-restores both an anchor and a referenced project's task copy (%s attachment)", async attachment => {
vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC", "true");
vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC_REMOTE", "true");
+14 -1
View File
@@ -199,6 +199,12 @@ async function lockWorkspaceRunParents(tx: Transaction, companyId: string, runId
return issueId;
}
// An archived workspace, or one whose cleanup failed, is retired. A run never
// writes to it again; the task continues in a new workspace instead.
export function isRetiredExecutionWorkspaceStatus(status: string | null | undefined) {
return status === "archived" || status === "cleanup_failed";
}
export class RemoteWorkspaceWriterActiveError extends HttpError {
constructor(
readonly workspaceId: string,
@@ -230,6 +236,13 @@ export async function reserveRemoteWorkspace(input: {
if (input.fresh && (issue.executionWorkspaceId !== input.fresh.previousWorkspaceId
|| issue.workspaceBindingRevision !== input.fresh.expectedBindingRevision)) throw conflict("The task workspace selection changed.");
let selected = input.fresh ? input.fresh.attemptId : input.existingWorkspaceId ?? issue.executionWorkspaceId;
// Without a workspace chosen by the caller, a task still bound to a retired
// workspace gets a new one. The retired row and its snapshot stay unchanged.
if (!input.fresh && !input.existingWorkspaceId && selected) {
const [bound] = await tx.select({ status: executionWorkspaces.status }).from(executionWorkspaces).where(and(
eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, selected))).for("update");
if (bound && isRetiredExecutionWorkspaceStatus(bound.status)) selected = null;
}
let selectedSharedSource = false;
if (!selected && input.mode === "shared_workspace" && input.projectWorkspaceId) {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`remote-shared-workspace:${input.companyId}:${input.projectWorkspaceId}`}, 0))`);
@@ -247,7 +260,7 @@ export async function reserveRemoteWorkspace(input: {
let authority = readRemoteWorkspaceAuthority(existing?.metadata);
if (existing && !authority) throw conflict("Import this existing workspace before enabling remote storage.", { code: "remote_workspace_migration_required" });
if (existing && authority) {
if (["archived", "cleanup_failed"].includes(existing.status)) throw conflict("Workspace ownership changed.", { code: "remote_workspace_retired" });
if (isRetiredExecutionWorkspaceStatus(existing.status)) throw conflict("Workspace ownership changed.", { code: "remote_workspace_retired" });
if (existing.sourceIssueId !== input.issueId) {
const actor = { type: "agent", source: "agent_jwt", companyId: input.companyId,
agentId: input.agentId, runId: input.runId,