diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts index 9ab2c78591b..d6ef54aaecc 100644 --- a/server/src/services/heartbeat/workspace-preparation.test.ts +++ b/server/src/services/heartbeat/workspace-preparation.test.ts @@ -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 }, diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts index 1a582f1af6a..f770869bbbd 100644 --- a/server/src/services/heartbeat/workspace-preparation.ts +++ b/server/src/services/heartbeat/workspace-preparation.ts @@ -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; diff --git a/server/src/services/remote-workspaces.integration.test.ts b/server/src/services/remote-workspaces.integration.test.ts index cdda1b06bdc..be36532b7a5 100644 --- a/server/src/services/remote-workspaces.integration.test.ts +++ b/server/src/services/remote-workspaces.integration.test.ts @@ -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"); diff --git a/server/src/services/remote-workspaces.ts b/server/src/services/remote-workspaces.ts index 8311367959e..3e61db81722 100644 --- a/server/src/services/remote-workspaces.ts +++ b/server/src/services/remote-workspaces.ts @@ -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,