From d63325ee3d349c65599c300c54e0f095b1176ecb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:26:49 -0600 Subject: [PATCH] fix(workspaces): restore on a new sandbox when a resumed sandbox disk is full (#22837) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A task on a reusable cloud sandbox resumes the same sandbox on its next run, and the run restores the last saved workspace there before the agent starts > - On staging, one run filled its sandbox disk. Its save failed, and the task correctly continued from the last save > - The next two runs resumed the same full sandbox. Each restore failed with a full disk, and Paperclip treated that as a permanent refusal, so the task went to Blocked with no automatic retry > - The full disk belonged to the sandbox, not to the saved workspace. A new sandbox would have restored the save > - This pull request takes a reused sandbox out of reuse when a restore finds its disk full, and lets the bounded setup retry restore on a new sandbox > - The benefit is that the task recovers by itself, and nobody has to free space in a sandbox or press Retry ## Linked Issues or Issue Description **What happened?** On hosted staging (2026-11-24), a Paperclip Runner task went to Blocked after a full sandbox disk: - 21:53Z: the run's agent filled a new Daytona sandbox during a 6-minute turn. The final workspace save failed with `native_workspace_sync_out_retry_exhausted` ("Saving the workspace stopped because the sandbox disk is full"). Its finalization sibling ended with `execution_reconciliation_required`. - 22:17Z and 22:26Z: two runs failed during setup with `remote_workspace_restore_failed` (step `sandbox_restore`, operation `upload`, reason `sandbox_disk_full`). Both recorded `remoteWorkspaceRestore.retryable: false`, so no retry was scheduled and a recovery action went to the board. Forensics from `/api/heartbeat-runs/:id/events` and the environment leases: all three runs used the same provider sandbox (three lease rows, one `providerLeaseId`, policy `reuse_by_environment`). The two restores resumed the sandbox that the first run had filled. **Expected behavior** A restore that fails only because a resumed sandbox is full continues on a new sandbox automatically. **Steps to reproduce** 1. Run a task on a reusable sandbox environment until the sandbox disk is full and the save fails. 2. Wake the task again. Lease selection resumes the same sandbox. 3. The restore upload fails with ENOSPC. The run fails with `retryable: false`, and every later wake picks the same sandbox again. **Paperclip version or commit** Staging Core on `f7fd3f43fe` (current `master` has the same code path). **Deployment mode** Hosted staging (cloud), Daytona sandbox provider plugin, reusable leases on. **Agent adapter(s) involved** `paperclip_runner` (setup runs before dispatch in legacy mode). **Root cause** `prepareRemoteWorkspace` in `server/src/services/remote-workspaces.ts` treats every restore failure that names a `reason=` as a permanent refusal. For `reason=sandbox_disk_full` on a resumed sandbox, the reason belongs to the sandbox. Lease selection kept choosing that sandbox, so every attempt failed the same way. Refs #22835 (the earlier stale snapshot qualification failure on the same agent, a different cause). ## What Changed - Add `server/src/services/full-reusable-sandbox.ts`: - `isRestoreSandboxDiskFullRefusal` matches a restore refusal with `reason=sandbox_disk_full` at any stage. - `retireFullReusableSandbox` applies only to this run's own active `reuse_by_environment` lease whose sandbox has an earlier lease row, so it was resumed. It removes the `reusableSandboxLease` scope and records `reusableSandboxLeaseSuperseded` (reason `sandbox_disk_full`) with one compare-and-swap. This is the same pattern that `native-retired-backup-source.ts` uses. - `remote-workspaces.ts`: when the sandbox leaves reuse, the restore failure is no longer a refusal. It is retryable only when the existing re-check of writer, epoch, clean state and saved version passes. `run-completion.ts` then schedules the existing bounded retry. - The retry's acquisition sees the full sandbox as obsolete. The existing obsolete-lease cleanup destroys it and keeps every protection (pending export, parked abandoned files). Then it creates a new sandbox. - A full disk on a sandbox created for the run keeps the current behavior. A new sandbox has the same disk. - `doc/task-recovery.md`: document the rule. ## Verification - Red on `master`: the new `full reused sandbox disk` case in `server/src/services/remote-workspaces.integration.test.ts` failed with `retryable: false`, the same result as on staging. - Green with the fix: the restore is retryable, the lease loses its reuse scope and gets the marker, and the final restore succeeds. The existing `full sandbox disk` case (a sandbox created for the run) still returns `retryable: false` and does not change the lease. - New `full sandbox disk` case in `server/src/__tests__/environment-runtime.test.ts`: after the sandbox leaves reuse, the next acquisition makes no resume call, destroys the full sandbox (`lease_fingerprint_mismatch`, `expired`), and creates a new sandbox. - `pnpm exec vitest run src/services/remote-workspaces.integration.test.ts src/__tests__/environment-runtime.test.ts src/services/native-runtime/native-retired-backup-source.integration.test.ts`: 3 files, 370 tests pass - `tsc -p server/tsconfig.json --noEmit`: passes - Review round: the disk-full check moved into `remote-workspace-transport.ts` with unit cases for the helper, upload and extract stages. One shared `supersedeReusableSandboxLease` writes the marker for both callers. A failed lease write keeps the restore refusal. The integration case now also restores on a new sandbox in a retry run. 378 tests pass across the four affected files, and `tsc` passes. - After deploy: confirm on staging that a disk-full restore on a resumed sandbox retries on a new sandbox, and that the affected task leaves Blocked. ## Risks - A run that hits this path spends one failed setup attempt (about 15 seconds) before the retry gets a new sandbox. - The full sandbox is destroyed through the existing obsolete-lease cleanup. That path already skips a sandbox with a pending export or parked abandoned files. Files from an abandoned epoch were already given up before this restore. - The rule needs an earlier lease row on the same sandbox. A sandbox created for the run is not affected. - Not covered here: the first loss, where the agent fills a new sandbox and the final save needs free space for its archive. That needs separate work. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, browser forensics on staging through Claude in Chrome). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/task-recovery.md | 10 ++++ .../src/__tests__/environment-runtime.test.ts | 13 ++++- .../src/services/environment-lease-handoff.ts | 38 +++++++++++++- server/src/services/environments.ts | 4 +- server/src/services/full-reusable-sandbox.ts | 36 +++++++++++++ .../native-retired-backup-source.ts | 30 +++-------- ...remote-workspace-restore-disk-full.test.ts | 33 ++++++++++++ .../services/remote-workspace-transport.ts | 8 +++ .../remote-workspaces.integration.test.ts | 52 +++++++++++++++++-- server/src/services/remote-workspaces.ts | 8 ++- 10 files changed, 198 insertions(+), 34 deletions(-) create mode 100644 server/src/services/full-reusable-sandbox.ts create mode 100644 server/src/services/remote-workspace-restore-disk-full.test.ts 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)