Files
PaperClipAI/server/src/services/environment-provider-unavailable-error.test.ts
T
DottaandClaude Opus 5.5 f0bd99ba8a fix(recovery): wait out a sandbox the provider could not start, with no Retry (#22194)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task that runs in a sandbox environment first gets a lease from
the environment provider (for example Daytona)
> - Sometimes the provider creates the sandbox but cannot start it.
Daytona then puts the sandbox in its `error` state
> - The Daytona plugin deletes that failed sandbox and rethrows the
provider error. The error has no HTTP status and no errno, so the host
cannot tell that it is a provider-side failure
> - The run fails with `setup_failed`, and the task rests on "Retry when
ready". No agent work had started, and a fresh sandbox works, so a
person must click Retry for something the system can do itself
> - Recovery must just work, and the target for runs that need Retry is
0%
> - This pull request makes the plugin report a removed sandbox that the
provider could not start as structured evidence (the step and the
provider state). The host classifies it as a transient provider failure.
The task then uses the existing bounded retries and the provider-outage
wait from #22139
> - The benefit is that a provider start failure delays the task by
seconds instead of stranding it on Retry

## Linked Issues or Issue Description

Refs #22139 (the provider-outage wait lane that this failure now
reaches). Refs #22128 (setup failure after work; this failure happens
before any work, so that path did not apply).

**What happened?**
In a restart-chaos wave with graceful release swaps on 2026-11-18, two
tasks started a run at 14:51:15Z and 14:51:24Z. Both runs failed at
14:51:53Z with `setup_failed` and `failureCause: lease_acquire_failed`.
The cause was `Sandbox <id> failed to start with status: error, error
reason: null` from the Daytona SDK, for two different sandboxes at the
same moment. Both tasks rested on Retry. A Retry click started each task
again, and both tasks completed.

**Expected behavior**
A sandbox that the provider cannot start is a provider failure before
any agent work. Paperclip deletes it and tries again with a new sandbox,
with no Retry. If the provider keeps failing, the task waits for the
provider without a Retry, and a person gets a working Retry only after
the 30-minute ceiling.

**Steps to reproduce**
1. Make the Daytona create call fail while the new sandbox is in the
provider's `error` state.
2. Assign a task to an agent that uses that environment.
3. The run fails with `setup_failed`, and the task rests on Retry.

## What Changed

- Plugin SDK (`environment-creation-cleanup.ts`,
`environment-acquire-error.ts`, `index.ts`): new
`PluginEnvironmentAcquisitionError`. It carries the acquisition
diagnostic (step, elapsed time, budget, provider state) for a failed
allocation that the provider already removed, with no cleanup envelope.
The acquire RPC error data (`paperclip/environment-acquire-error/v1`)
now carries this diagnostic. `readEnvironmentAcquisitionDiagnostic`
reads it from that envelope. The existing cleanup envelope path is
unchanged. No provider text crosses the RPC.
- Daytona plugin (`plugin.ts`): `destroyFailedCreation` returns the
state of the sandbox that it deleted. When a create fails without an
HTTP status and the deleted sandbox was in the `error` state, the plugin
throws `PluginEnvironmentAcquisitionError` with `providerState:
"error"`. A `build_failed` sandbox (a deterministic snapshot build
failure) and any other state keep the original error.
- Server (`environment-runtime.ts`): the acquire path records the
diagnostic for this run also when the error has no cleanup envelope. A
cleanup envelope for another run, company or environment still records
nothing.
- Server (`environment-provider-unavailable-error.ts`): an acquisition
diagnostic with `providerState: "error"` is the transient reason
`provider_start_failed` ("the provider could not start the sandbox"). It
becomes `EnvironmentProviderUnavailableError`, so the run uses the two
bounded retries and then the provider-outage wait lane (one probe per
environment, 30-minute ceiling).
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for
the changed SDK sources (generated by `node
tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --write`).

Module boundaries: the change to the shared SDK contract is additive.
The Daytona plugin owns the provider state. The host reads only the
closed diagnostic fields. A plugin that does not use the new class
behaves as before.

## Verification

- `packages/plugins/sandbox-providers/daytona`: `npx vitest run
src/plugin.test.ts -t "failed sandbox creation cleanup"` (37 passed).
New: "reports a sandbox that failed to start as a removed allocation
with its observed step" (red before the plugin change, green after) and
"keeps the create error when the removed sandbox was build_failed /
started".
- `packages/plugins/sdk`: `npx vitest run
tests/environment-acquire-error.test.ts
tests/environment-creation-cleanup.test.ts` (50 passed). New: the
diagnostic crosses the real worker RPC without provider text, and forged
or unstructured envelopes give no diagnostic.
- `server`: `npx vitest run
src/services/environment-provider-unavailable-error.test.ts
src/__tests__/environment-acquisition-diagnostics.test.ts` (74 passed).
New: the reason is `provider_start_failed` with a transient provider
failure, and a diagnostic that was not recorded for this run is not
retried.
- `server`: `npx vitest run src/__tests__/environment-runtime.test.ts -t
"provider could not start|retains uncertain plugin creation"` (12
passed). New: "records the step of a sandbox the provider could not
start and removed" for a worker error (red before the runtime change,
green after) and for a forged error (not recorded).
- `server`: `npx vitest run
src/services/__tests__/run-failure-diagnostics.test.ts
src/__tests__/heartbeat-process-recovery.test.ts -t
"provider|acquisition|diagnostic"` (167 passed).
- Typecheck: `server` `tsc --noEmit`, `pnpm run typecheck` in
`packages/plugins/sdk` and in the Daytona plugin all pass.
- `pnpm verify` exits 2 (the SDK input registry is a global CI input).
Required CI supplies the broad coverage.

## Risks

- **Automatic retries for a deterministic start failure.** If a provider
image or configuration made every sandbox go to `error`, the task now
waits in the provider-outage lane instead of resting on Retry at once.
The lane uses one probe per environment on a 1, 2, then 5 minute
backoff, and it hands the task to a person with a working Retry after 30
minutes. The aggregate automatic-run brake is unchanged. `build_failed`
is not retried by this change.
- **Shared SDK contract.** The new field is additive. An older host
ignores it, and the run fails as before.
- No database migration. No UI change.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used in
Claude Code with tool use (shell, file edits) and extended reasoning.

## 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
- [x] All Paperclip CI gates are green
- [x] 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 <noreply@anthropic.com>
2026-11-18 11:47:33 -06:00

241 lines
13 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { isRetryableEnvironmentErrorCode, JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, readEnvironmentAcquisitionDiagnostic } from "@paperclipai/plugin-sdk";
import { captureEnvironmentAcquisitionDiagnostic } from "./environment-acquisition-diagnostics.js";
import {
EnvironmentProviderUnavailableError,
findEnvironmentProviderUnavailableError,
readTransientEnvironmentProviderFailure,
readTransientLeaseAcquisitionFailure,
} from "./environment-provider-unavailable-error.js";
function withStatus(status: number, key: "status" | "statusCode" = "status") {
return Object.assign(new Error("provider refused"), { [key]: status });
}
describe("readTransientEnvironmentProviderFailure", () => {
it.each([408, 425, 429, 500, 502, 503, 504, 520, 524, 529, 599])("treats HTTP %i as transient", (status) => {
expect(readTransientEnvironmentProviderFailure(withStatus(status))).toEqual({ httpStatus: status });
});
it("reads statusCode as well as status", () => {
expect(readTransientEnvironmentProviderFailure(withStatus(503, "statusCode"))).toEqual({ httpStatus: 503 });
});
it.each(["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE", "EAI_AGAIN", "ENETUNREACH",
"UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", "CONNECTION_FAILED"])("treats errno %s as transient", (code) => {
expect(readTransientEnvironmentProviderFailure(Object.assign(new Error("closed"), { code })))
.toEqual({ errorCode: code });
});
it.each(["ENOTFOUND", "ABORT_ERR", "EACCES"])("does not retry errno %s", (code) => {
expect(readTransientEnvironmentProviderFailure(Object.assign(new Error("x"), { code }))).toBeNull();
});
it.each([
["ENOTFOUND", false, true],
["EAI_AGAIN", true, true],
["ABORT_ERR", false, false],
["EACCES", false, false],
] as const)("scopes errno %s: first acquisition %s, reattach to a reached host %s", (code, acquisition, reattach) => {
expect(isRetryableEnvironmentErrorCode(code)).toBe(acquisition);
expect(isRetryableEnvironmentErrorCode(code, "first_acquisition")).toBe(acquisition);
expect(isRetryableEnvironmentErrorCode(code, "known_host")).toBe(reattach);
});
it.each([400, 401, 403, 404, 409, 422, 501, 505])("does not retry HTTP %i", (status) => {
expect(readTransientEnvironmentProviderFailure(withStatus(status))).toBeNull();
});
it("finds transient evidence on a wrapped cause", () => {
const wrapped = new Error("outer", { cause: new Error("middle", { cause: withStatus(502) }) });
expect(readTransientEnvironmentProviderFailure(wrapped)).toEqual({ httpStatus: 502 });
});
it("stops at a definite non-transient status instead of reading deeper causes", () => {
const outer = Object.assign(new Error("bad request", { cause: withStatus(503) }), { status: 400 });
expect(readTransientEnvironmentProviderFailure(outer)).toBeNull();
});
it("reads the validated plugin RPC envelope", () => {
const rpcError = Object.assign(new Error("rpc failed"), {
data: { schema: "paperclip/environment-acquire-error/v1", providerDiagnostic: { httpStatus: 429 } },
});
expect(readTransientEnvironmentProviderFailure(rpcError)).toEqual({ httpStatus: 429 });
});
const stagingLeaseTimeout = (diagnostic: { phase: string; elapsedMs: number; budgetMs: number; providerState?: string }) =>
Object.assign(new Error("Daytona lease acquisition timed out; allocation cleanup is pending"), {
data: { schema: "paperclip/environment-creation-cleanup/v1",
cleanup: { providerLeaseId: "paperclip-create-05f81d77", companyId: "company", environmentId: "environment",
runId: "f41857b6", attemptId: "05f81d77", accountFingerprint: "a".repeat(64),
labels: { "paperclip-provider": "daytona", "paperclip-create-attempt": "05f81d77" } },
acquisitionDiagnostic: diagnostic },
});
it("treats an acquisition that reached its deadline as transient", () => {
const timeout = stagingLeaseTimeout({ phase: "create", elapsedMs: 300_004, budgetMs: 300_000, providerState: "creating" });
expect(readTransientEnvironmentProviderFailure(new Error("outer", { cause: timeout }))).toEqual({ acquisitionTimedOut: true });
});
it("does not retry an acquisition whose first failure came before its deadline", () => {
expect(readTransientEnvironmentProviderFailure(stagingLeaseTimeout({ phase: "workspace", elapsedMs: 100, budgetMs: 300_000 }))).toBeNull();
});
it("never parses message text", () => {
expect(readTransientEnvironmentProviderFailure(new Error("HTTP 502 Bad Gateway ECONNRESET"))).toBeNull();
});
});
describe("EnvironmentProviderUnavailableError", () => {
it.each([
[{ httpStatus: 429 }, "rate_limit"],
[{ httpStatus: 408 }, "timeout"],
[{ httpStatus: 504 }, "timeout"],
[{ errorCode: "ETIMEDOUT" }, "timeout"],
[{ httpStatus: 502 }, "overloaded"],
[{ errorCode: "ECONNRESET" }, "overloaded"],
] as const)("classifies %o as %s", (evidence, category) => {
const error = new EnvironmentProviderUnavailableError({
environmentName: "env", driver: "daytona", evidence, cause: null,
});
expect(error.providerFailure.category).toBe(category);
expect(error.providerFailure.retryability).toBe("transient");
});
it("names an acquisition timeout in plain words", () => {
const error = new EnvironmentProviderUnavailableError({
environmentName: "Paperclip Sandbox", driver: "sandbox", evidence: { acquisitionTimedOut: true }, cause: null,
});
expect(error.providerFailure).toMatchObject({ category: "timeout", retryability: "transient", phase: "startup" });
expect(error.providerFailure.message).toContain("did not finish starting");
expect(error.providerFailure.message).not.toMatch(/ETIMEDOUT|undefined/);
});
it("falls back to a generic provider label for an unsafe driver key", () => {
const error = new EnvironmentProviderUnavailableError({
environmentName: "env", driver: "bad driver <x>", evidence: { httpStatus: 502 }, cause: null,
});
expect(error.providerFailure.provider).toBe("environment");
});
it("is found through wrapper causes", () => {
const inner = new EnvironmentProviderUnavailableError({
environmentName: "env", driver: "ssh", evidence: { errorCode: "ECONNREFUSED" }, cause: null,
});
expect(findEnvironmentProviderUnavailableError(new Error("outer", { cause: inner }))).toBe(inner);
expect(findEnvironmentProviderUnavailableError(new Error("plain"))).toBeNull();
});
});
describe("readTransientLeaseAcquisitionFailure", () => {
const run = { id: "run-1", companyId: "company-1" };
const creationFailure = (elapsedMs: number, runId = run.id) => {
const error = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR,
message: "Daytona lease acquisition timed out; allocation cleanup is pending",
data: { schema: "paperclip/environment-creation-cleanup/v1",
cleanup: { providerLeaseId: "paperclip-create-1", companyId: run.companyId, environmentId: "env-1", runId,
attemptId: "attempt-1", accountFingerprint: "a".repeat(64), labels: {} },
acquisitionDiagnostic: { phase: "create", elapsedMs, budgetMs: 300_000 } } });
captureEnvironmentAcquisitionDiagnostic(error, { companyId: run.companyId, environmentId: "env-1", runId },
readEnvironmentAcquisitionDiagnostic(error));
return error;
};
it("keeps the provider's transient status", () => {
expect(readTransientLeaseAcquisitionFailure(withStatus(503), run)).toEqual({ httpStatus: 503 });
});
it("retries a creation that hit the acquisition deadline", () => {
expect(readTransientLeaseAcquisitionFailure(new Error("wrapped", { cause: creationFailure(300_000) }), run))
.toEqual({ acquisitionTimedOut: true });
});
it("retries a provisional creation that did not finish", () => {
expect(readTransientLeaseAcquisitionFailure(creationFailure(12_000), run)).toEqual({ reason: "acquisition_incomplete" });
});
it("retries a sandbox the provider could not start and already removed", () => {
const error = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR,
message: "Daytona could not start the sandbox; it was removed.",
data: { schema: "paperclip/environment-acquire-error/v1",
acquisitionDiagnostic: { phase: "create", elapsedMs: 38_000, budgetMs: 90_000, providerState: "error" } } });
captureEnvironmentAcquisitionDiagnostic(error, { companyId: run.companyId, environmentId: "env-1", runId: run.id },
readEnvironmentAcquisitionDiagnostic(error));
expect(readTransientLeaseAcquisitionFailure(new Error("lease", { cause: error }), run)).toEqual({ reason: "provider_start_failed" });
const unavailable = new EnvironmentProviderUnavailableError({ environmentName: "Daytona warm", driver: "sandbox",
evidence: { reason: "provider_start_failed" }, cause: error });
expect(unavailable.providerFailure).toMatchObject({ retryability: "transient", providerCode: "provider_start_failed" });
expect(unavailable.message).toContain("the provider could not start the sandbox");
});
it("names a later-step failure an unfinished acquisition, not a start failure", () => {
const error = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, message: "x",
data: { schema: "paperclip/environment-acquire-error/v1",
acquisitionDiagnostic: { phase: "shell", elapsedMs: 38_000, budgetMs: 90_000, providerState: "error" } } });
captureEnvironmentAcquisitionDiagnostic(error, { companyId: run.companyId, environmentId: "env-1", runId: run.id },
readEnvironmentAcquisitionDiagnostic(error));
expect(readTransientLeaseAcquisitionFailure(error, run)).toEqual({ reason: "acquisition_incomplete" });
});
it("does not retry a removed sandbox whose step was never recorded for this run", () => {
const error = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, message: "x",
data: { schema: "paperclip/environment-acquire-error/v1",
acquisitionDiagnostic: { phase: "create", elapsedMs: 38_000, budgetMs: 90_000, providerState: "error" } } });
expect(readTransientLeaseAcquisitionFailure(error, run)).toBeNull();
});
it("ignores an unfinished-creation diagnostic recorded for another run", () => {
expect(readTransientLeaseAcquisitionFailure(creationFailure(12_000, "run-2"), run)).toBeNull();
});
it("retries a plugin RPC deadline", () => {
const timeout = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.TIMEOUT, message: "RPC call timed out" });
expect(readTransientLeaseAcquisitionFailure(timeout, run)).toEqual({ acquisitionTimedOut: true });
});
const pg = (code: string) => Object.assign(new Error("database error"), { name: "PostgresError", code });
it.each([
["a terminated connection", pg("57P01")],
["a connection failure", pg("08006")],
["too many connections", pg("53300")],
["a lock timeout", pg("55P03")],
["a closed connection", Object.assign(new Error("closed"), { code: "CONNECTION_CLOSED" })],
["a Drizzle wrapper around a statement timeout", new Error("Failed query: select 1\nparams: ", { cause: pg("57014") })],
])("retries %s while recording the lease", (_label, cause) => {
expect(readTransientLeaseAcquisitionFailure(new Error("lease", { cause }), run)).toEqual({ reason: "database_error" });
});
it.each([
["a unique violation", pg("23505")],
["an undefined column", pg("42703")],
["a Drizzle wrapper around a syntax error", new Error("Failed query: select\nparams: ", { cause: pg("42601") })],
["a bare Drizzle wrapper", new Error("Failed query: select 1\nparams: ")],
["an errno that looks like a SQLSTATE", Object.assign(new Error("x"), { code: "EPERM" })],
])("does not retry %s", (_label, cause) => {
expect(readTransientLeaseAcquisitionFailure(new Error("lease", { cause }), run)).toBeNull();
});
it("does not retry a definite non-transient status, even with other evidence", () => {
const refused = Object.assign(new Error("unauthorized", { cause: creationFailure(300_000) }), { status: 401 });
expect(readTransientLeaseAcquisitionFailure(refused, run)).toBeNull();
});
it("retries a provider connection failure reported across the worker RPC", () => {
const rpcError = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, message: "read EADDRNOTAVAIL",
data: { schema: "paperclip/environment-acquire-error/v1", providerDiagnostic: { errorCode: "CONNECTION_FAILED" } } });
expect(readTransientLeaseAcquisitionFailure(new Error("lease", { cause: rpcError }), run))
.toEqual({ errorCode: "CONNECTION_FAILED" });
});
it("does not retry an error without structured evidence", () => {
expect(readTransientLeaseAcquisitionFailure(new Error("Daytona lease acquisition timed out"), run)).toBeNull();
});
it("names the reason in the board-facing failure", () => {
const error = new EnvironmentProviderUnavailableError({ environmentName: "Sandbox", driver: "daytona",
evidence: { reason: "database_error" }, cause: null });
expect(error.providerFailure).toMatchObject({ category: "overloaded", providerCode: "database_error" });
expect(error.message).toContain("a database query failed while recording the lease");
});
});