diff --git a/doc/task-recovery.md b/doc/task-recovery.md index 55cebac9f1b..b416d03fd35 100644 --- a/doc/task-recovery.md +++ b/doc/task-recovery.md @@ -233,6 +233,16 @@ a new background obligation. An uncertain acknowledgement never proves that files were saved. This adds no provider turn, recovery generation or retry budget, and the normal save and stop receipts still govern continuation. +A restore of the last save can also find a full disk. When the sandbox was +resumed from an earlier run, its own files are the cause, not the saved +workspace. The run's lease then drops its reuse scope and records +`reusableSandboxLeaseSuperseded` with reason `sandbox_disk_full`. The restore +is retried within the normal bootstrap budget. That retry's acquisition treats +the full sandbox as obsolete and cleans it up through the obsolete-lease path, +which keeps its export and parked-file protections. Then it restores on a new +sandbox. A sandbox created for the run has nothing from an earlier run, and a +new one has the same disk, so a full disk there still goes to the board. + Known publication receipts and exact API mutation receipts carry forward. Uncertain API mutations and upstream tool mutations remain fenced across run replacement. Reads and independent work remain available. Generic upstream diff --git a/server/src/__tests__/environment-runtime.test.ts b/server/src/__tests__/environment-runtime.test.ts index 394c1d0f48d..7f257fb5500 100644 --- a/server/src/__tests__/environment-runtime.test.ts +++ b/server/src/__tests__/environment-runtime.test.ts @@ -75,6 +75,7 @@ import { claimNativeRestartRecoveries } from "../services/native-runtime/native- import { NATIVE_PREPARATION_FENCING_VERSION } from "../services/native-runtime/native-active-runs.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { retireFullReusableSandbox } from "../services/full-reusable-sandbox.js"; const externalTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_ENVIRONMENT_RUNTIME_TEST_DATABASE_URL"); const embeddedPostgresSupport = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -4972,7 +4973,7 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { }); }); - it.each(["provider config", "workspace migration"])("does not resume released reusable plugin sandbox leases after %s drift", async drift => { + it.each(["provider config", "workspace migration", "full sandbox disk"])("does not resume released reusable plugin sandbox leases after %s drift", async drift => { const pluginId = randomUUID(); const { companyId, agentId, environment: baseEnvironment, runId } = await seedEnvironment(); const providerConfig = { @@ -5062,6 +5063,13 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { fingerprint: expect.stringMatching(/^v1:sha256:[a-f0-9]{64}$/), }), }); + if (drift === "full sandbox disk") { + // A restore found this reused sandbox full of an earlier run's files. + await db.insert(environmentLeases).values({ id: randomUUID(), companyId, environmentId: environment.id, + heartbeatRunId: runId, provider: first.lease.provider, providerLeaseId: first.lease.providerLeaseId, + leasePolicy: "reuse_by_environment", status: "expired" }); + await expect(retireFullReusableSandbox(db, first.lease, runId)).resolves.toBe(true); + } await runtimeWithPlugin.releaseRunLeases(runId); if (drift === "workspace migration") { @@ -5104,7 +5112,8 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { }); expect(second.lease.providerLeaseId).toBe(`lease-${updatedEnvironment.config.image}-replacement`); - expect(second.lease.metadata?.reusableSandboxLease).not.toEqual(first.lease.metadata?.reusableSandboxLease); + // The full sandbox's scope is unchanged; it is the sandbox that left reuse. + if (drift !== "full sandbox disk") expect(second.lease.metadata?.reusableSandboxLease).not.toEqual(first.lease.metadata?.reusableSandboxLease); expect(workerManager.call).not.toHaveBeenCalledWith( pluginId, "environmentResumeLease", diff --git a/server/src/services/environment-lease-handoff.ts b/server/src/services/environment-lease-handoff.ts index 37b2ed148c4..c9ceec3683f 100644 --- a/server/src/services/environment-lease-handoff.ts +++ b/server/src/services/environment-lease-handoff.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; -import type { environmentLeases } from "@paperclipai/db"; +import { and, eq, sql } from "drizzle-orm"; +import { environmentLeases, type Db } from "@paperclipai/db"; type Lease = typeof environmentLeases.$inferSelect; type Binding = Pick { + if (lease.leasePolicy !== "reuse_by_environment" || !lease.heartbeatRunId) return false; + const { reusableSandboxLease: scope, ...metadata } = lease.metadata ?? {}; + const [claimed] = await db.update(environmentLeases).set({ + metadata: { ...metadata, [SUPERSEDED_REUSABLE_SANDBOX_KEY]: { + schema: SUPERSEDED_REUSABLE_SANDBOX_SCHEMA, reason: input.reason, + supersededByRunId: input.supersededByRunId, supersededByProviderLeaseId: input.supersededByProviderLeaseId ?? null, + ...(input.manifestSha256 ? { manifestSha256: input.manifestSha256 } : {}), + reusableSandboxLease: scope ?? null, supersededAt: new Date().toISOString(), + } }, + updatedAt: new Date(), + }).where(and( + eq(environmentLeases.companyId, lease.companyId), eq(environmentLeases.id, lease.id), + eq(environmentLeases.status, lease.status), eq(environmentLeases.leasePolicy, "reuse_by_environment"), + eq(environmentLeases.heartbeatRunId, lease.heartbeatRunId), + sql`${environmentLeases.metadata} = ${JSON.stringify(lease.metadata)}::jsonb`, + )).returning({ id: environmentLeases.id }); + return Boolean(claimed); +} diff --git a/server/src/services/environments.ts b/server/src/services/environments.ts index f586d31d887..c96461c37d5 100644 --- a/server/src/services/environments.ts +++ b/server/src/services/environments.ts @@ -1,4 +1,4 @@ -import { createReusableLeaseHandoff, preserveReusableLeaseHandoff, withoutReusableLeaseHandoff } from "./environment-lease-handoff.js"; +import { createReusableLeaseHandoff, preserveReusableLeaseHandoff, SUPERSEDED_REUSABLE_SANDBOX_KEY, withoutReusableLeaseHandoff } from "./environment-lease-handoff.js"; import { promoteDeferredWorkIntents } from "./work-intent-outbox.js"; import { clearRemoteWorkspaceLocationForReleasedLease } from "./remote-workspace-snapshot-retention.js"; import { notifyNativeEnvironmentSettlement } from "./native-environment-settlement-notifications.js"; @@ -1633,7 +1633,7 @@ export function environmentService(db: Db) { // A source whose harness backup was restored into another // lease holds older session state. That claim and this // handoff compete on this row, so only one of them wins. - sql`not (coalesce(${environmentLeases.metadata}, '{}'::jsonb) ? 'reusableSandboxLeaseSuperseded')`, + sql`not (coalesce(${environmentLeases.metadata}, '{}'::jsonb) ? ${SUPERSEDED_REUSABLE_SANDBOX_KEY})`, sql`not (coalesce(${environmentLeases.metadata}, '{}'::jsonb) ? 'portableTaskSuccessor')`, ), ) diff --git a/server/src/services/full-reusable-sandbox.ts b/server/src/services/full-reusable-sandbox.ts new file mode 100644 index 00000000000..5355bfa4763 --- /dev/null +++ b/server/src/services/full-reusable-sandbox.ts @@ -0,0 +1,36 @@ +import { and, eq, ne, sql } from "drizzle-orm"; +import { environmentLeases, type Db } from "@paperclipai/db"; +import type { EnvironmentLease } from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; +import { supersedeReusableSandboxLease } from "./environment-lease-handoff.js"; + +/** + * Takes a reused sandbox whose disk is full out of reuse for this workspace. + * + * An earlier run on the same sandbox can leave it full (its own files, a save + * that could not finish). Every later run that resumes it fails the same way, + * so the task never recovers. A sandbox made for this run has nothing of an + * earlier run; a new one has the same disk, so this returns false for it and + * the refusal stays with the board. + * + * It never throws: a failed write keeps the restore's own refusal. + */ +export async function retireFullReusableSandbox(db: Db, lease: EnvironmentLease, runId: string): Promise { + if (lease.leasePolicy !== "reuse_by_environment" || !lease.providerLeaseId || lease.heartbeatRunId !== runId) return false; + try { + const [earlier] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( + eq(environmentLeases.companyId, lease.companyId), + eq(environmentLeases.providerLeaseId, lease.providerLeaseId), + ne(environmentLeases.id, lease.id), + sql`${environmentLeases.provider} is not distinct from ${lease.provider ?? null}`, + )).limit(1); + if (!earlier) return false; + const [current] = await db.select().from(environmentLeases) + .where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, lease.companyId))); + if (!current || current.status !== "active" || current.heartbeatRunId !== runId || !current.metadata?.reusableSandboxLease) return false; + return await supersedeReusableSandboxLease(db, current, { reason: "sandbox_disk_full", supersededByRunId: runId }); + } catch (error) { + logger.warn({ err: error, runId, leaseId: lease.id }, "Could not take a full reused sandbox out of reuse; the restore refusal stands"); + return false; + } +} diff --git a/server/src/services/native-runtime/native-retired-backup-source.ts b/server/src/services/native-runtime/native-retired-backup-source.ts index 1997a013d0a..2c53c704283 100644 --- a/server/src/services/native-runtime/native-retired-backup-source.ts +++ b/server/src/services/native-runtime/native-retired-backup-source.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { and, eq, gt, inArray, ne, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; -import { retiredReusableLeasePredecessors } from "../environment-lease-handoff.js"; +import { retiredReusableLeasePredecessors, supersedeReusableSandboxLease } from "../environment-lease-handoff.js"; import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js"; import { hasConfirmedSandboxStopAndRetain } from "../sandbox-stop-and-retain.js"; import { LEGACY_WORKSPACE_RECOVERY_KEY, LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "../workspace-restore-recovery-state.js"; @@ -94,35 +94,21 @@ export async function retiredSourceAuthorizesNativeBackupRestore(db: Db, input: return !idleSource || await supersedeIdleWarmSource(db, lease, input); } -export const SUPERSEDED_REUSABLE_SANDBOX_KEY = "reusableSandboxLeaseSuperseded"; +export { SUPERSEDED_REUSABLE_SANDBOX_KEY } from "../environment-lease-handoff.js"; /** * Claims an idle warm source before its backup is restored elsewhere. The * source still holds the checkpointed session, and the restored lease will - * move past it, so the source must never be resumed again. Removing its reuse - * scope makes the next acquisition for this workspace treat it as obsolete and - * clean it up through the existing obsolete-lease path. The write is a - * compare-and-swap on the checked row: a run that resumed or changed the lease - * in the meantime wins, and the restore does not happen. + * move past it, so the source must never be resumed again. A run that resumed + * or changed the lease in the meantime wins, and the restore does not happen. */ async function supersedeIdleWarmSource(db: Db, lease: typeof environmentLeases.$inferSelect, input: { companyId: string; currentRunId: string; manifestSha256: string; targetProviderLeaseId?: string | null; }) { - const { reusableSandboxLease: scope, ...metadata } = lease.metadata ?? {}; - const [claimed] = await db.update(environmentLeases).set({ - metadata: { ...metadata, [SUPERSEDED_REUSABLE_SANDBOX_KEY]: { - schema: "paperclip.reusable-sandbox-lease-superseded.v1", reason: "harness_backup_restored_elsewhere", - supersededByRunId: input.currentRunId, supersededByProviderLeaseId: input.targetProviderLeaseId ?? null, - manifestSha256: input.manifestSha256, reusableSandboxLease: scope ?? null, supersededAt: new Date().toISOString(), - } }, - updatedAt: new Date(), - }).where(and( - eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, lease.id), - eq(environmentLeases.status, lease.status), eq(environmentLeases.leasePolicy, "reuse_by_environment"), - eq(environmentLeases.heartbeatRunId, lease.heartbeatRunId!), - sql`${environmentLeases.metadata} = ${JSON.stringify(lease.metadata)}::jsonb`, - )).returning({ id: environmentLeases.id }); - return Boolean(claimed); + if (lease.companyId !== input.companyId) return false; + return supersedeReusableSandboxLease(db, lease, { reason: "harness_backup_restored_elsewhere", + supersededByRunId: input.currentRunId, supersededByProviderLeaseId: input.targetProviderLeaseId ?? null, + manifestSha256: input.manifestSha256 }); } const TERMINAL_SOURCE_RUN_STATUSES = new Set(["succeeded", "failed", "cancelled", "timed_out", "interrupted"]); diff --git a/server/src/services/remote-workspace-restore-disk-full.test.ts b/server/src/services/remote-workspace-restore-disk-full.test.ts new file mode 100644 index 00000000000..fb4bad61f06 --- /dev/null +++ b/server/src/services/remote-workspace-restore-disk-full.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import type { Db } from "@paperclipai/db"; +import type { EnvironmentLease } from "@paperclipai/shared"; +import { isRemoteWorkspaceRestoreDiskFull, RemoteWorkspaceOperationError } from "./remote-workspace-transport.js"; +import { retireFullReusableSandbox } from "./full-reusable-sandbox.js"; + +describe("restore disk-full refusal", () => { + it.each(["helper", "upload", "extract"])("names a full sandbox disk at the %s stage", stage => { + const operation = stage === "extract" ? "restore exit=1" : stage === "helper" ? "archive_helper" : "upload"; + expect(isRemoteWorkspaceRestoreDiskFull(new RemoteWorkspaceOperationError( + `remote_workspace_operation_failed: operation=${operation}; remote_workspace_restore_failed: stage=${stage} reason=sandbox_disk_full`))).toBe(true); + }); + + it("still names it when the transport adds structured fields around the reason", () => { + expect(isRemoteWorkspaceRestoreDiskFull(new Error( + "remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=extract code=ENOSPC reason=sandbox_disk_full exit=1"))).toBe(true); + }); + + it.each([ + "remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=inspect_root reason=occupied_root", + "remote_workspace_operation_failed: operation=prepare exit=1; remote_workspace_prepare_failed: stage=clone reason=sandbox_disk_full", + "remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=extract reason=sandbox_disk_full_unknown", + ])("does not name another refusal (%s)", message => { + expect(isRemoteWorkspaceRestoreDiskFull(new Error(message))).toBe(false); + }); + + it("keeps the restore refusal when the lease write fails", async () => { + const db = { select: () => { throw new Error("connection terminated"); } } as unknown as Db; + const lease = { id: "lease", companyId: "company", leasePolicy: "reuse_by_environment", providerLeaseId: "sandbox", + heartbeatRunId: "run", provider: "daytona", metadata: {} } as unknown as EnvironmentLease; + await expect(retireFullReusableSandbox(db, lease, "run")).resolves.toBe(false); + }); +}); diff --git a/server/src/services/remote-workspace-transport.ts b/server/src/services/remote-workspace-transport.ts index 66dfc3f9d14..38fd1e84992 100644 --- a/server/src/services/remote-workspace-transport.ts +++ b/server/src/services/remote-workspace-transport.ts @@ -189,6 +189,14 @@ function remoteWorkspaceRestoreFailureDetail(step: RemoteWorkspaceRestoreStep, c return `${step === "snapshot_download" ? "storage" : "transport"}=${label}${code ? ` code=${code}` : ""}${status ? ` status=${status}` : ""}`; } +// A restore stage that reports a full sandbox disk, in the grammar of SANDBOX_SETUP_CAUSE. +const RESTORE_DISK_FULL = /(?:^|; )remote_workspace_restore_failed: stage=[a-z_]{1,32}(?: [a-z_]+=[A-Za-z0-9_]{1,64}){0,16}? reason=sandbox_disk_full(?: |$)/; + +/** A sandbox restore refused because the sandbox disk is full, at any restore stage. */ +export function isRemoteWorkspaceRestoreDiskFull(error: unknown): boolean { + return error instanceof Error && RESTORE_DISK_FULL.test(error.message); +} + /** The restore failure carried by a setup error, through at most four causes. */ export function findRemoteWorkspaceRestoreError(error: unknown): RemoteWorkspaceRestoreError | null { for (let cause = error, depth = 0; cause && depth < 4; cause = (cause as { cause?: unknown }).cause, depth++) { diff --git a/server/src/services/remote-workspaces.integration.test.ts b/server/src/services/remote-workspaces.integration.test.ts index 41ef78e92f3..c3040a41830 100644 --- a/server/src/services/remote-workspaces.integration.test.ts +++ b/server/src/services/remote-workspaces.integration.test.ts @@ -407,7 +407,7 @@ suite("remote workspace lifecycle with real Postgres and independent filesystem } }, 60_000); - it.each(["same root", "different root", "destroyed allocation", "occupied root", "missing object", "stalled download", "transient restore", "full sandbox disk", "restore lock busy"] as const)( + it.each(["same root", "different root", "destroyed allocation", "occupied root", "missing object", "stalled download", "transient restore", "full sandbox disk", "full reused sandbox disk", "restore lock busy"] as const)( "preserves the published workspace path and files on a cold restore (%s)", async mode => { const reserved = await reserve({ kind: "empty" }), first = await target("sandbox-A"); const prepared = await prepareRemoteWorkspace({ db, storage, workspace: reserved, runId: ids.run, lease: await lease(), target: first }); @@ -464,10 +464,23 @@ suite("remote workspace lifecycle with real Postgres and independent filesystem expect(await fs.lstat(expectedRemoteRoot).catch(() => null)).toBeNull(); vi.mocked(second.runner!.execute).mockRestore(); } - if (mode === "full sandbox disk") { + if (mode === "full reused sandbox disk") { + // Staging 2026-11-24: an earlier run filled this reusable sandbox, and the + // next runs resumed it and failed the same way until the task was blocked. + await db.insert(environmentLeases).values({ id: randomUUID(), companyId: ids.company, environmentId: ids.environment, + heartbeatRunId: ids.run, issueId: ids.issue, provider: "daytona", providerLeaseId: newLease.providerLeaseId, + leasePolicy: "reuse_by_environment", status: "expired" }); + await db.update(environmentLeases).set({ leasePolicy: "reuse_by_environment", + metadata: { ...newLease.metadata, agentId: ids.agent, reusableSandboxLease: { companyId: ids.company, environmentId: ids.environment } } }) + .where(eq(environmentLeases.id, nextLease)); + Object.assign(newLease, (await db.select().from(environmentLeases).where(eq(environmentLeases.id, nextLease)))[0]!); + } + if (mode === "full sandbox disk" || mode === "full reused sandbox disk") { // The sandbox cannot hold even one copy: every restored file write fails - // with ENOSPC. That repeats on every automatic retry, so it is named and - // goes to the board, whose Retry works once the sandbox has space. + // with ENOSPC. A new sandbox has the same disk, so on a sandbox made for + // this run that is named and goes to the board. A reused sandbox may be + // full of an earlier run's files: it leaves reuse, and the bounded retry + // restores on a new sandbox. const preload = path.join(root, "full-disk.cjs"); await fs.writeFile(preload, `const fs=require('node:fs'),open=fs.promises.open; fs.promises.open=async(...args)=>{const handle=await open.apply(fs.promises,args); @@ -479,10 +492,39 @@ require('node:module').syncBuiltinESMExports();`); ? { ...command, env: { ...command.env, NODE_OPTIONS: `--require ${preload}` } } : command)); const full = await prepareRemoteWorkspace({ db, storage, workspace: reservedAgain, runId: nextRun, lease: newLease, target: second }) .then(() => null, (error: unknown) => error as RemoteWorkspaceRestoreError); - expect(full).toMatchObject({ step: "sandbox_restore", retryable: false, message: "remote_workspace_restore_failed: step=sandbox_restore; " + const reused = mode === "full reused sandbox disk"; + expect(full).toMatchObject({ step: "sandbox_restore", retryable: reused, message: "remote_workspace_restore_failed: step=sandbox_restore; " + "remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=extract reason=sandbox_disk_full" }); + const [after] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, nextLease)); + if (reused) { + expect(after!.metadata).not.toHaveProperty("reusableSandboxLease"); + expect(after!.metadata?.reusableSandboxLeaseSuperseded).toMatchObject({ reason: "sandbox_disk_full", supersededByRunId: nextRun, + reusableSandboxLease: { companyId: ids.company, environmentId: ids.environment } }); + } else expect(after!.metadata).toEqual(newLease.metadata); expect(await fs.lstat(expectedRemoteRoot).catch(() => null)).toBeNull(); vi.mocked(second.runner!.execute).mockRestore(); + if (reused) { + // The bounded retry is a new run on a new sandbox. The full sandbox + // stays as it was, and the retry restores the saved files. + await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, nextRun)); + const [ended] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, nextLease)); + await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success", metadata: { ...ended!.metadata, + remoteExecutionTermination: remoteTerminationReceipt(ended as EnvironmentLease, { providerLeaseId: ended!.providerLeaseId, state: "stopped" }) } }) + .where(eq(environmentLeases.id, nextLease)); + const retryRun = randomUUID(), retryLease = randomUUID(); + await db.insert(heartbeatRuns).values({ id: retryRun, companyId: ids.company, agentId: ids.agent, nativeIssueId: ids.issue, runtimeMode: "native", status: "running" }); + const [fresh] = await db.insert(environmentLeases).values({ id: retryLease, companyId: ids.company, environmentId: ids.environment, + heartbeatRunId: retryRun, issueId: ids.issue, provider: "daytona", providerLeaseId: `allocation-${retryLease}`, + leasePolicy: "reuse_by_environment", status: "active" }).returning(); + const retryWorkspace = await reserveRemoteWorkspace({ db, storage, companyId: ids.company, issueId: ids.issue, runId: retryRun, + agentId: ids.agent, environmentId: ids.environment, projectId: null, projectWorkspaceId: null, existingWorkspaceId: reserved.id, source: { kind: "empty" } }); + const newSandbox = await target("sandbox-C"); + const retried = await prepareRemoteWorkspace({ db, storage, workspace: retryWorkspace, runId: retryRun, lease: fresh as EnvironmentLease, target: newSandbox }); + expect(retried.remoteRoot.startsWith(newSandbox.remoteCwd)).toBe(true); + expect(await fs.readFile(path.join(retried.remoteRoot, "report.md"), "utf8")).toBe("useful saved result\n"); + expect(await fs.readFile(path.join(retried.remoteRoot, "binary.bin"))).toEqual(Buffer.from([0, 1, 255])); + return; + } } if (mode === "restore lock busy") { const lockDirectory = path.join(path.dirname(expectedRemoteRoot), ".paperclip-runtime", "workspace-restore-locks"); diff --git a/server/src/services/remote-workspaces.ts b/server/src/services/remote-workspaces.ts index 0c39bcc599f..a0477054e61 100644 --- a/server/src/services/remote-workspaces.ts +++ b/server/src/services/remote-workspaces.ts @@ -10,6 +10,7 @@ import path from "node:path"; import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"; import { crashPoint } from "@paperclipai/shared/crash-points"; import { sandboxDiskFullFaultTarget } from "./sandbox-disk-full-fault.js"; +import { retireFullReusableSandbox } from "./full-reusable-sandbox.js"; import { companies, environmentLeases, executionWorkspaces, executionWorkspaceSnapshots, heartbeatRuns, issues, workspaceOperations, type Db, } from "@paperclipai/db"; @@ -32,7 +33,7 @@ import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./r import { captureRemoteWorkspaceArchive, cleanupRemoteWorkspaceArchive, prepareRemoteWorkspaceDirectory, prepareRemoteRepository, remoteWorkspaceRepositoryPath, RemoteWorkspaceOperationTimeoutError, RemoteWorkspacePreparationTimeoutError, remoteWorkspaceFailureCause, hasRemoteRecoveryAttachment, - requireRemoteWorkspaceTarget, restoreRemoteWorkspaceDirectory, RemoteWorkspaceRestoreError, type RemoteWorkspaceRestoreStep, + requireRemoteWorkspaceTarget, restoreRemoteWorkspaceDirectory, RemoteWorkspaceRestoreError, isRemoteWorkspaceRestoreDiskFull, type RemoteWorkspaceRestoreStep, type RemoteWorkspaceSavePhaseTiming, syncRemoteWorkspaceRecoveryDirectory, } from "./remote-workspace-transport.js"; import { @@ -493,8 +494,11 @@ export async function prepareRemoteWorkspace(input: { // saved version; a failed restore never publishes over existing files. // A sandbox refusal that names its reason (an occupied folder, a changed // owner, a rejected archive) repeats on retry, so it goes to the board. + // A full disk on a reused sandbox leaves reuse, so the retry gets a new sandbox. let retryable = false; - const refused = error instanceof Error && / (?:reason|archive)=[a-z_]+/.test(error.message) + const movedOffFullSandbox = step === "sandbox_restore" && isRemoteWorkspaceRestoreDiskFull(error) + && await retireFullReusableSandbox(input.db, input.lease, input.runId); + const refused = error instanceof Error && / (?:reason|archive)=[a-z_]+/.test(error.message) && !movedOffFullSandbox && !(step === "sandbox_restore" && /; remote_workspace_restore_failed: stage=restore_lock reason=restore_lock_busy$/.test(error.message)); if (step !== "snapshot_lookup" && !refused) { const [latest] = await input.db.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces)