mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## 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 <noreply@anthropic.com>
152 lines
9.2 KiB
TypeScript
152 lines
9.2 KiB
TypeScript
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, 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";
|
|
import { readNativeHarnessBackupStamp } from "./native-harness-backup-stamp.js";
|
|
import { nativeWorkspaceExportPendingForLease, nativeWorkspaceExportPendingForResource } from "./native-workspace-finalization-state.js";
|
|
|
|
/** Durable run events that prove a provider session did work in a run. */
|
|
export const NATIVE_PROVIDER_DURABLE_EVENT_TYPES = new Set([
|
|
"harness.ready",
|
|
"session.started",
|
|
"session.resumed",
|
|
"session.updated",
|
|
"turn.started",
|
|
"provider.event",
|
|
"provider.rpc_result",
|
|
]);
|
|
|
|
export function nativeHarnessBackupManifestSha256(manifestBytes: Buffer | string): string {
|
|
return `sha256:${createHash("sha256").update(manifestBytes).digest("hex")}`;
|
|
}
|
|
|
|
/**
|
|
* A created sandbox normally refuses a per-turn backup that has no recorded
|
|
* reusable lease, because the backup's source sandbox may still hold newer
|
|
* provider state. That ambiguity is absent when Paperclip itself destroyed the
|
|
* source sandbox: the provider confirmed the termination, the source lease's
|
|
* stamp names exactly this backup, and no provider work for the session was
|
|
* recorded after the backup completed. This is the same proof a confirmed
|
|
* replacement relies on, reached through a lease that was retired first.
|
|
*
|
|
* A settled workspace-restore hold is the other retired source. The hold
|
|
* changed the lease to `retain_on_failure`, which reuse never selects, and
|
|
* stopped the sandbox under a stop-only receipt that permits no provider work.
|
|
* Releases before the hold settlement restored warm reuse left such rows
|
|
* stranded, so this also unsticks state saved by those releases.
|
|
*
|
|
* An idle warm source is the third. Its own run is terminal, no run holds the
|
|
* lease, and no workspace export is pending on the sandbox, so nothing can do
|
|
* provider work there. Reuse skips such a lease while the previous run's
|
|
* workspace export is still in flight, and the next run then gets a new lease.
|
|
* With no provider work after the backup, the idle sandbox holds exactly the
|
|
* checkpointed state, so restoring the backup continues the same session. The
|
|
* source is claimed as superseded first, so it is never resumed with that
|
|
* older state after the restored lease moves on.
|
|
*/
|
|
export async function retiredSourceAuthorizesNativeBackupRestore(db: Db, input: {
|
|
companyId: string;
|
|
currentRunId: string;
|
|
normalizedSessionId: string;
|
|
manifest: { sourceProviderLeaseId: string; runnerInstanceId: string; normalizedSessionId: string };
|
|
manifestSha256: string;
|
|
/** The allocation the backup restores into. Its own missing state never proves a retired source. */
|
|
targetProviderLeaseId?: string | null;
|
|
}): Promise<boolean> {
|
|
if (!input.manifest.sourceProviderLeaseId || input.manifest.normalizedSessionId !== input.normalizedSessionId
|
|
|| input.manifest.sourceProviderLeaseId === input.targetProviderLeaseId) return false;
|
|
const leases = await db.select().from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, input.companyId),
|
|
eq(environmentLeases.providerLeaseId, input.manifest.sourceProviderLeaseId),
|
|
));
|
|
const source = leases.filter(lease => lease.companyId === input.companyId
|
|
&& lease.providerLeaseId === input.manifest.sourceProviderLeaseId);
|
|
const tips = source.filter(lease => !Object.hasOwn(lease.metadata ?? {}, "reusableLeaseSuccessor"));
|
|
if (tips.length !== 1) return false;
|
|
const lease = tips[0]!;
|
|
if (!retiredReusableLeasePredecessors(lease, source.filter(row => row.id !== lease.id))) return false;
|
|
const termination = lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined;
|
|
const destroyed = ["expired", "failed"].includes(lease.status) && hasRemoteTerminationReceipt(lease)
|
|
&& termination?.state === "destroyed";
|
|
const stamp = readNativeHarnessBackupStamp(lease.metadata?.nativeHarnessBackup, lease.providerLeaseId!);
|
|
if (!stamp || stamp.manifestSha256 !== input.manifestSha256
|
|
|| stamp.normalizedSessionId !== input.normalizedSessionId
|
|
|| stamp.runnerInstanceId !== input.manifest.runnerInstanceId) return false;
|
|
// A released lease can still be selected for resume; only a retired one is final.
|
|
const idleSource = !destroyed && !await settledRestoreHoldRetiresSource(db, lease);
|
|
if (idleSource && !await idleWarmSourceRetiresBackup(db, lease, input.currentRunId)) return false;
|
|
// Provider work recorded after the checkpoint means the destroyed sandbox
|
|
// held newer state than this backup. Restoring would silently rewind it.
|
|
const later = await db.select({ runId: heartbeatRunEvents.runId }).from(heartbeatRunEvents)
|
|
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, heartbeatRunEvents.runId))
|
|
.where(and(
|
|
eq(heartbeatRunEvents.companyId, input.companyId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId),
|
|
ne(heartbeatRuns.id, input.currentRunId),
|
|
inArray(heartbeatRunEvents.eventType, [...NATIVE_PROVIDER_DURABLE_EVENT_TYPES]),
|
|
gt(heartbeatRunEvents.createdAt, new Date(stamp.completedAt)),
|
|
)).limit(1);
|
|
if (later.length) return false;
|
|
return !idleSource || await supersedeIdleWarmSource(db, lease, input);
|
|
}
|
|
|
|
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. 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;
|
|
}) {
|
|
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"]);
|
|
|
|
/**
|
|
* A warm reusable lease whose run has ended and that no run holds. Its sandbox
|
|
* may still be running, but only a run does provider work there, and the
|
|
* caller's later-work check proves none did after the backup. A pending
|
|
* workspace export or cleanup on the allocation keeps it ambiguous.
|
|
*/
|
|
async function idleWarmSourceRetiresBackup(db: Db, lease: typeof environmentLeases.$inferSelect, currentRunId: string) {
|
|
if (lease.leasePolicy !== "reuse_by_environment" || !["released", "retained"].includes(lease.status)
|
|
|| !lease.heartbeatRunId || lease.heartbeatRunId === currentRunId
|
|
|| lease.metadata?.pendingCleanupInFlight === true
|
|
// A restore hold or a pending shutdown settlement still protects the files; reuse skips these too.
|
|
|| Object.hasOwn(lease.metadata ?? {}, LEGACY_WORKSPACE_RECOVERY_KEY)
|
|
|| (lease.metadata?.legacyShutdownWorkspaceSettlement as { state?: unknown } | undefined)?.state === "pending") return false;
|
|
const [run] = await db.select({ sourceRunStatus: heartbeatRuns.status }).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, lease.companyId), eq(heartbeatRuns.id, lease.heartbeatRunId))).limit(1);
|
|
if (!run || !TERMINAL_SOURCE_RUN_STATUSES.has(run.sourceRunStatus)) return false;
|
|
return !await nativeWorkspaceExportPendingForResource(db, lease, currentRunId);
|
|
}
|
|
|
|
/**
|
|
* A stopped, released lease is retired only when it is a workspace-restore hold
|
|
* that nothing can select for resume: `retain_on_failure` with the hold's own
|
|
* marker, a confirmed stop-and-retain receipt whose state is `stopped`, and no
|
|
* unsaved writer or pending native workspace export bound to the allocation.
|
|
* A stopped `reuse_by_environment` lease stays ambiguous and fails closed.
|
|
*/
|
|
async function settledRestoreHoldRetiresSource(db: Db, lease: typeof environmentLeases.$inferSelect): Promise<boolean> {
|
|
const marker = lease.metadata?.workspaceRestoreRecovery as { schema?: unknown; runId?: unknown } | undefined;
|
|
if (lease.leasePolicy !== "retain_on_failure" || lease.status !== "released" || !lease.heartbeatRunId
|
|
|| marker?.schema !== LEGACY_WORKSPACE_RECOVERY_SCHEMA || marker.runId !== lease.heartbeatRunId) return false;
|
|
// Provider expiry cannot revive the allocation; it only makes the source
|
|
// more final. Every other stop-and-retain receipt check stays strict.
|
|
if (!hasConfirmedSandboxStopAndRetain({ ...lease, expiresAt: null })) return false;
|
|
// Includes the dirty remote writer source (`preparedRemoteWorkspaceSource`).
|
|
return !await nativeWorkspaceExportPendingForLease(db, lease);
|
|
}
|