From 73dc33c620e237185b236225d0d3508e864f1d6a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:45:20 -0600 Subject: [PATCH] fix(runner): keep a disk reserve so a full sandbox disk does not strand the runner (#22068) 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 > - Agents in a Paperclip-managed sandbox run under the Paperclip runner (`runnerd`), which keeps durable state on the sandbox disk > - An agent can fill that disk with its own work. In one case the agent installed a Rust toolchain and a second checkout with dependencies on a 10 GiB sandbox > - `runnerd` then could not write its state and exited. Each relaunch tried to upload its launch files to the full disk and failed, 83 times in 7 minutes > - The run ended as a generic provider failure that asked a person to inspect it, and Retry repeated the same failure > - This pull request keeps a small disk reserve that belongs to Paperclip. Recovery releases it to relaunch the runner, and stops at once with a named code when nothing is left to free > - The benefit is that the agent's turn can continue and see the full disk in its own tool output, instead of the run dying with it ## Linked Issues or Issue Description **What happened?** An agent in a managed Daytona sandbox filled the 10 GiB disk. `runnerd` exited with `failed to persist bounded diagnostic: No space left on device (os error 28)`. Runner process recovery then retried for the full 420000 ms reconnect grace. Every attempt failed with `.paperclip-upload-.tar.gz: create: ... no space left on device`. The run failed as `native_provider_terminal_failed`, and the recovery asked a board user to verify that the provider stopped. **Steps to reproduce** 1. Run an agent in a managed sandbox and have it fill the disk (for example a Rust toolchain plus a full dependency install). 2. `runnerd` exits when it next writes its state. 3. Watch recovery retry the relaunch upload until the grace expires. **Expected behavior** Paperclip relaunches its runner on a disk the agent filled, so the turn continues and the agent sees the full disk in its tools. When the runner truly cannot start, recovery says so at once with a named cause instead of retrying for 7 minutes. **Environment** Managed Daytona sandbox (fleet snapshot, 4 CPU, 8 GiB memory, 10 GiB disk), `paperclip_runner` native runtime. ## What Changed - New `server/src/services/native-runtime/remote-runner-disk-reserve.ts` owns the reserve: hold/release scripts, the full-disk classifier, and `createRemoteRunnerDiskReserve`. A release waits for an in-flight hold, and no hold starts after a release. - Both remote runner launchers (agent runs and Dot) get a reserve path in managed sandboxes only: `/.paperclip-runtime/paperclip-runner/disk-reserve`. Workspace saves and Git already exclude `.paperclip-runtime`. SSH hosts get no reserve. - After the first launch's identity is confirmed, the launcher holds 256 MiB in the background, only while 2 GiB more is free. It is off the startup path. - A relaunch releases the reserve before it stages. A launch that hits a full disk while staging releases the reserve and stages once more. - Release tries twice and reports `released`, `not_held` or `failed`. Only `not_held` ends the launch with `sandbox_disk_full`. A release that cannot run rethrows the original error, so recovery still retries. - Command-based staging (no `syncIn`) keeps a full disk recognizable with an `ENOSPC` code instead of a bare `runner_remote_*_staging_failed`. - `SANDBOX_DISK_FULL_FAILURE_CODE` and `isSandboxDiskFullFailure` live in the runner package. Runner process recovery checks the error code and stops at once instead of retrying for the whole grace. Other staging failures still retry. ## Verification - Red before the fix, green after: - `server/src/services/native-runtime/remote-runner-disk-reserve.test.ts`: release-and-restage, release before relaunch, `sandbox_disk_full` when release frees too little, no retry for a failure that is not a full disk, hold/release scripts in a real shell, no hold below the free-space floor. Before the fix, the launch rejected with the exact upload error from the incident. - `packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts` "fails at once when a replacement cannot be staged because the sandbox disk is full": before the fix it was still retrying after 4 s; after, it fails with `sandbox_disk_full` after one replacement. - Kept: "retries a replacement whose staging failed before any process launched" still passes, so a raw transient staging failure still retries. - Updated: "confirms no replacement process exists when staging fails before the launch RPC" now expects `sandbox_disk_full` with the upload error as cause. Exit is still confirmed and no launch RPC runs. - Real sandbox from the same fleet snapshot (Daytona, 10 GiB): hold created a 256 MiB reserve. The disk was filled to 100%. A 5 MB write then failed. Release returned `true`, and a 50 MB write then succeeded. A second release returned `false`. Hold on the now 98% full disk did not create a reserve. - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. `pnpm verify` result is in a comment below. - Review round: tests for a lost release RPC, hold/release ordering, command-based staging on a full disk, the hold after a dispatched first launch (not on relaunch), and no reserve on SSH. Each launcher-level test failed with its fix removed. - Focused suites on the review revision: transport 335/335, launcher 130/130 (filtered), launch assets 35/35, reserve 14/14. Server and runner typecheck pass. - Not run: a full product run in which an agent fills the disk and the relaunched `runnerd` resumes the turn end to end. ## Risks - Each managed sandbox holds 256 MiB more disk while it has more than 2 GiB free. That is 2.5% of a 10 GiB sandbox. - A relaunch for any reason releases the reserve for the rest of that run. The next run's launch takes it again. - If the agent keeps writing after the relaunch, the disk can fill again. The second time, nothing is left to release, and the run fails at once with `sandbox_disk_full` instead of after 7 minutes. - The run's error code is still `native_provider_terminal_failed`. The message now names `sandbox_disk_full`. A dedicated failure code and recovery text are a follow-up. - `runnerd` loses its own error message when it cannot persist its diagnostic. This PR does not change the Rust binary. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [x] 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 --- .../src/contracts/sandbox-disk-full.ts | 11 + packages/paperclip-runner/src/index.ts | 1 + .../src/live/runnerd-codex-transport.test.ts | 51 ++++ .../src/live/runnerd-codex-transport.ts | 7 + .../native-session-executor.test.ts | 4 +- .../native-runtime/native-session-executor.ts | 53 +++- .../native-runtime/remote-launch-assets.ts | 3 +- .../remote-runner-disk-reserve.test.ts | 287 ++++++++++++++++++ .../remote-runner-disk-reserve.ts | 121 ++++++++ server/src/vendor/paperclip-runner/index.ts | 2 + 10 files changed, 528 insertions(+), 12 deletions(-) create mode 100644 packages/paperclip-runner/src/contracts/sandbox-disk-full.ts create mode 100644 server/src/services/native-runtime/remote-runner-disk-reserve.test.ts create mode 100644 server/src/services/native-runtime/remote-runner-disk-reserve.ts diff --git a/packages/paperclip-runner/src/contracts/sandbox-disk-full.ts b/packages/paperclip-runner/src/contracts/sandbox-disk-full.ts new file mode 100644 index 00000000000..e2769a0d4b1 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/sandbox-disk-full.ts @@ -0,0 +1,11 @@ +/** + * The `code` a runner launch failure carries when the sandbox disk is full and + * nothing Paperclip owns is left to free. Runner process recovery stops at once + * on it: the same launch fails the same way for the rest of the grace. + */ +export const SANDBOX_DISK_FULL_FAILURE_CODE = "sandbox_disk_full"; + +export function isSandboxDiskFullFailure(error: unknown): boolean { + return typeof error === "object" && error !== null + && (error as { code?: unknown }).code === SANDBOX_DISK_FULL_FAILURE_CODE; +} diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index dcb459109b1..9431ee4330d 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -8,6 +8,7 @@ export * from "./contracts/completion-result.js"; export * from "./contracts/codex.js"; export * from "./contracts/provider-performance.js"; export * from "./contracts/durable-recovery.js"; +export * from "./contracts/sandbox-disk-full.js"; export * from "./contracts/harness-driver.js"; export * from "./contracts/local-runner.js"; export * from "./contracts/native-execution.js"; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index bf44c8eaea4..92b0d34f86d 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -22,6 +22,7 @@ import { PRP_PROTOCOL_VERSION } from "../protocol/replay-contract.js"; import { redactCapabilityEvidenceData } from "./evidence-redaction.js"; import { NativeSessionCloseUnrecoverableError } from "../contracts/native-session-backend.js"; import { parsePaperclipQuestionSet } from "../contracts/question-set.js"; +import { SANDBOX_DISK_FULL_FAILURE_CODE } from "../contracts/sandbox-disk-full.js"; import { ACPX_CREDENTIAL_BINDING_ENV, createAcpxCredentialBinding, @@ -615,6 +616,56 @@ it("retries a replacement whose staging failed before any process launched", asy } }, 15_000); +// Relaunching on a full sandbox disk retried the same upload for the whole grace. +it("fails at once when a replacement cannot be staged because the sandbox disk is full", async () => { + const directory = await mkdtemp(join(tmpdir(), "runnerd-replacement-disk-full-")); + const diskFull = Object.assign(new Error("sandbox_disk_full: the sandbox disk is full, so the runner cannot be started"), + { code: SANDBOX_DISK_FULL_FAILURE_CODE }); + const children: ReturnType[] = []; + const exits: Promise[] = []; + const launch = vi.fn((spec: durableControlPlane.RunnerProcessLaunchSpec) => { + if (children.length > 0) return { + child: { pid: undefined, exitCode: null, kill: () => false }, + completion: Promise.reject(diskFull), + isExitConfirmed: (): boolean => true, + }; + const child = spawn(spec.command, [...spec.args], { cwd: spec.cwd, env: spec.environment, stdio: "ignore" }); + children.push(child); + exits.push(new Promise(resolveExit => child.once("exit", () => resolveExit()))); + return { + child, + completion: new Promise((resolveExit, rejectExit) => { + child.once("error", rejectExit); + child.once("exit", (code, signal) => resolveExit({ code, signal, stdout: "", stderr: "" })); + }), + isExitConfirmed: () => child.exitCode !== null || child.signalCode !== null, + }; + }); + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), codexCommand: fakeCodex, + codexArgs: fakeCodexArgs(directory), stateDirectory: directory, + lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 }, + runnerReconnectGraceMs: 10_000, runnerProcessLauncher: launch, + }); + try { + await bundle.transport.request("thread/start", { cwd: directory }); + const failed = (async () => { + for await (const _event of bundle.transport.notifications()) {} + })().catch(error => error as Error); + children[0]!.kill("SIGKILL"); + const result = await Promise.race([failed, new Promise(resolve => setTimeout(() => resolve("still retrying"), 4_000))]); + expect(result).toMatchObject({ message: expect.stringMatching(/^sandbox_disk_full: /), cause: diskFull }); + expect(launch).toHaveBeenCalledTimes(2); + } finally { + const providerPid = bundle.evidence().codexPid; + if (providerPid) { try { process.kill(providerPid, "SIGKILL"); } catch {} } + await bundle.transport.detachControllerForRestart!(); + for (const child of children) child.kill("SIGKILL"); + await Promise.all(exits); + await rm(directory, { recursive: true, force: true }); + } +}, 20_000); + it("fails instead of relaunching a runner that keeps exiting right after it is restored", async () => { const directory = await mkdtemp(join(tmpdir(), "runnerd-restore-crash-loop-")); const crash = "paperclip-runnerd: redacted display activity exceeds its schema bounds"; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 549fcbc5673..ab98fa86a33 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -1,6 +1,7 @@ import { providerTurnStartBefore, providerTurnToolCallSourceSeq } from "./provider-turn-tool-order.js"; import type { RunnerAttachmentDownloadGrant } from "../contracts/harness-driver.js"; import { readProviderFailure } from "../contracts/provider-failure.generated.js"; +import { isSandboxDiskFullFailure } from "../contracts/sandbox-disk-full.js"; import { confirmAntigravityProbeNativeRetirement } from "../drivers/acpx/antigravity-probe-retirement.js"; import { resolveGrokDisableWebSearch, admittedGrokWebSearchPolicy } from "../drivers/acpx/grok-web-search.js"; import { PRP_COMPLETION_TOOL_NAME, PRP_COMPLETION_RESULT_BRIDGE_INPUT_SCHEMA } from "../contracts/completion-result.js"; @@ -9399,6 +9400,12 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ); return; } + // The launcher already released everything Paperclip holds on that + // disk. The same launch fails the same way for the rest of the grace. + if (isSandboxDiskFullFailure(observationError)) { + this.#failTransport(new Error(observationDetail.slice(0, 1_000), { cause: observationError })); + return; + } attempt += 1; } if (!this.#closed) { diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index db296a1335e..cd8fcb9be11 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1763,7 +1763,9 @@ describe("remote runner process supervision", () => { stateDirectory: "/runtime", diagnosticsDirectory: "/runtime/diagnostics", runnerInstanceId: "runner-remote", ensureArtifact: async () => { throw stagingError; }, })({ command: "/controller/runnerd", args: [], cwd: "/controller", environment: {} }); - await expect(handle.completion).rejects.toBe(stagingError); + // With no reserve to release, the full disk is named so recovery stops retrying. + await expect(handle.completion).rejects.toMatchObject({ + message: expect.stringMatching(/^sandbox_disk_full: /), cause: stagingError }); expect(execute).not.toHaveBeenCalled(); expect(handle.child.pid).toBeUndefined(); expect(handle.isExitConfirmed?.()).toBe(true); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 2602a2eb4f5..fee231ca370 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -80,6 +80,13 @@ import { museRunnerBroker } from "../muse-runner-broker.js"; import { nativeCaseHandoffResult } from "./native-case-handoff.js"; import { assertExternalNativeRunAuthority } from "./external-native-authority.js"; import { stageRemoteLaunchAssets } from "./remote-launch-assets.js"; +import { + createRemoteRunnerDiskReserve, + isSandboxDiskFullError, + remoteRunnerDiskReservePath, + remoteStagingFailure, + sandboxDiskFullFailure, +} from "./remote-runner-disk-reserve.js"; import { NATIVE_CONTINUITY_STATE_ENTRIES, NATIVE_SESSION_ROOT_HELD_ENTRIES, describeUnexpectedNativeSessionRootEntries, isKnownNativeSessionRootEntry, @@ -14675,7 +14682,7 @@ export async function stageRemoteRunnerFile(input: { bypassSession: true, }); if (result.exitCode !== 0 || result.timedOut) { - throw new Error("runner_remote_staging_failed"); + throw remoteStagingFailure("runner_remote_staging_failed", result); } } @@ -14795,7 +14802,7 @@ export async function stageRemoteRunnerDirectory(input: { bypassSession: true, }); if (result.exitCode !== 0 || result.timedOut) { - throw new Error("runner_remote_directory_staging_failed"); + throw remoteStagingFailure("runner_remote_directory_staging_failed", result); } } @@ -15949,6 +15956,8 @@ export function createRemoteRunnerProcessLauncher(input: { stateDirectory: string; diagnosticsDirectory: string; runnerInstanceId: string; + /** Managed sandboxes only; never on a user's own host. Outside every saved directory. */ + diskReservePath?: string; ensureArtifact?: (spec: RunnerProcessLaunchSpec) => Promise; requireProcessStartFingerprint?: boolean; onSpawn?: (meta: { @@ -15961,7 +15970,11 @@ export function createRemoteRunnerProcessLauncher(input: { onRunnerProcessSpawned?: () => void; }): (spec: RunnerProcessLaunchSpec) => RunnerProcessHandle { const runner = input.runner; + const reserve = input.diskReservePath ? createRemoteRunnerDiskReserve(runner, input.diskReservePath) : null; + let launches = 0; return (spec) => { + // Every later launch replaces a runner that was lost, possibly to a full disk. + const relaunch = launches++ > 0; let exitConfirmed = false; // Set immediately before the launch RPC. Until then no sandbox command // could have started runnerd, so a staging failure proves no process. @@ -16034,15 +16047,30 @@ export function createRemoteRunnerProcessLauncher(input: { }; }; const completion = (async () => { + if (relaunch) await reserve?.release(); if (input.ensureArtifact) { - if (input.trace) { - await input.trace.measure( - "runner.runtime.stage", - () => input.ensureArtifact!(spec), - { parentName: "runner.session.startup" }, - ); - } else { - await input.ensureArtifact(spec); + const stage = () => input.trace + ? input.trace.measure("runner.runtime.stage", () => input.ensureArtifact!(spec), + { parentName: "runner.session.startup" }) + : input.ensureArtifact!(spec); + let restaged = false; + for (;;) { + try { + await stage(); + break; + } catch (error) { + if (!isSandboxDiskFullError(error)) throw error; + const released = reserve && !restaged ? await reserve.release() : "not_held"; + if (released === "released") { + restaged = true; + continue; + } + // The reserve may still be held, so recovery may try again. + if (released === "failed") throw error; + // Nothing Paperclip owns is left to free, and no runner is + // running to free space, so retrying cannot succeed. + throw sandboxDiskFullFailure(error); + } } } if (pendingSignal) return cancelledBeforeDispatch(); @@ -16162,6 +16190,9 @@ export function createRemoteRunnerProcessLauncher(input: { endedAtMs: Date.now(), attributes: { identitySource: "remote_marker", detached: true }, }); + // Off the startup path. A relaunch leaves the reserve released, so one + // run cannot take space back from an agent that already filled the disk. + if (!relaunch) reserve?.hold(); let supervisionUnknownSince: number | null = null; while (true) { @@ -16501,6 +16532,7 @@ async function prepareRemoteExternalRunner({ input, target, runner, root, identi const launch = createRemoteRunnerProcessLauncher({ target, runner, remoteBinary, processIdentityPath: posix.join(runnerStateDirectory, "runner-process.identity"), stateDirectory: runnerStateDirectory, diagnosticsDirectory: posix.join(remoteRoot, "diagnostics"), runnerInstanceId: input.runnerInstanceId, + diskReservePath: remoteRunnerDiskReservePath(target), requireProcessStartFingerprint: true, onSpawn: async meta => { await input.onSpawn?.(meta); identityReady(); }, onLog: input.onLog, trace: input.trace, onRunnerProcessSpawned: () => spawned() }); @@ -18397,6 +18429,7 @@ async function createRunnerdBackendWithinSessionClaim( stateDirectory: remoteStateDirectory, diagnosticsDirectory: posix.join(remoteSessionRoot!, "diagnostics"), runnerInstanceId: input.runnerInstanceId, + diskReservePath: remoteRunnerDiskReservePath(remoteTarget), ensureArtifact: spec => { const sourceRun = spec.nativeRunner && spec.nativeRunner.identity.runId !== input.execution.binding.runId; const isolatedCodex = input.execution.provider.kind === "codex" diff --git a/server/src/services/native-runtime/remote-launch-assets.ts b/server/src/services/native-runtime/remote-launch-assets.ts index 6c787fa3abf..c10fc27154a 100644 --- a/server/src/services/native-runtime/remote-launch-assets.ts +++ b/server/src/services/native-runtime/remote-launch-assets.ts @@ -4,6 +4,7 @@ import { posix, resolve } from "node:path"; import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; import type { NativeRuntimeContextSnapshot } from "../../vendor/paperclip-runner/index.js"; import type { NativeRunTrace } from "./native-run-trace.js"; +import { remoteStagingFailure } from "./remote-runner-disk-reserve.js"; type StageAsset = { sourcePath: string; @@ -117,7 +118,7 @@ export async function stageRemoteLaunchAssets(input: LaunchAssetsInput): Promise timeoutMs: 10_000, }); if (created.exitCode !== 0 || created.timedOut) { - throw new Error("runner_remote_directory_staging_failed"); + throw remoteStagingFailure("runner_remote_directory_staging_failed", created); } if (directory.name !== "codex-home") continue; const localDirectory = resolve(input.root, directory.name); diff --git a/server/src/services/native-runtime/remote-runner-disk-reserve.test.ts b/server/src/services/native-runtime/remote-runner-disk-reserve.test.ts new file mode 100644 index 00000000000..080d744a6fd --- /dev/null +++ b/server/src/services/native-runtime/remote-runner-disk-reserve.test.ts @@ -0,0 +1,287 @@ +import { spawn } from "node:child_process"; +import { existsSync, statSync } from "node:fs"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +import { describe, expect, it, vi } from "vitest"; +import { SANDBOX_DISK_FULL_FAILURE_CODE, isSandboxDiskFullFailure } from "../../vendor/paperclip-runner/index.js"; +import { createRemoteRunnerProcessLauncher, stageRemoteRunnerFile } from "./native-session-executor.js"; +import { + createRemoteRunnerDiskReserve, + holdRemoteRunnerDiskReserve, + releaseRemoteRunnerDiskReserve, + remoteRunnerDiskReservePath, +} from "./remote-runner-disk-reserve.js"; + +type Execute = CommandManagedRuntimeRunner["execute"]; +type Request = Parameters[0]; + +const ok = { exitCode: 0, signal: null, timedOut: false, pid: null, startedAt: null, stdout: "", stderr: "" }; +// What a Daytona upload reports when the agent has filled the sandbox disk. +const diskFull = () => new Error( + '{"errors":["/home/daytona/paperclip-workspace/.paperclip-upload-1.tar.gz: create: open /home/daytona/paperclip-workspace/.paperclip-upload-1.tar.gz: no space left on device"],"files":[]}', +); +const label = (request: Request) => request.args?.[2]; +const spec = { command: "/controller/runnerd", args: [], cwd: "/controller", environment: {} }; +const reservePath = "/workspace/.paperclip-runtime/paperclip-runner/disk-reserve"; + +/** A sandbox whose disk holds Paperclip's reserve. Staging fits only after the reserve is released. */ +function fullSandbox(options: { freedByRelease: boolean; failedReleases?: number }) { + const disk = { reserveHeld: true, failedReleases: options.failedReleases ?? 0 }; + const execute = vi.fn(async request => { + if (label(request) === "paperclip-runner-disk-reserve-release") { + if (disk.failedReleases > 0) { + disk.failedReleases -= 1; + throw new Error("sandbox_rpc_lost"); + } + const released = disk.reserveHeld; + disk.reserveHeld = false; + return { ...ok, stdout: released ? "released\n" : "not_held\n" }; + } + return ok; + }); + const ensureArtifact = vi.fn(async () => { + if (disk.reserveHeld || !options.freedByRelease) throw diskFull(); + }); + return { disk, execute, ensureArtifact }; +} + +function launcherFor(sandbox: { execute: Execute; ensureArtifact?: () => Promise }) { + return createRemoteRunnerProcessLauncher({ + target: { kind: "remote", transport: "sandbox", environmentId: "environment", leaseId: "lease", remoteCwd: "/workspace" }, + runner: { execute: sandbox.execute }, + remoteBinary: "/runtime/runnerd", processIdentityPath: "/runtime/identity", + stateDirectory: "/runtime/sessions/s/runner", diagnosticsDirectory: "/runtime/sessions/s/diagnostics", + runnerInstanceId: "runner-disk-reserve", + diskReservePath: reservePath, + ensureArtifact: sandbox.ensureArtifact, + }); +} + +// An agent filled a managed sandbox's disk, runnerd exited, and every +// relaunch failed to upload its launch files for the whole reconnect grace. +describe("remote runner launch on a full sandbox disk", () => { + it("releases Paperclip's disk reserve and stages again", async () => { + const sandbox = fullSandbox({ freedByRelease: true }); + const handle = launcherFor(sandbox)(spec); + // Stop before dispatch: this test covers staging only. + handle.child.kill("SIGTERM"); + await expect(handle.completion).resolves.toMatchObject({ stderr: "runner_process_launch_cancelled" }); + expect(sandbox.ensureArtifact).toHaveBeenCalledTimes(2); + expect(sandbox.disk.reserveHeld).toBe(false); + }); + + it("releases the reserve before a relaunch stages, since the lost runner may have died on a full disk", async () => { + const sandbox = fullSandbox({ freedByRelease: true }); + const launcher = launcherFor(sandbox); + sandbox.disk.reserveHeld = false; + const first = launcher(spec); + first.child.kill("SIGTERM"); + await first.completion; + sandbox.disk.reserveHeld = true; + sandbox.ensureArtifact.mockClear(); + + const relaunch = launcher(spec); + relaunch.child.kill("SIGTERM"); + await expect(relaunch.completion).resolves.toMatchObject({ stderr: "runner_process_launch_cancelled" }); + expect(sandbox.ensureArtifact).toHaveBeenCalledTimes(1); + expect(sandbox.disk.reserveHeld).toBe(false); + }); + + it("fails at once with the shared sandbox_disk_full code when releasing the reserve does not free enough space", async () => { + const sandbox = fullSandbox({ freedByRelease: false }); + const handle = launcherFor(sandbox)(spec); + const failure = await handle.completion.catch((error: unknown) => error); + expect(isSandboxDiskFullFailure(failure)).toBe(true); + expect(failure).toMatchObject({ code: SANDBOX_DISK_FULL_FAILURE_CODE, message: expect.stringMatching(/^sandbox_disk_full: /) }); + expect(sandbox.ensureArtifact).toHaveBeenCalledTimes(2); + // No launch RPC ran, so recovery knows no replacement runner exists. + expect(sandbox.execute.mock.calls.map(([request]) => label(request))).toEqual(["paperclip-runner-disk-reserve-release"]); + expect(handle.isExitConfirmed?.()).toBe(true); + }); + + it("retries a release whose sandbox command was lost, then stages again", async () => { + const sandbox = fullSandbox({ freedByRelease: true, failedReleases: 1 }); + const handle = launcherFor(sandbox)(spec); + handle.child.kill("SIGTERM"); + await expect(handle.completion).resolves.toMatchObject({ stderr: "runner_process_launch_cancelled" }); + expect(sandbox.disk.reserveHeld).toBe(false); + }); + + it("keeps the failure retryable when the release cannot run, because the reserve may still be held", async () => { + const sandbox = fullSandbox({ freedByRelease: true, failedReleases: 2 }); + const failure = await launcherFor(sandbox)(spec).completion.catch((error: unknown) => error); + expect(isSandboxDiskFullFailure(failure)).toBe(false); + expect(failure).toMatchObject({ message: expect.stringContaining("no space left on device") }); + expect(sandbox.disk.reserveHeld).toBe(true); + }); + + it("does not stage twice for a failure that is not a full disk", async () => { + const sandbox = fullSandbox({ freedByRelease: true }); + const failure = new Error("runner_remote_directory_staging_failed"); + sandbox.ensureArtifact.mockImplementation(async () => { throw failure; }); + await expect(launcherFor(sandbox)(spec).completion).rejects.toBe(failure); + expect(sandbox.ensureArtifact).toHaveBeenCalledTimes(1); + expect(sandbox.disk.reserveHeld).toBe(true); + }); + + it("recognizes a full disk reported by a command-based upload, not only by a provider upload", async () => { + const root = await mkdtemp(join(tmpdir(), "runner-disk-reserve-stage-")); + try { + const sourcePath = join(root, "runtime-context.json"); + await writeFile(sourcePath, "{}"); + const sandbox = fullSandbox({ freedByRelease: true }); + sandbox.ensureArtifact.mockImplementation(async () => { + await stageRemoteRunnerFile({ + target: { kind: "remote", transport: "sandbox", remoteCwd: root } as never, + runner: { execute: async () => (sandbox.disk.reserveHeld + ? { ...ok, exitCode: 1, stderr: "base64: write error: No space left on device" } + : ok) } as never, + sourcePath, targetPath: join(root, "staged.json"), mode: 0o600, + }); + }); + const handle = launcherFor(sandbox)(spec); + handle.child.kill("SIGTERM"); + await expect(handle.completion).resolves.toMatchObject({ stderr: "runner_process_launch_cancelled" }); + expect(sandbox.ensureArtifact).toHaveBeenCalledTimes(2); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); + +describe("remote runner disk reserve across launches", () => { + it("holds the reserve once after the first launch starts, and a relaunch only releases it", async () => { + let nonce = ""; + const execute = vi.fn(async request => { + const name = label(request); + if (name === "paperclip-runner-launch") { nonce = request.args![4]!; return ok; } + if (name === "paperclip-runner-process-identity") { + return { ...ok, stdout: `${nonce}\n4321\n2026-09-06T00:00:00.000Z\nrunner-disk-reserve\n` }; + } + // The runner exits at once, so the launch settles. + if (name === "paperclip-runner-monitor") return { ...ok, exitCode: 45 }; + if (name === "paperclip-runner-disk-reserve-release") return { ...ok, stdout: "released\n" }; + if (name === "paperclip-runner-disk-reserve-hold") return ok; + return { ...ok, exitCode: 1 }; + }); + const launcher = launcherFor({ execute, ensureArtifact: async () => undefined }); + const holds = () => execute.mock.calls.filter(([request]) => label(request) === "paperclip-runner-disk-reserve-hold"); + const releases = () => execute.mock.calls.filter(([request]) => label(request) === "paperclip-runner-disk-reserve-release"); + + await launcher(spec).completion; + await vi.waitFor(() => expect(holds()).toHaveLength(1)); + expect(holds()[0]![0].args?.[3]).toBe(reservePath); + expect(releases()).toHaveLength(0); + + await launcher(spec).completion; + expect(releases()).toHaveLength(1); + expect(holds()).toHaveLength(1); + expect(execute.mock.calls.filter(([request]) => label(request) === "paperclip-runner-launch")).toHaveLength(2); + }); + + it("holds no reserve when the launcher has no reserve path, as on a user's own host", async () => { + let nonce = ""; + const execute = vi.fn(async request => { + const name = label(request); + if (name === "paperclip-runner-launch") { nonce = request.args![4]!; return ok; } + if (name === "paperclip-runner-process-identity") { + return { ...ok, stdout: `${nonce}\n4321\n2026-09-06T00:00:00.000Z\nrunner-ssh\n` }; + } + if (name === "paperclip-runner-monitor") return { ...ok, exitCode: 45 }; + return { ...ok, exitCode: 1 }; + }); + const launcher = createRemoteRunnerProcessLauncher({ + target: { kind: "remote", transport: "ssh", environmentId: "environment", leaseId: "lease", remoteCwd: "/home/me/ws" } as never, + runner: { execute }, remoteBinary: "/runtime/runnerd", processIdentityPath: "/runtime/identity", + stateDirectory: "/runtime", diagnosticsDirectory: "/runtime/diagnostics", runnerInstanceId: "runner-ssh", + diskReservePath: remoteRunnerDiskReservePath({ transport: "ssh", remoteCwd: "/home/me/ws" }), + ensureArtifact: async () => undefined, + }); + await launcher(spec).completion; + await launcher(spec).completion; + expect(execute.mock.calls.some(([request]) => String(label(request)).startsWith("paperclip-runner-disk-reserve"))).toBe(false); + }); +}); + +describe("remote runner disk reserve ordering", () => { + it("lets a background hold finish before a release, so a relaunch never stages with the space taken back", async () => { + let finishHold!: () => void; + const holdGate = new Promise(resolve => { finishHold = resolve; }); + const events: string[] = []; + const execute = vi.fn(async request => { + if (label(request) === "paperclip-runner-disk-reserve-hold") { + events.push("hold:start"); + await holdGate; + events.push("hold:done"); + return ok; + } + events.push("release"); + return { ...ok, stdout: "released\n" }; + }); + const reserve = createRemoteRunnerDiskReserve({ execute }, reservePath); + reserve.hold(); + const released = reserve.release(); + await new Promise(resolve => setTimeout(resolve, 20)); + expect(events).toEqual(["hold:start"]); + finishHold(); + await expect(released).resolves.toBe("released"); + expect(events).toEqual(["hold:start", "hold:done", "release"]); + }); + + it("starts no hold once a release was requested", async () => { + const execute = vi.fn(async () => ({ ...ok, stdout: "not_held\n" })); + const reserve = createRemoteRunnerDiskReserve({ execute }, reservePath); + await reserve.release(); + reserve.hold(); + expect(execute.mock.calls.map(([request]) => label(request))).toEqual(["paperclip-runner-disk-reserve-release"]); + }); +}); + +const localExecute: Execute = request => new Promise(resolve => { + const child = spawn(request.command, request.args ?? [], { cwd: request.cwd, env: { ...process.env, ...request.env }, + stdio: ["ignore", "pipe", "pipe"] }); + let stdout = "", stderr = ""; + child.stdout.on("data", chunk => { stdout += String(chunk); }); + child.stderr.on("data", chunk => { stderr += String(chunk); }); + child.once("close", (code, signal) => resolve({ exitCode: code, signal, timedOut: false, pid: child.pid ?? null, + startedAt: null, stdout, stderr })); +}); + +describe("remote runner disk reserve scripts", () => { + it("holds the reserve once, then the release frees it", async () => { + const root = await mkdtemp(join(tmpdir(), "runner-disk-reserve-")); + const reserve = join(root, "runtime", "disk-reserve"); + const execute = vi.fn(localExecute); + try { + await holdRemoteRunnerDiskReserve({ execute }, reserve, { bytes: 1024 * 1024, minimumFreeBytes: 0 }); + expect(statSync(reserve).size).toBe(1024 * 1024); + await holdRemoteRunnerDiskReserve({ execute }, reserve, { bytes: 1024 * 1024, minimumFreeBytes: 0 }); + expect(existsSync(`${reserve}.partial`)).toBe(false); + await expect(releaseRemoteRunnerDiskReserve({ execute }, reserve)).resolves.toBe("released"); + expect(existsSync(reserve)).toBe(false); + await expect(releaseRemoteRunnerDiskReserve({ execute }, reserve)).resolves.toBe("not_held"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("never takes space the agent needs: no reserve below the free-space floor", async () => { + const root = await mkdtemp(join(tmpdir(), "runner-disk-reserve-")); + const reserve = join(root, "disk-reserve"); + try { + await holdRemoteRunnerDiskReserve({ execute: localExecute }, reserve, + { bytes: 1024 * 1024, minimumFreeBytes: Number.MAX_SAFE_INTEGER }); + expect(existsSync(reserve)).toBe(false); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("holds a reserve only in a managed sandbox, under the runtime directory saves exclude", () => { + expect(remoteRunnerDiskReservePath({ transport: "sandbox", remoteCwd: "/home/daytona/ws/" })) + .toBe("/home/daytona/ws/.paperclip-runtime/paperclip-runner/disk-reserve"); + expect(remoteRunnerDiskReservePath({ transport: "ssh", remoteCwd: "/home/me/ws" })).toBeUndefined(); + }); +}); diff --git a/server/src/services/native-runtime/remote-runner-disk-reserve.ts b/server/src/services/native-runtime/remote-runner-disk-reserve.ts new file mode 100644 index 00000000000..631d42f7fb2 --- /dev/null +++ b/server/src/services/native-runtime/remote-runner-disk-reserve.ts @@ -0,0 +1,121 @@ +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +import { SANDBOX_DISK_FULL_FAILURE_CODE } from "../../vendor/paperclip-runner/index.js"; + +/** + * The agent can fill a managed sandbox's disk. runnerd then cannot write its + * state and exits, and its relaunch cannot upload its launch files. Paperclip + * holds this much disk in each managed sandbox and releases it to relaunch the + * runner, so the agent's turn continues and its tools report the full disk. + */ +export const REMOTE_RUNNER_DISK_RESERVE_BYTES = 256 * 1024 * 1024; +// The reserve is taken only while this much more is free, so it never takes +// space from an agent that is already close to the limit. +const MINIMUM_FREE_BYTES = 2 * 1024 * 1024 * 1024; + +type Runner = Pick; + +const HOLD_SCRIPT = [ + 'set -u; reserve=$1; bytes=$2; minimum_free_kib=$3; [ -f "$reserve" ] && exit 0', + 'directory=$(dirname -- "$reserve"); mkdir -p -- "$directory" || exit 1', + `free_kib=$(df -Pk -- "$directory" | awk 'NR == 2 { print $4 }')`, + '[ -n "$free_kib" ] && [ "$free_kib" -ge "$minimum_free_kib" ] || exit 0', + 'partial="$reserve.partial"; rm -f -- "$partial"', + 'fallocate -l "$bytes" "$partial" 2>/dev/null || dd if=/dev/zero of="$partial" bs=65536 count=$((bytes / 65536)) 2>/dev/null || { rm -f -- "$partial"; exit 1; }', + 'mv -f -- "$partial" "$reserve"', +].join("\n"); + +// rm needs no free space. The last line names the outcome. +const RELEASE_SCRIPT = + 'rm -f -- "$1.partial" || exit 1; if [ -f "$1" ]; then rm -f -- "$1" && echo released; else echo not_held; fi'; + +export async function holdRemoteRunnerDiskReserve( + runner: Runner, + reservePath: string, + options: { bytes?: number; minimumFreeBytes?: number } = {}, +): Promise { + const bytes = options.bytes ?? REMOTE_RUNNER_DISK_RESERVE_BYTES; + const minimumFreeBytes = options.minimumFreeBytes ?? MINIMUM_FREE_BYTES; + await runner.execute({ + command: "sh", + args: ["-c", HOLD_SCRIPT, "paperclip-runner-disk-reserve-hold", reservePath, + String(bytes), String(Math.ceil((minimumFreeBytes + bytes) / 1024))], + bypassSession: true, + timeoutMs: 30_000, + }); +} + +export type DiskReserveRelease = "released" | "not_held" | "failed"; + +/** Tries twice: one lost sandbox RPC must not read as "nothing left to free". */ +export async function releaseRemoteRunnerDiskReserve(runner: Runner, reservePath: string): Promise { + for (let attempt = 0; attempt < 2; attempt += 1) { + const result = await runner.execute({ + command: "sh", + args: ["-c", RELEASE_SCRIPT, "paperclip-runner-disk-reserve-release", reservePath], + bypassSession: true, + timeoutMs: 10_000, + }).catch(() => null); + if (result?.exitCode !== 0 || result.timedOut) continue; + const outcome = result.stdout.trim().split("\n").at(-1); + if (outcome === "released" || outcome === "not_held") return outcome; + } + return "failed"; +} + +/** + * The reserve of one runner launcher. A release waits for an in-flight hold, + * and no hold starts after a release, so a relaunch never stages while the + * space it freed is taken back. + */ +export function createRemoteRunnerDiskReserve(runner: Runner, reservePath: string) { + let pendingHold: Promise | null = null; + let releaseRequested = false; + return { + hold(): void { + if (releaseRequested || pendingHold) return; + pendingHold = holdRemoteRunnerDiskReserve(runner, reservePath).catch(() => undefined); + }, + async release(): Promise { + releaseRequested = true; + await pendingHold; + return releaseRemoteRunnerDiskReserve(runner, reservePath); + }, + }; +} + +export type RemoteRunnerDiskReserve = ReturnType; + +export function isSandboxDiskFullError(error: unknown): boolean { + if (!error || typeof error !== "object") return false; + const { code, message } = error as { code?: unknown; message?: unknown }; + if (code === "ENOSPC" || code === "EDQUOT") return true; + return typeof message === "string" && isSandboxDiskFullText(message); +} + +export function isSandboxDiskFullText(text: string): boolean { + return /no space left on device|disk quota exceeded|\bENOSPC\b|\bEDQUOT\b/i.test(text); +} + +/** A staging command's failure, keeping a full disk recognizable without its output. */ +export function remoteStagingFailure( + code: string, + result: { stdout?: string; stderr?: string }, +): Error { + return isSandboxDiskFullText(`${result.stderr ?? ""}\n${result.stdout ?? ""}`) + ? Object.assign(new Error(`${code}: no space left on device`), { code: "ENOSPC" }) + : new Error(code); +} + +export function sandboxDiskFullFailure(cause: unknown): Error { + return Object.assign( + new Error(`${SANDBOX_DISK_FULL_FAILURE_CODE}: the sandbox disk is full, so the runner cannot be started`, { cause }), + { code: SANDBOX_DISK_FULL_FAILURE_CODE }, + ); +} + +/** Managed sandboxes only; never on a user's own host. `.paperclip-runtime` is outside every saved directory. */ +export function remoteRunnerDiskReservePath(target: { transport: string; remoteCwd: string }): string | undefined { + return target.transport === "sandbox" + ? `${target.remoteCwd.replace(/\/+$/, "")}/.paperclip-runtime/paperclip-runner/disk-reserve` + : undefined; +} diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 082e22499c8..c9110058ab0 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -197,6 +197,8 @@ export const QUALIFIED_ACPX_PROFILES = runner.QUALIFIED_ACPX_PROFILES; export const QUALIFIED_ACPX_VERSION = runner.QUALIFIED_ACPX_VERSION; export const CURSOR_DISTRIBUTION_PINS = runner.CURSOR_DISTRIBUTION_PINS; export const KIMI_DISTRIBUTION_CLOSURE_SHA256 = runner.KIMI_DISTRIBUTION_CLOSURE_SHA256; +export const SANDBOX_DISK_FULL_FAILURE_CODE = runner.SANDBOX_DISK_FULL_FAILURE_CODE; +export const isSandboxDiskFullFailure = runner.isSandboxDiskFullFailure; export const resolveSourceCodexHome = runner.resolveSourceCodexHome; export const resolveCodexCommand = runner.resolveCodexCommand; export const resolvePinnedCodexCommand = runner.resolvePinnedCodexCommand;