diff --git a/server/src/__tests__/abandoned-workspace-files-hold.test.ts b/server/src/__tests__/abandoned-workspace-files-hold.test.ts index 50bb8cd3f29..53ec13cc30b 100644 --- a/server/src/__tests__/abandoned-workspace-files-hold.test.ts +++ b/server/src/__tests__/abandoned-workspace-files-hold.test.ts @@ -25,6 +25,7 @@ import { abandonUnverifiedRemoteWorkspaceEpoch } from "../services/remote-worksp import { nativeWorkspaceExportPendingForLease } from "../services/native-runtime/native-workspace-finalization-state.ts"; import { retireReplacedReusableSandboxLease } from "../services/reusable-sandbox-resume-replacement.ts"; import { heartbeatService } from "../services/heartbeat.ts"; +import { nextEnvironmentCleanupAt } from "../services/environment-cleanup-state.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, @@ -153,7 +154,7 @@ describe.skipIf(!support.supported)("sandbox that holds files from an abandoned } function worker(seeded: Seeded) { - const call = vi.fn(async (_pluginId: string, method: string) => { + const call = vi.fn(async (_pluginId: string, method: string, _params?: unknown) => { if (method === "environmentResumeLease") throw new JsonRpcCallError({ code: -32000, message: REFUSAL }); if (method === "environmentAcquireLease") { return { providerLeaseId: "replacement-sandbox", metadata: { provider: "fake-plugin", image: "fake:test", @@ -284,7 +285,11 @@ describe.skipIf(!support.supported)("sandbox that holds files from an abandoned 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 () => { + async function entries(action: string) { + return await db.select().from(activityLog).where(eq(activityLog.action, action)); + } + + it("removes the files only after the retention period, and says removed only after the provider confirms it", async () => { const seeded = await seed(); await abandon(seeded); const { call, runtime } = worker(seeded); @@ -294,16 +299,83 @@ describe.skipIf(!support.supported)("sandbox that holds files from an abandoned 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 entries("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." }); + const [released] = await entries("workspace.abandoned_files_released"); + expect(released).toMatchObject({ entityType: "issue", entityId: seeded.issueId, actorType: "system", actorId: "workspace-retention" }); + expect(released!.details).toMatchObject({ reason: "retention_expired", + summary: "Unsaved files from an interrupted run were kept for 8 days. They are scheduled for removal." }); + expect(await entries("workspace.abandoned_files_removed")).toEqual([]); + await sweep(runtime); expect(destroyCalls(call)).toHaveLength(1); expect(await leaseRow(seeded)).toMatchObject({ status: "expired" }); + const [removed] = await entries("workspace.abandoned_files_removed"); + expect(removed).toMatchObject({ entityType: "issue", entityId: seeded.issueId, actorType: "system" }); + expect(removed!.details).toMatchObject({ + summary: "Unsaved files from an interrupted run were kept for 8 days and have now been removed." }); + }); + + it("does not report removal when the provider delete fails", async () => { + const seeded = await seed(); + await abandon(seeded); + const { call, runtime } = worker(seeded); + await acquire(seeded, runtime); + vi.restoreAllMocks(); + await setReceipts(seeded, receipt => ({ ...receipt, retainUntil: new Date(Date.now() - 1_000).toISOString() })); + call.mockImplementation(async (_pluginId: string, method: string) => { + throw new Error(`provider refused ${method}`); + }); + await sweep(runtime); + expect(await entries("workspace.abandoned_files_released")).toHaveLength(1); + expect(await entries("workspace.abandoned_files_removed")).toEqual([]); + expect(await leaseRow(seeded)).toMatchObject({ status: "pending_cleanup" }); + }); + + it("says nothing on the task when another receipt still holds the sandbox", async () => { + const seeded = await seed(); + await abandon(seeded); + const { call, runtime } = worker(seeded); + await acquire(seeded, runtime); + vi.restoreAllMocks(); + const workspace = await readWorkspace(seeded); + const [first] = workspace.metadata!.remoteWorkspaceAbandonedEpochs as Array>; + await db.update(executionWorkspaces).set({ metadata: { ...workspace.metadata, remoteWorkspaceAbandonedEpochs: [ + { ...first, retainUntil: new Date(Date.now() - 1_000).toISOString() }, + { ...first, epoch: 7, location: { ...(first!.location as Record), remoteCwd: "/other-root" }, + retainUntil: new Date(Date.now() + 86_400_000).toISOString() }, + ] } }).where(eq(executionWorkspaces.id, seeded.executionWorkspaceId)); + await sweep(runtime); + expect(await entries("workspace.abandoned_files_released")).toEqual([]); + expect(destroyCalls(call)).toEqual([]); + expect(await leaseRow(seeded)).toMatchObject({ status: "retained" }); + }); + + it("wakes the cleanup worker at the receipt's retention end, also after a restart, and then goes quiet", async () => { + const seeded = await seed(); + await abandon(seeded); + const { call, runtime } = worker(seeded); + await acquire(seeded, runtime); + vi.restoreAllMocks(); + await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success" }) + .where(eq(environmentLeases.providerLeaseId, "replacement-sandbox")); + const [receipt] = (await readWorkspace(seeded)).metadata!.remoteWorkspaceAbandonedEpochs as Array>; + const retainUntil = Date.parse(receipt!.retainUntil as string); + + expect(await nextEnvironmentCleanupAt(db)).toBe(retainUntil); + const restarted = createDb(connectionString); + try { + expect(await nextEnvironmentCleanupAt(restarted)).toBe(retainUntil); + } finally { + await restarted.$client.end({ timeout: 1 }); + } + + await setReceipts(seeded, value => ({ ...value, retainUntil: new Date(Date.now() - 1_000).toISOString() })); + await sweep(runtime); + expect(destroyCalls(call)).toHaveLength(1); + expect(await entries("workspace.abandoned_files_removed")).toHaveLength(1); + expect(await nextEnvironmentCleanupAt(db)).toBeNull(); }); async function stoppedWarmOrphan(seeded: Seeded) { diff --git a/server/src/services/environment-cleanup-state.ts b/server/src/services/environment-cleanup-state.ts index a2c9e86dd7d..0298e25be34 100644 --- a/server/src/services/environment-cleanup-state.ts +++ b/server/src/services/environment-cleanup-state.ts @@ -1,6 +1,7 @@ import { and, eq, or, sql } from "drizzle-orm"; import { environmentLeases, sandboxCreationOperations, type Db } from "@paperclipai/db"; import { hasDeferredEnvironmentCleanup } from "./environment-cleanup-notifications.js"; +import { nextAbandonedWorkspaceFileHoldExpiryAt } from "./remote-workspace-abandoned-files-hold.js"; export const ENVIRONMENT_CLEANUP_RETRY_MS = 5 * 60_000; @@ -86,7 +87,8 @@ export async function nextEnvironmentCleanupAt(db: Db, backoffMs = ENVIRONMENT_C ${pendingCleanupDeadlineSql()}) end)` }).from(environmentLeases).where(eq(environmentLeases.status, "pending_cleanup")); const [creation] = await db.select({ next: sql`min(extract(epoch from ${sandboxCreationOperations.nextAttemptAt}) * 1000)` }) .from(sandboxCreationOperations).where(recoverableSandboxCreationCondition()); - const deadlines = [row?.next, creation?.next].filter((value): value is string => value != null).map(Number); + const expiry = await nextAbandonedWorkspaceFileHoldExpiryAt(db); + const deadlines = [row?.next, creation?.next, expiry].filter((value): value is string | number => value != null).map(Number); const saved = deadlines.length ? Math.min(...deadlines) : null; const buffered = hasDeferredEnvironmentCleanup(db) ? Date.now() + backoffMs : null; return saved === null ? buffered : buffered === null ? saved : Math.min(saved, buffered); diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 402192f82e8..613e6d30a76 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -31,7 +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 { expireAbandonedWorkspaceFileHoldsWhenDue, parkAbandonedWorkspaceFilesLease, recordAbandonedWorkspaceFilesRemoved } from "../remote-workspace-abandoned-files-hold.js"; import { CHAT_COMPLETION_WAKE_REASON } from "../chat-completion-delivery.js"; import { hasStopOnlyCleanup, @@ -1886,7 +1886,10 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD failureReason: "pending_cleanup_retry", remoteExecutionTermination: remoteTerminationReceipt(lease, receipt), }); - if (released) destroyed += 1; + if (released) { + destroyed += 1; + await recordAbandonedWorkspaceFilesRemoved(db, row); + } } else if (environment) { const result = await environmentRuntime.destroyRunLease({ environment, @@ -1895,6 +1898,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD }); if (result && result.status !== "pending_cleanup") { destroyed += 1; + if (result.cleanupStatus === "success") await recordAbandonedWorkspaceFilesRemoved(db, row); } } } catch (error) { diff --git a/server/src/services/remote-workspace-abandoned-files-hold.ts b/server/src/services/remote-workspace-abandoned-files-hold.ts index 629aeed4b85..6f65507220e 100644 --- a/server/src/services/remote-workspace-abandoned-files-hold.ts +++ b/server/src/services/remote-workspace-abandoned-files-hold.ts @@ -11,6 +11,11 @@ export { ABANDONED_WORKSPACE_FILES_RETENTION_DAYS, ABANDONED_WORKSPACE_FILES_RET 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 const ABANDONED_WORKSPACE_FILES_RELEASE_KEY = "abandonedWorkspaceFilesRelease"; + +function days(count: number) { + return `${count} ${count === 1 ? "day" : "days"}`; +} export type AbandonedWorkspaceFilesReleaseReason = "recovered" | "discarded" | "retention_expired"; @@ -90,26 +95,32 @@ export async function releaseAbandonedWorkspaceFiles(db: Db, input: { 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 runId = typeof target.runId === "string" ? target.runId : undefined; + const [run] = runId ? await tx.select({ issueId: heartbeatRuns.issueId }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, runId))) : []; + const issueId = workspace.sourceIssueId ?? run?.issueId ?? null; + const keptDays = Math.max(1, Math.round((now.getTime() - Date.parse(String(target.abandonedAt ?? now.toISOString()))) / 86_400_000)); + const marker = { issueId, workspaceId: workspace.id, abandonedEpoch: input.epoch, reason: input.reason, keptDays, runId: runId ?? null }; 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}`, + metadata: sql`(${environmentLeases.metadata} - ${ABANDONED_WORKSPACE_FILES_PARKED_KEY}) + || ${JSON.stringify({ [ABANDONED_WORKSPACE_FILES_RELEASE_KEY]: marker })}::jsonb`, }).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 scheduled = unparked.length > 0; 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.` + ? scheduled ? `Unsaved files from an interrupted run were kept for ${days(keptDays)}. They are scheduled for removal.` : null : input.reason === "discarded" - ? "Unsaved files from an interrupted run were discarded and will be removed." + ? `Unsaved files from an interrupted run were discarded.${scheduled ? " They are scheduled for removal." : ""}` : "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, + logger.info({ companyId: input.companyId, workspaceId: workspace.id, abandonedEpoch: input.epoch, reason: input.reason, + actorType: input.actorType, actorId: input.actorId, leasesHandedToCleanup: unparked.length }, "abandoned workspace files released"); + if (summary) 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, + entityId: issueId ?? workspace.id, runId, details: { summary, reason: input.reason, workspaceId: workspace.id, abandonedEpoch: input.epoch, retainUntil: new Date(receiptRetainUntil(target)).toISOString(), leasesHandedToCleanup: unparked.length } }); return true; @@ -147,12 +158,42 @@ export async function expireAbandonedWorkspaceFileHolds(db: Db, now = new Date() return { expired }; } -const ABANDONED_WORKSPACE_FILES_EXPIRY_INTERVAL_MS = 60 * 60 * 1000; -const lastExpiryPass = new WeakMap(); +function receiptExpirySql() { + return sql`coalesce(case when receipt->>'retainUntil' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T' then (receipt->>'retainUntil')::timestamptz end, + case when receipt->>'abandonedAt' ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T' + then (receipt->>'abandonedAt')::timestamptz + ${`${ABANDONED_WORKSPACE_FILES_RETENTION_DAYS} days`}::interval end, + 'epoch'::timestamptz)`; +} + +export async function nextAbandonedWorkspaceFileHoldExpiryAt(db: Pick): Promise { + const [row] = await db.execute<{ next: string | Date | null }>(sql`select min(${receiptExpirySql()}) as next + from execution_workspaces workspace + cross join lateral jsonb_array_elements(case when jsonb_typeof(workspace.metadata->'remoteWorkspaceAbandonedEpochs') = 'array' + then workspace.metadata->'remoteWorkspaceAbandonedEpochs' else '[]'::jsonb end) receipt + where workspace.metadata ? 'remoteWorkspaceAbandonedEpochs' + and receipt->>'schema' = ${REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA} + and jsonb_typeof(receipt->'location'->'providerLeaseId') = 'string' + and coalesce(jsonb_typeof(receipt->'released'), 'null') = 'null'`); + return row?.next ? new Date(row.next).getTime() : null; +} 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()); + const next = await nextAbandonedWorkspaceFileHoldExpiryAt(db); + if (next === null || next > now.getTime()) return { expired: 0 }; return await expireAbandonedWorkspaceFileHolds(db, now); } + +export async function recordAbandonedWorkspaceFilesRemoved(db: Db, lease: Pick): Promise { + const marker = lease.metadata?.[ABANDONED_WORKSPACE_FILES_RELEASE_KEY] as { + issueId?: string | null; workspaceId?: string; abandonedEpoch?: number; reason?: string; keptDays?: number; runId?: string | null; + } | undefined; + if (!marker || (marker.reason !== "retention_expired" && marker.reason !== "discarded")) return; + const summary = marker.reason === "retention_expired" + ? `Unsaved files from an interrupted run were kept for ${days(marker.keptDays ?? ABANDONED_WORKSPACE_FILES_RETENTION_DAYS)} and have now been removed.` + : "Discarded unsaved files from an interrupted run have now been removed."; + await logActivity(db, { companyId: lease.companyId, actorType: "system", actorId: "workspace-retention", + action: "workspace.abandoned_files_removed", entityType: marker.issueId ? "issue" : "execution_workspace", + entityId: marker.issueId ?? marker.workspaceId ?? lease.id, runId: marker.runId ?? undefined, + details: { summary, reason: marker.reason, workspaceId: marker.workspaceId, abandonedEpoch: marker.abandonedEpoch, leaseId: lease.id } }); +}