From ad1686d913b4caeef9d2bd2ba9888d7c4261395a Mon Sep 17 00:00:00 2001 From: Dotta Date: Thu, 12 Nov 2026 23:36:44 -0600 Subject: [PATCH] fix(recovery): replace and park a held sandbox, release holds, and never trim unreleased receipts Co-Authored-By: Claude Opus 5.5 --- .../abandoned-workspace-files-hold.test.ts | 191 +++++++++++++++--- .../environment-retained-orphan-settlement.ts | 2 + server/src/services/environment-runtime.ts | 14 +- server/src/services/heartbeat/recovery.ts | 6 + .../remote-workspace-abandoned-files-hold.ts | 135 ++++++++++++- .../remote-workspace-epoch-abandonment.ts | 17 +- .../reusable-sandbox-resume-replacement.ts | 8 +- 7 files changed, 336 insertions(+), 37 deletions(-) diff --git a/server/src/__tests__/abandoned-workspace-files-hold.test.ts b/server/src/__tests__/abandoned-workspace-files-hold.test.ts index 2366c00a9cf..50bb8cd3f29 100644 --- a/server/src/__tests__/abandoned-workspace-files-hold.test.ts +++ b/server/src/__tests__/abandoned-workspace-files-hold.test.ts @@ -23,8 +23,13 @@ import { environmentService } from "../services/environments.ts"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts"; import { abandonUnverifiedRemoteWorkspaceEpoch } from "../services/remote-workspace-epoch-abandonment.ts"; import { nativeWorkspaceExportPendingForLease } from "../services/native-runtime/native-workspace-finalization-state.ts"; -import { REUSABLE_SANDBOX_RESUME_FAILED_CODE } from "../services/reusable-sandbox-resume-error.ts"; -import { retireReplacedReusableSandboxLease, reusableSandboxReplacementIsSafe } from "../services/reusable-sandbox-resume-replacement.ts"; +import { retireReplacedReusableSandboxLease } from "../services/reusable-sandbox-resume-replacement.ts"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { releasableRetainedOrphanCondition, settleRetainedOrphanSandbox } from "../services/environment-retained-orphan-settlement.ts"; +import { + ABANDONED_WORKSPACE_FILES_PARKED_KEY, ABANDONED_WORKSPACE_FILES_PARKED_REASON, ABANDONED_WORKSPACE_FILES_RETENTION_DAYS, + expireAbandonedWorkspaceFileHolds, releaseAbandonedWorkspaceFiles, +} from "../services/remote-workspace-abandoned-files-hold.ts"; vi.mock("../services/native-runtime/native-harness-backup-storage.js", () => ({ verifyRecoverableNativeHarnessBackup: vi.fn(async () => true), @@ -179,36 +184,183 @@ describe.skipIf(!support.supported)("sandbox that holds files from an abandoned return call.mock.calls.filter(([, method]) => method === "environmentDestroyLease"); } - it("refuses to replace the sandbox after a failed resume and keeps it out of cleanup", async () => { + async function sweep(runtime: ReturnType) { + return await heartbeatService(db, { environmentRuntime: runtime as never }).sweepPendingCleanupLeases({ backoffMs: 0 }); + } + + async function newRun(seeded: Seeded) { + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: seeded.companyId, agentId: seeded.agentId, + issueId: seeded.issueId, invocationSource: "assignment", status: "running" }); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, seeded.runId)); + await reserveFor(seeded, runId); + return runId; + } + + it("gives the next run a new sandbox at once and parks the held one, which cleanup and later runs leave alone", async () => { const seeded = await seed(); await abandon(seeded); const { call, runtime } = worker(seeded); - await expect(acquire(seeded, runtime)).rejects.toMatchObject({ code: REUSABLE_SANDBOX_RESUME_FAILED_CODE }); + const acquired = await acquire(seeded, runtime); - expect(await leaseRow(seeded)).toMatchObject({ status: "retained", providerLeaseId: seeded.providerLeaseId }); + expect(acquired.lease.providerLeaseId).toBe("replacement-sandbox"); + expect(acquired.lease.metadata?.sandboxLeaseAcquisition).toEqual({ outcome: "replacement", reason: "resume_failed" }); + const parked = await leaseRow(seeded); + expect(parked).toMatchObject({ status: "retained", failureReason: ABANDONED_WORKSPACE_FILES_PARKED_REASON }); + expect(parked.metadata).toHaveProperty(ABANDONED_WORKSPACE_FILES_PARKED_KEY); expect(await nativeWorkspaceExportPendingForLease(db, seeded.lease)).toBe(true); - await expect(runtime.destroyRunLease({ environment: seeded.environment, lease: await leaseRow(seeded), + + await sweep(runtime); + await expect(runtime.destroyRunLease({ environment: seeded.environment, lease: parked, failureReason: "pending_cleanup_retry" })).resolves.toBeNull(); + await expect(runtime.retryPendingSandboxTeardown({ environment: seeded.environment, lease: parked })).rejects.toThrow(); expect(destroyCalls(call)).toEqual([]); - expect(await db.select().from(environmentLeases).where(eq(environmentLeases.status, "pending_cleanup"))).toEqual([]); + expect(await leaseRow(seeded)).toMatchObject({ status: "retained" }); + + await db.update(environmentLeases).set({ status: "released" }).where(eq(environmentLeases.providerLeaseId, "replacement-sandbox")); + const nextRunId = await newRun(seeded); + const later = worker(seeded); + let clock = Date.now(); + vi.spyOn(Date, "now").mockImplementation(() => (clock += 40_000)); + later.call.mockImplementation(async (_pluginId: string, method: string) => { + if (method === "environmentResumeLease") return { providerLeaseId: "replacement-sandbox", metadata: { provider: "fake-plugin", + image: "fake:test", timeoutMs: 300_000, reuseLease: true, remoteCwd: "/home/daytona/paperclip-workspace" } }; + throw new Error(`Unexpected plugin method: ${method}`); + }); + const next = await later.runtime.acquireRunLease({ companyId: seeded.companyId, environment: seeded.environment, + issueId: seeded.issueId, agentId: seeded.agentId, adapterType: "paperclip_runner", heartbeatRunId: nextRunId, + persistedExecutionWorkspace: { id: seeded.executionWorkspaceId, mode: "isolated_workspace" } }); + expect(next.lease.providerLeaseId).toBe("replacement-sandbox"); + const resumed = later.call.mock.calls.filter(([, method]) => method === "environmentResumeLease"); + expect(resumed.map(([, , params]) => (params as { providerLeaseId: string }).providerLeaseId)).toEqual(["replacement-sandbox"]); + expect(await leaseRow(seeded)).toMatchObject({ status: "retained" }); }); - it("parks a held lease as retained when it is retired anyway", async () => { + it("pulls a held lease already queued for cleanup back to retained, and leaves it on the provider", async () => { const seeded = await seed(); await abandon(seeded); - expect(await retireReplacedReusableSandboxLease({ db, lease: seeded.lease as EnvironmentLease, - companyId: seeded.companyId, heartbeatRunId: seeded.runId })).toBe(true); - expect(await leaseRow(seeded)).toMatchObject({ status: "retained" }); + await db.update(environmentLeases).set({ status: "pending_cleanup", cleanupStatus: "failed", failureReason: "resume_failed" }) + .where(eq(environmentLeases.id, seeded.lease.id)); + const { call, runtime } = worker(seeded); + await sweep(runtime); + expect(destroyCalls(call)).toEqual([]); + expect(await leaseRow(seeded)).toMatchObject({ status: "retained", failureReason: ABANDONED_WORKSPACE_FILES_PARKED_REASON }); }); it("treats a receipt written before release fields existed as unreleased", async () => { const seeded = await seed(); await abandon(seeded); await setReceipts(seeded, ({ retainUntil: _retainUntil, released: _released, ...receipt }) => receipt); - expect(await reusableSandboxReplacementIsSafe({ db, lease: seeded.lease as EnvironmentLease, companyId: seeded.companyId, - heartbeatRunId: seeded.runId, executionWorkspaceId: seeded.executionWorkspaceId, adapterType: "paperclip_runner", - cause: new Error(REFUSAL) })).toBe(false); + expect(await nativeWorkspaceExportPendingForLease(db, seeded.lease)).toBe(true); + expect(await retireReplacedReusableSandboxLease({ db, lease: seeded.lease as EnvironmentLease, + companyId: seeded.companyId, heartbeatRunId: seeded.runId })).toBe(true); + expect(await leaseRow(seeded)).toMatchObject({ status: "retained" }); + }); + + it("records a retention expiry on the receipt", async () => { + const seeded = await seed(); + await abandon(seeded); + const [receipt] = (await readWorkspace(seeded)).metadata!.remoteWorkspaceAbandonedEpochs as Array>; + expect(Date.parse(receipt!.retainUntil as string) - Date.parse(receipt!.abandonedAt as string)) + .toBe(ABANDONED_WORKSPACE_FILES_RETENTION_DAYS * 86_400_000); + }); + + it.each([ + { reason: "recovered" as const, actorType: "system" as const, actorId: "workspace-recovery" }, + { reason: "discarded" as const, actorType: "user" as const, actorId: "board-user" }, + ])("hands the parked lease to normal cleanup once the files are $reason", async ({ reason, actorType, actorId }) => { + const seeded = await seed(); + await abandon(seeded); + const { call, runtime } = worker(seeded); + await acquire(seeded, runtime); + expect(await releaseAbandonedWorkspaceFiles(db, { companyId: seeded.companyId, workspaceId: seeded.executionWorkspaceId, + epoch: 1, reason, actorType, actorId })).toBe(true); + expect(await leaseRow(seeded)).toMatchObject({ status: "pending_cleanup" }); + vi.restoreAllMocks(); + await sweep(runtime); + expect(destroyCalls(call).map(([, , params]) => (params as { providerLeaseId: string }).providerLeaseId)) + .toEqual([seeded.providerLeaseId]); + expect(await leaseRow(seeded)).toMatchObject({ status: "expired" }); + }); + + it("removes the files only after the retention period, with a plain activity entry on the task", async () => { + const seeded = await seed(); + await abandon(seeded); + const { call, runtime } = worker(seeded); + await acquire(seeded, runtime); + vi.restoreAllMocks(); + + expect(await expireAbandonedWorkspaceFileHolds(db, new Date(Date.now() + 86_400_000))).toEqual({ expired: 0 }); + await sweep(runtime); + expect(destroyCalls(call)).toEqual([]); + expect(await db.select().from(activityLog).where(eq(activityLog.action, "workspace.abandoned_files_released"))).toEqual([]); + + expect(await expireAbandonedWorkspaceFileHolds(db, new Date(Date.now() + 8 * 86_400_000))).toEqual({ expired: 1 }); + const [entry] = await db.select().from(activityLog).where(eq(activityLog.action, "workspace.abandoned_files_released")); + expect(entry).toMatchObject({ entityType: "issue", entityId: seeded.issueId, actorType: "system", actorId: "workspace-retention" }); + expect(entry!.details).toMatchObject({ reason: "retention_expired", + summary: "Unsaved files from an interrupted run were kept for 8 days and have now been removed." }); + await sweep(runtime); + expect(destroyCalls(call)).toHaveLength(1); + expect(await leaseRow(seeded)).toMatchObject({ status: "expired" }); + }); + + async function stoppedWarmOrphan(seeded: Seeded) { + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, seeded.runId)); + await db.update(environmentLeases).set({ status: "failed", cleanupStatus: "success", leasePolicy: "reuse_by_environment", + metadata: { ...seeded.lease.metadata, remoteExecutionTermination: { state: "stopped", leaseId: seeded.lease.id, + runId: seeded.abandonedRunId } } }).where(eq(environmentLeases.id, seeded.lease.id)); + const listed = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(releasableRetainedOrphanCondition()); + const settled = await settleRetainedOrphanSandbox(db, { recordId: seeded.lease.id, runId: seeded.abandonedRunId } as never, + { now: new Date(), proof: { reason: "owner_gone" } as never }); + return { listed: listed.map(row => row.id), settled }; + } + + it("keeps a held sandbox when the retained orphan settlement reviews it", async () => { + const seeded = await seed(); + await abandon(seeded); + const { listed, settled } = await stoppedWarmOrphan(seeded); + expect(listed).toEqual([]); + expect(settled).toEqual({ settled: false, reason: "workspace_preservation_pending" }); + expect(await leaseRow(seeded)).toMatchObject({ status: "failed" }); + }); + + it("lists the sandbox for the retained orphan settlement again once the receipt is released", async () => { + const seeded = await seed(); + await abandon(seeded); + await setReceipts(seeded, receipt => ({ ...receipt, + released: { reason: "discarded", releasedAt: new Date().toISOString(), actorType: "user", actorId: "board-user" } })); + const { listed, settled } = await stoppedWarmOrphan(seeded); + expect(listed).toEqual([seeded.lease.id]); + expect(settled.reason).not.toBe("workspace_preservation_pending"); + expect(await nativeWorkspaceExportPendingForLease(db, seeded.lease)).toBe(false); + }); + + async function abandonOnOtherSandbox(seeded: Seeded, remoteCwd: string) { + const workspace = await readWorkspace(seeded); + const authority = workspace.metadata!.remoteWorkspace as Record & { epoch: number }; + const location = { environmentId: seeded.environment.id, leaseId: randomUUID(), providerLeaseId: "sandbox-b", remoteCwd }; + await db.update(executionWorkspaces).set({ metadata: { ...workspace.metadata, remoteWorkspace: { ...authority, + writerRunId: seeded.runId, dirty: true, location } } }).where(eq(executionWorkspaces.id, seeded.executionWorkspaceId)); + await db.transaction(tx => abandonUnverifiedRemoteWorkspaceEpoch(tx, { companyId: seeded.companyId, + workspaceId: seeded.executionWorkspaceId, runId: seeded.runId, epoch: authority.epoch, + snapshotId: authority.snapshotId as string, location })); + } + + it("keeps holding the first sandbox after many later abandonments on another sandbox", async () => { + const seeded = await seed(); + await abandon(seeded); + for (let index = 0; index < 21; index++) await abandonOnOtherSandbox(seeded, `/root-${index}`); + for (let index = 0; index < 5; index++) await abandonOnOtherSandbox(seeded, "/root-0"); + const receipts = (await readWorkspace(seeded)).metadata!.remoteWorkspaceAbandonedEpochs as Array>; + expect(receipts).toHaveLength(22); + expect(receipts.filter(receipt => (receipt.location as { remoteCwd: string }).remoteCwd === "/root-0")).toHaveLength(1); + expect(await nativeWorkspaceExportPendingForLease(db, seeded.lease)).toBe(true); + + expect(await releaseAbandonedWorkspaceFiles(db, { companyId: seeded.companyId, workspaceId: seeded.executionWorkspaceId, + epoch: 1, reason: "discarded", actorType: "user", actorId: "board-user" })).toBe(true); + expect(await nativeWorkspaceExportPendingForLease(db, seeded.lease)).toBe(false); }); it("replaces and cleans the sandbox as before when the receipt names a different sandbox", async () => { @@ -234,15 +386,4 @@ describe.skipIf(!support.supported)("sandbox that holds files from an abandoned expect(acquired.lease.providerLeaseId).toBe("replacement-sandbox"); expect(await leaseRow(seeded)).toMatchObject({ status: "pending_cleanup" }); }); - - it("replaces and cleans the sandbox once the receipt is released", async () => { - const seeded = await seed(); - await abandon(seeded); - await setReceipts(seeded, receipt => ({ ...receipt, - released: { reason: "discarded", releasedAt: new Date().toISOString(), actorType: "user", actorId: "board-user" } })); - const { runtime } = worker(seeded); - const acquired = await acquire(seeded, runtime); - expect(acquired.lease.providerLeaseId).toBe("replacement-sandbox"); - expect(await leaseRow(seeded)).toMatchObject({ status: "pending_cleanup" }); - }); }); diff --git a/server/src/services/environment-retained-orphan-settlement.ts b/server/src/services/environment-retained-orphan-settlement.ts index 071cd598105..f9ba599d920 100644 --- a/server/src/services/environment-retained-orphan-settlement.ts +++ b/server/src/services/environment-retained-orphan-settlement.ts @@ -2,6 +2,7 @@ import { and, eq, inArray, ne, notInArray, or, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db"; import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js"; import { nativeWorkspaceExportPendingForLease } from "./native-runtime/native-workspace-finalization-state.js"; +import { abandonedWorkspaceFilesHeldOnLeaseRowSql } from "./remote-workspace-abandoned-files-hold.js"; import type { OwnerProof } from "./owner-proof.js"; import type { InProgressRecord, SettleOutcome } from "./recovery/ownership-registry.js"; import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; @@ -111,6 +112,7 @@ function softlyHeldSql(now?: Date) { function alwaysHeldSql() { return sql`(${environmentLeases.metadata} ?| array['nativeWorkspaceExportResume', 'sandboxStopAndRetain', 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', 'runnerTaskSourceConsumer'] + or ${abandonedWorkspaceFilesHeldOnLeaseRowSql()} or coalesce(${environmentLeases.metadata}->>'pendingCleanupInFlight', 'false') = 'true' or coalesce(${environmentLeases.metadata}#>>'{legacyShutdownWorkspaceSettlement,state}' = 'pending', false) or exists (select 1 from heartbeat_runs run where run.id = ${environmentLeases.heartbeatRunId} diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index b637afc081f..cd0f523d8c8 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -22,6 +22,7 @@ import { flushDeferredEnvironmentCleanup, registerDeferredEnvironmentCleanup, wr import { executeEnvironmentTask, pluginEnvironmentSupportsTasks, settleDispatchedEnvironmentTask } from "./environment-task-runtime.js"; import { allowLegacyShutdownWorkspaceCleanup, legacyShutdownWorkspaceResourceProtected } from "./legacy-shutdown-workspace-settlement.js"; import { nativeWorkspaceExportPendingForLease, nativeWorkspaceExportPendingForResource } from "./native-runtime/native-workspace-finalization-state.js"; +import { abandonedWorkspaceFilesHeldOnLease, abandonedWorkspaceFilesParked, parkAbandonedWorkspaceFilesLease } from "./remote-workspace-abandoned-files-hold.js"; import { beginIdleTrackedWork } from "./task-admission.js"; import { historicalProviderCredentials } from "./historical-provider-credentials.js"; import { ownedWorkspaceRecoveryLease, type WorkspaceRecoverySourceIdentity } from "./workspace-recovery-source.js"; @@ -1136,14 +1137,16 @@ async function waitForSettlingReusableLease(db: Db, input: { } function reusableLeaseCanBeResumed(input: { - lease: Pick; + lease: Pick; heartbeatRunId: string | null; }): boolean { + if (abandonedWorkspaceFilesParked(input.lease)) return false; if (input.lease.status === "released" || input.lease.status === "retained") return true; return input.lease.status === "active" && input.heartbeatRunId !== null && input.lease.heartbeatRunId === input.heartbeatRunId; } -function reusableLeaseCanBeCleanedUp(lease: Pick): boolean { +function reusableLeaseCanBeCleanedUp(lease: Pick): boolean { + if (abandonedWorkspaceFilesParked(lease)) return false; return lease.status === "released" || lease.status === "retained"; } @@ -3213,6 +3216,10 @@ function createSandboxEnvironmentDriver( failureReason: string; }): Promise { if (await legacyShutdownWorkspaceResourceProtected(db, input.lease)) return null; + if (await abandonedWorkspaceFilesHeldOnLease(db, input.lease)) { + await parkAbandonedWorkspaceFilesLease(db, input.lease, ["released", "retained", "failed", "pending_cleanup"]); + return null; + } let cleanupStatus: "success" | "failed" = "success"; let termination: ReturnType; const metadata = input.lease.metadata ?? {}; @@ -4331,6 +4338,9 @@ export function environmentRuntimeService( if (!(await allowLegacyShutdownWorkspaceCleanup(db, input.lease))) { throw new Error("Shutdown workspace settlement is still pending."); } + if (!hasStopOnlyCleanup(input.lease) && await abandonedWorkspaceFilesHeldOnLease(db, input.lease)) { + throw new Error("Unsaved files from an abandoned workspace are held on this sandbox; destructive cleanup is forbidden."); + } if (input.lease.metadata?.legacyShutdownWorkspaceSettlement) { const current = await environmentsSvc.getLeaseById(input.lease.id); if (!current) throw new Error("Shutdown workspace source is unavailable."); diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index bab1110db5a..402192f82e8 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -31,6 +31,7 @@ import { createHeartbeatAgentStatus } from "./agent-status.js"; import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js"; import { preserveCancelledNativeWorkspaces, preserveOrphanedNativeWorkspace } from "../native-runtime/native-failed-workspace-recovery.js"; import { nativeWorkspaceExportPendingForLease, pendingNativeWorkspaceFinalizationCondition } from "../native-runtime/native-workspace-finalization-state.js"; +import { expireAbandonedWorkspaceFileHoldsWhenDue, parkAbandonedWorkspaceFilesLease } from "../remote-workspace-abandoned-files-hold.js"; import { CHAT_COMPLETION_WAKE_REASON } from "../chat-completion-delivery.js"; import { hasStopOnlyCleanup, @@ -1747,6 +1748,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD logger.warn({ errorKind: "teardown_claim_settle_failed" }, "teardown claim settle failed; a later sweep retries"); }); + if (!manualRetry) await expireAbandonedWorkspaceFileHoldsWhenDue(db).catch(() => { + logger.warn({ errorKind: "abandoned_workspace_files_expiry_failed" }, "abandoned workspace file expiry failed; a later sweep retries"); + }); + const rows = await db .select() .from(environmentLeases) @@ -1767,6 +1772,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD let capped = 0; for (const row of rows) { if (pendingCleanupAttemptsInFlight.has(row.id)) continue; + if (!hasStopOnlyCleanup(row) && await parkAbandonedWorkspaceFilesLease(db, row, ["pending_cleanup"])) continue; if (!hasStopOnlyCleanup(row) && await nativeWorkspaceExportPendingForLease(db, row)) { await deferPendingCleanupLease(row.id); continue; diff --git a/server/src/services/remote-workspace-abandoned-files-hold.ts b/server/src/services/remote-workspace-abandoned-files-hold.ts index 6fdb8373471..629aeed4b85 100644 --- a/server/src/services/remote-workspace-abandoned-files-hold.ts +++ b/server/src/services/remote-workspace-abandoned-files-hold.ts @@ -1,13 +1,21 @@ -import { sql, type SQL } from "drizzle-orm"; -import { environmentLeases, type Db } from "@paperclipai/db"; -import { REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA } from "./remote-workspace-epoch-abandonment.js"; +import { and, eq, inArray, sql, type SQL } from "drizzle-orm"; +import { environmentLeases, executionWorkspaces, heartbeatRuns, type Db } from "@paperclipai/db"; +import { logger } from "../middleware/logger.js"; +import { logActivity } from "./activity-log.js"; +import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js"; +import { + ABANDONED_WORKSPACE_FILES_RETENTION_DAYS, ABANDONED_WORKSPACE_FILES_RETENTION_MS, REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA, +} from "./remote-workspace-epoch-abandonment.js"; -export const ABANDONED_WORKSPACE_FILES_RETENTION_DAYS = 7; -export const ABANDONED_WORKSPACE_FILES_RETENTION_MS = ABANDONED_WORKSPACE_FILES_RETENTION_DAYS * 24 * 60 * 60 * 1000; +export { ABANDONED_WORKSPACE_FILES_RETENTION_DAYS, ABANDONED_WORKSPACE_FILES_RETENTION_MS }; +export const ABANDONED_WORKSPACE_FILES_PARKED_KEY = "abandonedWorkspaceFilesParked"; +export const ABANDONED_WORKSPACE_FILES_PARKED_REASON = "abandoned_workspace_files_held"; +export const ABANDONED_WORKSPACE_FILES_RELEASED_REASON = "abandoned_workspace_files_released"; export type AbandonedWorkspaceFilesReleaseReason = "recovered" | "discarded" | "retention_expired"; type HoldLease = Pick; +type Receipt = Record & { location?: { providerLeaseId?: unknown }; released?: unknown }; export function abandonedWorkspaceFilesHeldSql(companyId: SQL | string, providerLeaseId: SQL | string): SQL { return sql`exists (select 1 from execution_workspaces held_workspace @@ -31,3 +39,120 @@ export async function abandonedWorkspaceFilesHeldOnLease(db: Pick sql`${lease.companyId}::uuid`, lease.providerLeaseId)} as held`); return row?.held === true; } + +export function abandonedWorkspaceFilesParked(lease: { metadata?: Record | null }): boolean { + return lease.metadata?.[ABANDONED_WORKSPACE_FILES_PARKED_KEY] != null; +} + +export async function parkAbandonedWorkspaceFilesLease(db: Db, lease: Pick, statuses: string[]): Promise { + const now = new Date(); + const parked = await writeEnvironmentCleanup(db, tx => tx.update(environmentLeases).set({ + status: "retained", cleanupStatus: "failed", failureReason: ABANDONED_WORKSPACE_FILES_PARKED_REASON, updatedAt: now, + metadata: sql`(case when jsonb_typeof(${environmentLeases.metadata}) = 'object' then ${environmentLeases.metadata} else '{}'::jsonb end) + || ${JSON.stringify({ [ABANDONED_WORKSPACE_FILES_PARKED_KEY]: { parkedAt: now.toISOString() }, pendingCleanupInFlight: false })}::jsonb`, + }).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId), + inArray(environmentLeases.status, statuses), + sql`coalesce(${environmentLeases.metadata}->>'pendingCleanupInFlight', 'false') != 'true'`, + abandonedWorkspaceFilesHeldOnLeaseRowSql())).returning({ id: environmentLeases.id }), + { companyId: lease.companyId, runId: lease.heartbeatRunId ?? undefined, leaseId: lease.id }); + return parked.length > 0; +} + +function receiptRetainUntil(receipt: Receipt): number { + const explicit = typeof receipt.retainUntil === "string" ? Date.parse(receipt.retainUntil) : Number.NaN; + if (Number.isFinite(explicit)) return explicit; + const abandonedAt = typeof receipt.abandonedAt === "string" ? Date.parse(receipt.abandonedAt) : Number.NaN; + return (Number.isFinite(abandonedAt) ? abandonedAt : 0) + ABANDONED_WORKSPACE_FILES_RETENTION_MS; +} + +function unreleased(receipt: unknown): receipt is Receipt { + const value = receipt as Receipt | null; + return value?.schema === REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA && value.released == null + && typeof value.location?.providerLeaseId === "string"; +} + +export async function releaseAbandonedWorkspaceFiles(db: Db, input: { + companyId: string; workspaceId: string; epoch: number; reason: AbandonedWorkspaceFilesReleaseReason; + actorType: "system" | "user" | "agent"; actorId: string; now?: Date; +}): Promise { + const now = input.now ?? new Date(); + return db.transaction(async transaction => { + const tx = transaction as unknown as Db; + const [workspace] = await tx.select().from(executionWorkspaces).where(and( + eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, input.workspaceId))).for("update"); + const receipts = Array.isArray(workspace?.metadata?.remoteWorkspaceAbandonedEpochs) + ? workspace!.metadata!.remoteWorkspaceAbandonedEpochs as unknown[] : []; + const target = receipts.find(receipt => unreleased(receipt) && receipt.epoch === input.epoch) as Receipt | undefined; + if (!workspace || !target) return false; + const released = { reason: input.reason, releasedAt: now.toISOString(), actorType: input.actorType, actorId: input.actorId }; + await tx.update(executionWorkspaces).set({ updatedAt: now, metadata: { ...workspace.metadata, + remoteWorkspaceAbandonedEpochs: receipts.map(receipt => receipt === target ? { ...target, released } : receipt) } }) + .where(and(eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, workspace.id))); + const providerLeaseId = target.location!.providerLeaseId as string; + const unparked = await writeEnvironmentCleanup(tx, write => write.update(environmentLeases).set({ + status: "pending_cleanup", cleanupStatus: "failed", failureReason: ABANDONED_WORKSPACE_FILES_RELEASED_REASON, + releasedAt: now, updatedAt: now, + metadata: sql`${environmentLeases.metadata} - ${ABANDONED_WORKSPACE_FILES_PARKED_KEY}`, + }).where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.providerLeaseId, providerLeaseId), + eq(environmentLeases.status, "retained"), sql`${environmentLeases.metadata} ? ${ABANDONED_WORKSPACE_FILES_PARKED_KEY}`, + sql`not ${abandonedWorkspaceFilesHeldOnLeaseRowSql()}`)).returning({ id: environmentLeases.id }), + { companyId: input.companyId }); + const [run] = typeof target.runId === "string" ? await tx.select({ issueId: heartbeatRuns.issueId }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, target.runId))) : []; + const issueId = workspace.sourceIssueId ?? run?.issueId ?? null; + const kept = Math.max(1, Math.round((now.getTime() - Date.parse(String(target.abandonedAt ?? now.toISOString()))) / 86_400_000)); + const summary = input.reason === "retention_expired" + ? `Unsaved files from an interrupted run were kept for ${kept} ${kept === 1 ? "day" : "days"} and have now been removed.` + : input.reason === "discarded" + ? "Unsaved files from an interrupted run were discarded and will be removed." + : "Unsaved files from an interrupted run were saved to the task's recovered files."; + await logActivity(tx, { companyId: input.companyId, actorType: input.actorType, actorId: input.actorId, + action: "workspace.abandoned_files_released", entityType: issueId ? "issue" : "execution_workspace", + entityId: issueId ?? workspace.id, runId: typeof target.runId === "string" ? target.runId : undefined, + details: { summary, reason: input.reason, workspaceId: workspace.id, abandonedEpoch: input.epoch, + retainUntil: new Date(receiptRetainUntil(target)).toISOString(), leasesHandedToCleanup: unparked.length } }); + return true; + }); +} + +export async function expireAbandonedWorkspaceFileHolds(db: Db, now = new Date()): Promise<{ expired: number }> { + const rows = await db.select({ id: executionWorkspaces.id, companyId: executionWorkspaces.companyId, + receipts: sql`${executionWorkspaces.metadata}->'remoteWorkspaceAbandonedEpochs'` }).from(executionWorkspaces) + .where(sql`jsonb_typeof(${executionWorkspaces.metadata}->'remoteWorkspaceAbandonedEpochs') = 'array' + and exists (select 1 from jsonb_array_elements(${executionWorkspaces.metadata}->'remoteWorkspaceAbandonedEpochs') receipt + where receipt->>'schema' = ${REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA} + and coalesce(jsonb_typeof(receipt->'released'), 'null') = 'null')`); + let expired = 0; + const held = new Map(); + for (const row of rows) { + for (const receipt of Array.isArray(row.receipts) ? row.receipts : []) { + if (!unreleased(receipt)) continue; + if (receiptRetainUntil(receipt) > now.getTime() || typeof receipt.epoch !== "number") { + held.set(row.companyId, (held.get(row.companyId) ?? 0) + 1); + continue; + } + if (await releaseAbandonedWorkspaceFiles(db, { companyId: row.companyId, workspaceId: row.id, epoch: receipt.epoch, + reason: "retention_expired", actorType: "system", actorId: "workspace-retention", now })) expired += 1; + } + } + if (expired > 0 || held.size > 0) { + const parked = await db.select({ companyId: environmentLeases.companyId, count: sql`count(*)::int` }) + .from(environmentLeases).where(sql`${environmentLeases.metadata} ? ${ABANDONED_WORKSPACE_FILES_PARKED_KEY}`) + .groupBy(environmentLeases.companyId); + logger.info({ expired, retentionDays: ABANDONED_WORKSPACE_FILES_RETENTION_DAYS, + heldReceiptsByCompany: Object.fromEntries(held), parkedLeasesByCompany: Object.fromEntries(parked.map(p => [p.companyId, p.count])) }, + "abandoned workspace file holds checked"); + } + return { expired }; +} + +const ABANDONED_WORKSPACE_FILES_EXPIRY_INTERVAL_MS = 60 * 60 * 1000; +const lastExpiryPass = new WeakMap(); + +export async function expireAbandonedWorkspaceFileHoldsWhenDue(db: Db, now = new Date()): Promise<{ expired: number }> { + const last = lastExpiryPass.get(db); + if (last !== undefined && now.getTime() - last < ABANDONED_WORKSPACE_FILES_EXPIRY_INTERVAL_MS) return { expired: 0 }; + lastExpiryPass.set(db, now.getTime()); + return await expireAbandonedWorkspaceFileHolds(db, now); +} diff --git a/server/src/services/remote-workspace-epoch-abandonment.ts b/server/src/services/remote-workspace-epoch-abandonment.ts index a8091a993d0..f0f2739b832 100644 --- a/server/src/services/remote-workspace-epoch-abandonment.ts +++ b/server/src/services/remote-workspace-epoch-abandonment.ts @@ -5,6 +5,8 @@ import { persistActivity } from "./activity-log.js"; type Transaction = Parameters[0]>[0]; export const REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA = "paperclip.remote-workspace-abandoned-epoch.v1"; +export const ABANDONED_WORKSPACE_FILES_RETENTION_DAYS = 7; +export const ABANDONED_WORKSPACE_FILES_RETENTION_MS = ABANDONED_WORKSPACE_FILES_RETENTION_DAYS * 24 * 60 * 60 * 1000; /** * Ends an epoch whose unsaved files cannot be verified, without applying them. @@ -35,9 +37,20 @@ export async function abandonUnverifiedRemoteWorkspaceEpoch(tx: Transaction, inp const abandoned = { schema: REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA, epoch: current.epoch, runId: input.runId, snapshotId: current.snapshotId, location, providerRef: workspace.providerRef, ...(workspace.metadata?.nativeWorkspaceMigration !== undefined ? { nativeWorkspaceMigration: workspace.metadata.nativeWorkspaceMigration } : {}), - abandonedAt: new Date().toISOString() }; + abandonedAt: new Date().toISOString(), retainUntil: new Date(Date.now() + ABANDONED_WORKSPACE_FILES_RETENTION_MS).toISOString() }; + const held = (receipt: unknown) => { + const value = receipt as { schema?: unknown; released?: unknown; location?: { providerLeaseId?: unknown } } | null; + return value?.schema === REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA && value.released == null + && typeof value.location?.providerLeaseId === "string"; + }; + const sameRoot = (receipt: unknown) => { + const value = receipt as { location?: { providerLeaseId?: unknown; remoteCwd?: unknown } }; + return held(receipt) && value.location?.providerLeaseId === location.providerLeaseId && value.location?.remoteCwd === location.remoteCwd; + }; + const kept = [...prior.filter(receipt => !sameRoot(receipt)), abandoned]; + const releasedHistory = kept.filter(receipt => !held(receipt)).slice(-20); const metadata: Record = { ...workspace.metadata, remoteWorkspace: next, - remoteWorkspaceAbandonedEpochs: [...prior, abandoned].slice(-20) }; + remoteWorkspaceAbandonedEpochs: kept.filter(receipt => held(receipt) || releasedHistory.includes(receipt)) }; // The migration receipt names the old root as the next preparation's root. delete metadata.nativeWorkspaceMigration; const [saved] = await tx.update(executionWorkspaces).set({ providerRef: null, cwd: `/workspaces/${workspace.id}`, metadata, diff --git a/server/src/services/reusable-sandbox-resume-replacement.ts b/server/src/services/reusable-sandbox-resume-replacement.ts index a7099e21d31..d323a93a9cb 100644 --- a/server/src/services/reusable-sandbox-resume-replacement.ts +++ b/server/src/services/reusable-sandbox-resume-replacement.ts @@ -7,7 +7,7 @@ import type { EnvironmentLease } from "@paperclipai/shared"; import { writeEnvironmentCleanup } from "./environment-cleanup-notifications.js"; import { verifyRecoverableNativeHarnessBackup } from "./native-runtime/native-harness-backup-storage.js"; import { findPluginWorkerUnavailableError } from "./plugin-worker-unavailable-error.js"; -import { abandonedWorkspaceFilesHeldOnLease, abandonedWorkspaceFilesHeldOnLeaseRowSql } from "./remote-workspace-abandoned-files-hold.js"; +import { abandonedWorkspaceFilesHeldOnLeaseRowSql, ABANDONED_WORKSPACE_FILES_PARKED_KEY, ABANDONED_WORKSPACE_FILES_PARKED_REASON } from "./remote-workspace-abandoned-files-hold.js"; import { sandboxProviderFailureLabel } from "./remote-workspace-transport.js"; /** @@ -107,7 +107,6 @@ export async function reusableSandboxReplacementIsSafe(input: { eq(executionWorkspaceSnapshots.status, "committed"), )); if (!snapshot) return false; - if (await abandonedWorkspaceFilesHeldOnLease(db, lease)) return false; const scope = lease.metadata?.reusableSandboxLease as { adapterType?: unknown } | undefined; if ((input.adapterType === "paperclip_runner" || scope?.adapterType === "paperclip_runner") @@ -137,10 +136,13 @@ export async function retireReplacedReusableSandboxLease(input: { const [claimed] = await writeEnvironmentCleanup(db, tx => tx.update(environmentLeases).set({ status: sql`case when ${held} then 'retained' else 'pending_cleanup' end`, cleanupStatus: "failed", - failureReason: REUSABLE_SANDBOX_RESUME_REPLACED_REASON, + failureReason: sql`case when ${held} then ${ABANDONED_WORKSPACE_FILES_PARKED_REASON} else ${REUSABLE_SANDBOX_RESUME_REPLACED_REASON} end`, releasedAt: now, lastUsedAt: now, updatedAt: now, + metadata: sql`case when ${held} then coalesce(${environmentLeases.metadata}, '{}'::jsonb) + || ${JSON.stringify({ [ABANDONED_WORKSPACE_FILES_PARKED_KEY]: { parkedAt: now.toISOString() } })}::jsonb + else ${environmentLeases.metadata} end`, }).where(and( eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, input.companyId),