diff --git a/server/src/services/heartbeat/environment-selection.test.ts b/server/src/services/heartbeat/environment-selection.test.ts index d8e252c832c..ed7ea5a5109 100644 --- a/server/src/services/heartbeat/environment-selection.test.ts +++ b/server/src/services/heartbeat/environment-selection.test.ts @@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"; import { mkdtemp, mkdir, rm, writeFile, readFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { agents, companies, createDb, environments, environmentLeases, heartbeatRuns, issues, projects, projectWorkspaces, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, type Db } from "@paperclipai/db"; +import { agents, companies, createDb, environments, environmentLeases, executionWorkspaces, executionWorkspaceSnapshots, heartbeatRuns, issues, projects, projectWorkspaces, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, type Db } from "@paperclipai/db"; import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; @@ -282,6 +282,47 @@ describe.skipIf(!support.supported)("heartbeat environment selection boundary", expect(reopen).not.toHaveBeenCalled(); expect(result.reusableExistingExecutionWorkspace).toBeNull(); }); + + async function migratedToRemoteStorage(generation: number) { + const f = await expired(); + restoration.removed = false; + const worktreePath = join(home, "removed-worktree"); + const snapshotId = randomUUID(); + await db.insert(executionWorkspaceSnapshots).values({ id: snapshotId, companyId: f.issue.companyId, executionWorkspaceId: f.saved.id, + sourceOperationId: randomUUID(), generation: 1, epoch: 1, status: "committed" }); + await db.update(executionWorkspaces).set({ + cwd: `/workspaces/${f.saved.id}`, providerRef: null, providerType: "cloud_sandbox", + cleanupReason: "reproducible_git_cache_expired", closedAt: new Date("2020-01-01T00:00:00Z"), + metadata: { createdByRuntime: true, gitBranchOwnershipVersion: 1, lifecycleGeneration: generation, + gitCacheRestoration: { schema: "paperclip.git-cache-restoration.v1", companyId: f.issue.companyId, workspaceId: f.saved.id, + sourceIssueId: f.issue.id, repoUrl: null, commit: "a".repeat(40), branchName: null, sourceKind: "managed_project", + projectId: f.project.id, sourcePath: home, worktreePath, gitBranchOwnershipVersion: 1, verifiedAt: "2020-01-01T00:00:00.000Z" }, + gitCacheExpiration: { schema: "paperclip.git-cache-expiration.v1", generation: 3, workspaceRemoved: true, completed: true, + worktreeTrash: join(home, ".expired"), worktreeAdmin: join(home, ".git", "worktrees", "removed"), baseTrash: null }, + remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 1, snapshotId, location: null, writerRunId: null, + dirty: false, source: { kind: "git", repoUrl: "https://example.test/repo.git", ref: "a".repeat(40), branchName: "saved" } } }, + }).where(eq(executionWorkspaces.id, f.saved.id)); + return f; + } + + it("reopens an expired workspace migrated to remote storage from its saved snapshot", async () => { + const { input, issue, saved } = await migratedToRemoteStorage(3); + const result = await selectHeartbeatEnvironment(db, input); + expect(result.reusableExistingExecutionWorkspace).toMatchObject({ id: saved.id, status: "active" }); + const stored = await executionWorkspaceService(db).getStoredById(issue.companyId, saved.id); + expect(stored).toMatchObject({ id: saved.id, status: "active", closedAt: null, cleanupReason: null, cwd: `/workspaces/${saved.id}` }); + expect(stored?.metadata?.lifecycleGeneration).toBe(4); + const [bound] = await db.select({ executionWorkspaceId: issues.executionWorkspaceId }).from(issues).where(eq(issues.id, issue.id)); + expect(bound?.executionWorkspaceId).toBe(saved.id); + }); + + it("does not treat a remote workspace's expiration from an earlier lifecycle as current", async () => { + const { input, svc } = await migratedToRemoteStorage(4); + const reopen = vi.spyOn(svc, "reopenClosedIsolatedExecutionWorkspaceForIssue"); + const result = await selectHeartbeatEnvironment(db, input); + expect(reopen).not.toHaveBeenCalled(); + expect(result.reusableExistingExecutionWorkspace).toBeNull(); + }); }); it.each(["muse", "openai_dot", "grok_bot"] as const)("keeps %s managed placement without adopting the task's selected workspace", async provider => { diff --git a/server/src/services/heartbeat/environment-selection.ts b/server/src/services/heartbeat/environment-selection.ts index 78f9e922b82..4d7f37fc046 100644 --- a/server/src/services/heartbeat/environment-selection.ts +++ b/server/src/services/heartbeat/environment-selection.ts @@ -3,7 +3,7 @@ import { heartbeatExternalProvider, nativeExecutionUsesTaskWorkspace } from "./e import { heartbeatRuns, issues, type Db, type agents } from "@paperclipai/db"; import { and, eq } from "drizzle-orm"; import { readGitCacheExpiration } from "../git-workspace-restoration.js"; -import type { ExecutionWorkspace, InstanceSettings, IssueExecutionWorkspaceSettings, ProjectExecutionWorkspacePolicy } from "@paperclipai/shared"; +import { readRemoteWorkspaceAuthority, type ExecutionWorkspace, type InstanceSettings, type IssueExecutionWorkspaceSettings, type ProjectExecutionWorkspacePolicy } from "@paperclipai/shared"; import { parseObject } from "../../adapters/utils.js"; import { logger } from "../../middleware/logger.js"; import { parseNativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; @@ -39,6 +39,13 @@ import { resolveNativeRecoveryExecutionWorkspaceBinding, resolveExecutionWorkspa type Issue = typeof issues.$inferSelect; +function gitCacheExpirationRemovedWorkspace(workspace: Parameters[0]) { + if (!readRemoteWorkspaceAuthority(workspace.metadata)) return readGitCacheExpiration(workspace)?.workspaceRemoved === true; + const expiration = parseObject(workspace.metadata?.gitCacheExpiration); + return expiration.schema === "paperclip.git-cache-expiration.v1" && expiration.workspaceRemoved === true + && Number.isSafeInteger(expiration.generation) && expiration.generation === workspace.metadata?.lifecycleGeneration; +} + export async function resolveSshAuthenticationBeforeRouting(input: { agentDefaultEnvironmentId: string | null; lowTrustIssueEnvironmentId: string | null; @@ -139,7 +146,7 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnviron if (existingExecutionWorkspace && issueId && !controllerOnly && !fresh && existingExecutionWorkspace.id === readNonEmptyString(issueRef?.executionWorkspaceId) && (existingExecutionWorkspace.status === "archived" || existingExecutionWorkspace.status === "cleanup_failed") - && (readGitCacheExpiration(existingExecutionWorkspace as Parameters[0])?.workspaceRemoved + && (gitCacheExpirationRemovedWorkspace(existingExecutionWorkspace as Parameters[0]) || readTaskDirectoryRetention(existingExecutionWorkspace) !== null || (existingExecutionWorkspace.sourceIssueId === issueId && existingExecutionWorkspace.cleanupReason?.startsWith("issue_terminal") === true))) {