fix(daytona): record provider state when lease creation hits its deadline (#15946)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents can run in Daytona sandboxes. The Daytona plugin acquires a
lease before each run.
> - Some acquisitions time out. The report then says
`environmentAcquisitionPhase=create` and that the whole 300 s budget was
used.
> - The Daytona SDK create timeout is equal to the acquisition budget.
The outer timer always fires first. Thus the report never shows the
state that Daytona left the sandbox in.
> - Without that state, we cannot choose a fix. A stuck snapshot pull, a
slow start, and a missing allocation need different fixes.
> - This pull request adds one bounded, read-only provider lookup at the
create deadline. It records a fixed-enum provider state in the existing
acquisition diagnostic.
> - The benefit is that the next timeout identifies where the provider
stopped. Retry, budget, and cleanup behavior do not change.

## Linked Issues or Issue Description

Refs #15736 (bounded Daytona acquisition failure observations). This
pull request extends those observations.

**What happened?**

A Daytona lease acquisition timed out with `Daytona lease acquisition
timed out; allocation cleanup is pending`. The run-failure report gave
`environmentAcquisitionPhase=create`,
`environmentAcquisitionElapsedMs=300004`, and
`environmentAcquisitionBudgetMs=300000`. The report did not show the
Daytona sandbox state. The SDK create timeout is equal to the outer
budget, so the outer timer always fires first. The SDK never reports the
stuck state.

**Expected behavior**

When creation is still pending at the deadline, the report should show
where the provider left the allocation. Examples are `pulling_snapshot`,
`starting`, `error`, or `absent`.

**Steps to reproduce**

1. Configure a Daytona environment.
2. Start a run when Daytona does not finish create and start within the
acquisition budget.
3. Inspect the setup-failure report. Only the phase, the elapsed time,
and the budget are present.

**Paperclip version or commit**

`master` at ba04968.

## What Changed

- `packages/plugins/sdk`: Add an optional `providerState` field to
`PluginEnvironmentAcquisitionDiagnostic`. The values are a fixed enum:
`absent`, `creating`, `pending_build`, `building_snapshot`,
`pulling_snapshot`, `starting`, `started`, `error`, `build_failed`,
`other`, `unavailable`. The reader omits an unknown value and keeps the
other fields. Old envelopes stay valid.
- `packages/plugins/sandbox-providers/daytona`: When the acquisition
deadline fires while `client.create` is still pending, make one
`client.get` of the provisional `paperclip-create-<attempt>` name. The
lookup has a 5 s bound, inside the host's 30 s RPC margin. Report the
state only when the name and all ownership labels match. Otherwise
report `unavailable`. A not-found error reports `absent`.
- The lookup does not delete. It does not set `observedProviderLeaseId`.
It does not change retries, budgets, or the cleanup envelope.
- After the deadline, only the timer settles the call. A late create
result cannot replace the timeout error before the lookup completes. A
test proves this guard.
- `server`: Project the value to
`run_execution.environmentAcquisitionProviderState`. It uses the same
private, run-scoped receipt as the other acquisition fields.
- `doc/observability.md`: Document the new field and its limits.

## Verification

- `cd packages/plugins/sandbox-providers/daytona && npx vitest run
--config vitest.config.ts`: 392 passed, 6 skipped.
- `npx vitest run
packages/plugins/sdk/tests/environment-creation-cleanup.test.ts
server/src/services/__tests__/run-failure-diagnostics.test.ts
server/src/__tests__/environment-acquisition-diagnostics.test.ts
server/src/__tests__/run-failure-sentry-real-sdk.test.ts
server/src/__tests__/environment-runtime.test.ts`: 302 passed, 11
skipped.
- `tsc --noEmit` passes for `packages/plugins/sdk` and
`packages/plugins/sandbox-providers/daytona`.
- New tests cover state mapping, `other` for unlisted states, `absent`,
`unavailable` for lookup failure and label mismatch, a hung lookup
bounded to 5 s, no deletion, an unchanged cleanup envelope, and a late
create that settles during the lookup.
- A mutation check removed the late-settlement guard. The late-create
test then failed.
- The local server `tsc` was killed by the sandbox memory limit. CI must
confirm the server typecheck. The server change is one line.

## Risks

- Low risk. The timeout rejection can come up to 5 s later, and only for
a create-phase deadline. The host RPC margin is 30 s.
- The lookup is one extra read-only Daytona API call for each
create-phase timeout.
- This is a diagnostic. It does not fix the upstream cause. The next
timeout report must show the state before a fix is chosen.
- This is a Sentry run-failure report change. It is not a Telemetry
change. The new value is a fixed enum. It does not contain provider IDs,
causes, URLs, or paths.

> 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

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude
Code with tool use (shell, file edit, test runs). Context window and
reasoning configuration are set by the runtime.

## 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: Devin Foley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-10-11 21:22:39 -07:00
1 parent ba04968b10
commit 657e71584a
8 files changed
+159 -7

No files matched your search

+10
View File
@@ -595,6 +595,16 @@ still describes the earlier failure. The overall error message is unchanged.
Elapsed time is bounded to seven days, and the budget to one day. Unknown or
malformed optional values are omitted without invalidating cleanup ownership.
When the deadline expires while Daytona creation is still pending, the plugin
makes one read-only lookup (bounded to five seconds, inside the host's 30-second
RPC margin) of its provisional creation name and reports
`environmentAcquisitionProviderState`. The value is one of `absent`, `creating`,
`pending_build`, `building_snapshot`, `pulling_snapshot`, `starting`, `started`,
`error`, `build_failed`, `other`, or `unavailable` (lookup failed, timed out, or
ownership labels did not match). It records where the provider left the
allocation, not why. The lookup does not delete, retry, or change the cleanup
envelope.
These fields cross the existing creation-cleanup RPC envelope only for lease
acquisition. The host accepts them only from an actual RPC error with matching
company, environment, and run ownership. A private receipt binds the report to
@@ -569,9 +569,83 @@ describe("Daytona sandbox provider plugin", () => {
}).catch(error => error);
await vi.advanceTimersByTimeAsync(2_000);
const error = await pending;
expect(readEnvironmentAcquisitionDiagnostic(error)).toEqual({ phase, elapsedMs: 2_000, budgetMs: 2_000 });
// The default lookup mock returns no sandbox, so a pending create reports `unavailable`.
expect(readEnvironmentAcquisitionDiagnostic(error)).toEqual({ phase, elapsedMs: 2_000, budgetMs: 2_000,
...(phase === "create" ? { providerState: "unavailable" } : {}) });
expect(error.message).toBe("Daytona lease acquisition timed out; allocation cleanup is pending");
expect(sandbox.delete).not.toHaveBeenCalled();
if (phase !== "create") expect(mockGet).not.toHaveBeenCalled();
});
function ownedCreation(state: string) {
const requested = mockCreate.mock.calls.at(-1)![0];
return { ...createMockSandbox({ state }), name: requested.name, labels: { ...requested.labels } };
}
it.each([
["pulling_snapshot", "pulling_snapshot"], ["starting", "starting"], ["pending_build", "pending_build"],
["error", "error"], ["stopped", "other"], ["11184809", "other"],
])("records provider state %s as %s when creation is still pending at the deadline", async (state, expected) => {
mockCreate.mockImplementation(() => new Promise(() => {}));
let found: ReturnType<typeof ownedCreation> | undefined;
mockGet.mockImplementation(async () => (found = ownedCreation(state)));
const pending = plugin.definition.onEnvironmentAcquireLease!({ ...params, config: { ...params.config, timeoutMs: 2_000 } }).catch(error => error);
await vi.advanceTimersByTimeAsync(2_000);
const error = await pending;
expect(readEnvironmentAcquisitionDiagnostic(error)).toEqual({ phase: "create", elapsedMs: 2_000, budgetMs: 2_000, providerState: expected });
expect(mockGet).toHaveBeenCalledOnce();
expect(mockGet).toHaveBeenCalledWith(mockCreate.mock.calls[0][0].name);
// Read-only: no deletion, and the host-owned cleanup envelope is unchanged.
expect(found!.delete).not.toHaveBeenCalled();
expect(readEnvironmentCreationCleanupError(error)?.observedProviderLeaseId).toBeUndefined();
expect(JSON.stringify(environmentCreationCleanupErrorData(error, true))).not.toContain(found!.id);
});
it.each([
["absent", () => mockGet.mockRejectedValue(new MockDaytonaNotFoundError("private-not-found"))],
["unavailable", () => mockGet.mockRejectedValue(new Error("private-provider-failure"))],
["unavailable", () => mockGet.mockImplementation(async () => {
const foreign = ownedCreation("started"); foreign.labels["paperclip-run-id"] = "foreign-run"; return foreign;
})],
])("records %s when the deadline lookup cannot attribute an allocation", async (expected, arrange) => {
mockCreate.mockImplementation(() => new Promise(() => {}));
arrange();
const pending = plugin.definition.onEnvironmentAcquireLease!({ ...params, config: { ...params.config, timeoutMs: 2_000 } }).catch(error => error);
await vi.advanceTimersByTimeAsync(2_000);
const error = await pending;
expect(readEnvironmentAcquisitionDiagnostic(error)?.providerState).toBe(expected);
expect(JSON.stringify(environmentCreationCleanupErrorData(error, true))).not.toContain("private-");
});
it("bounds a hung deadline lookup well inside the host's RPC margin", async () => {
mockCreate.mockImplementation(() => new Promise(() => {}));
mockGet.mockImplementation(() => new Promise(() => {}));
let settled = false;
const pending = plugin.definition.onEnvironmentAcquireLease!(params).catch(error => { settled = true; return error; });
await vi.advanceTimersByTimeAsync(304_999);
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
const error = await pending;
expect(readEnvironmentAcquisitionDiagnostic(error)).toEqual({ phase: "create", elapsedMs: 300_000, budgetMs: 300_000, providerState: "unavailable" });
expect(error.message).toBe("Daytona lease acquisition timed out; allocation cleanup is pending");
});
it("keeps the timeout result when a late create settles during the deadline lookup", async () => {
const sandbox = createMockSandbox();
mockCreate.mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(sandbox), 2_500)));
mockGet.mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(ownedCreation("starting")), 4_000)));
let settled = false;
const pending = plugin.definition.onEnvironmentAcquireLease!({ ...params, config: { ...params.config, timeoutMs: 2_000 } })
.catch(error => { settled = true; return error; });
// The host serializes the error on settlement; it must wait for the lookup.
await vi.advanceTimersByTimeAsync(3_000);
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(3_000);
const error = await pending;
expect(readEnvironmentAcquisitionDiagnostic(error)).toEqual({ phase: "create", elapsedMs: 2_000, budgetMs: 2_000, providerState: "starting" });
expect(readEnvironmentCreationCleanupError(error)?.providerLeaseId).toBe(mockCreate.mock.calls[0][0].name);
expect(sandbox.getWorkDir).not.toHaveBeenCalled();
expect(sandbox.delete).not.toHaveBeenCalled();
});
it.each(["create", "workspace"] as const)("keeps the original %s observation when cleanup consumes the remaining deadline", async phase => {
@@ -598,7 +672,7 @@ describe("Daytona sandbox provider plugin", () => {
await vi.advanceTimersByTimeAsync(100);
const second = plugin.definition.onEnvironmentAcquireLease!({ ...params, config: { ...params.config, timeoutMs: 3_000 } }).catch(error => error);
await vi.advanceTimersByTimeAsync(3_000);
expect(readEnvironmentAcquisitionDiagnostic(await first)).toEqual({ phase: "create", elapsedMs: 2_000, budgetMs: 2_000 });
expect(readEnvironmentAcquisitionDiagnostic(await first)).toEqual({ phase: "create", elapsedMs: 2_000, budgetMs: 2_000, providerState: "unavailable" });
expect(readEnvironmentAcquisitionDiagnostic(await second)).toEqual({ phase: "workspace", elapsedMs: 3_000, budgetMs: 3_000 });
mockCreate.mockResolvedValue(createMockSandbox());
expect(await plugin.definition.onEnvironmentAcquireLease!(params)).not.toHaveProperty("acquisitionDiagnostic");
@@ -14,6 +14,7 @@ import type {
PluginContext,
PluginEnvironmentCreationCleanup,
PluginEnvironmentAcquisitionDiagnostic,
PluginEnvironmentAcquisitionProviderState,
PluginTracer,
PluginEnvironmentAcquireLeaseParams,
PluginEnvironmentCancelInteractiveSetupParams,
@@ -1045,6 +1046,28 @@ async function destroyFailedCreation(
await withLivenessTimeout("sandbox.failedCreateDelete", 15_000, () => orphan.delete(10, true));
}
// Daytona states reported as-is after a create deadline; any other is `other`.
const REPORTED_CREATE_STATES = new Set<string>([
"creating", "pending_build", "building_snapshot", "pulling_snapshot", "starting", "started", "error", "build_failed",
] satisfies PluginEnvironmentAcquisitionProviderState[]);
// One read-only lookup of the provisional creation name, so a create deadline
// records where the provider left the allocation. It neither deletes nor
// records an observed ID: the host-owned cleanup envelope is unchanged.
async function observeCreateState(
config: DaytonaDriverConfig, cleanup: PluginEnvironmentCreationCleanup,
): Promise<PluginEnvironmentAcquisitionProviderState> {
try {
const sandbox = await withLivenessTimeout("sandbox.createStateLookup", 5_000,
() => createDaytonaClient(config).get(cleanup.providerLeaseId));
if (!sandbox || sandbox.name !== cleanup.providerLeaseId || typeof sandbox.state !== "string" ||
Object.entries(cleanup.labels).some(([key, value]) => sandbox.labels?.[key] !== value)) return "unavailable";
return REPORTED_CREATE_STATES.has(sandbox.state) ? sandbox.state as PluginEnvironmentAcquisitionProviderState : "other";
} catch (error) {
return error instanceof DaytonaNotFoundError ? "absent" : "unavailable";
}
}
// ─── Per-lease started-sandbox handle cache ──────────────────────────────────
// Memoize the started Daytona `Sandbox` handle so repeated exec/sync/resume/
// teardown calls on one lease skip the per-call `client.get(sandboxId)` REST
@@ -2500,6 +2523,15 @@ const plugin = definePlugin({
const assertActive = () => {
if (expired || Date.now() >= deadline) throw timeoutFailure();
};
const deadlineFailure = async () => {
// Only a create that has neither resolved nor rejected is still pending.
const createPending = phase === "create" && firstFailure === undefined ? cleanup : undefined;
const diagnostic = observeFailure();
// Stop late setup before the lookup, so a late create cannot be admitted.
expired = true;
if (createPending) diagnostic.providerState = await observeCreateState(config, createPending);
return timeoutFailure();
};
const acquire = async (): Promise<PluginEnvironmentLease> => {
const sandbox = await createSandbox(params, config, {
onCreateAttempt: (attempt) => { cleanup = attempt; },
@@ -2586,11 +2618,14 @@ const plugin = definePlugin({
}
};
let timer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
try {
return await Promise.race([
acquire(),
// After the deadline only the timer settles the call: a late create
// rejection cannot replace the timeout's ownership and observation.
acquire().catch((error: unknown) => timedOut ? new Promise<never>(() => undefined) : Promise.reject(error)),
new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(timeoutFailure()), budgetMs);
timer = setTimeout(() => { timedOut = true; void deadlineFailure().then(reject); }, budgetMs);
}),
]);
} finally {
@@ -19,8 +19,19 @@ export interface PluginEnvironmentAcquisitionDiagnostic {
/** Milliseconds from acquisition start to the first failure, before cleanup. */
elapsedMs: number;
budgetMs: number;
/**
* Provider state of the provisional allocation, observed once after a create
* deadline. Only a fixed set of states is reported; it is not the cause.
*/
providerState?: PluginEnvironmentAcquisitionProviderState;
}
export const ENVIRONMENT_ACQUISITION_PROVIDER_STATES = [
"absent", "creating", "pending_build", "building_snapshot", "pulling_snapshot",
"starting", "started", "error", "build_failed", "other", "unavailable",
] as const;
export type PluginEnvironmentAcquisitionProviderState = typeof ENVIRONMENT_ACQUISITION_PROVIDER_STATES[number];
export function readEnvironmentAcquisitionDiagnostic(error: unknown): PluginEnvironmentAcquisitionDiagnostic | null {
try {
// Diagnostics never make an invalid ownership envelope usable for cleanup.
@@ -33,10 +44,14 @@ export function readEnvironmentAcquisitionDiagnostic(error: unknown): PluginEnvi
const phase = fields.phase?.value;
const elapsedMs = fields.elapsedMs?.value;
const budgetMs = fields.budgetMs?.value;
const providerState = fields.providerState?.value;
if (!["create", "workspace", "shell", "expiry", "sentinel"].includes(phase as string) ||
typeof elapsedMs !== "number" || !Number.isSafeInteger(elapsedMs) || elapsedMs < 0 || elapsedMs > 604_800_000 ||
typeof budgetMs !== "number" || !Number.isSafeInteger(budgetMs) || budgetMs < 1 || budgetMs > 86_400_000) return null;
return { phase: phase as PluginEnvironmentAcquisitionDiagnostic["phase"], elapsedMs, budgetMs };
// An unknown optional state is omitted; it never invalidates the observation.
const knownState = ENVIRONMENT_ACQUISITION_PROVIDER_STATES.find(value => value === providerState);
return { phase: phase as PluginEnvironmentAcquisitionDiagnostic["phase"], elapsedMs, budgetMs,
...(knownState ? { providerState: knownState } : {}) };
} catch { return null; }
}
+2 -2
View File
@@ -450,8 +450,8 @@ export {
PRINCIPAL_TYPES,
} from "@paperclipai/shared";
export { PluginEnvironmentCreationCleanupError, environmentCreationCleanupErrorData, readEnvironmentCreationCleanupError, readEnvironmentAcquisitionDiagnostic } from "./environment-creation-cleanup.js";
export type { PluginEnvironmentCreationCleanup, PluginEnvironmentAcquisitionDiagnostic } from "./environment-creation-cleanup.js";
export { PluginEnvironmentCreationCleanupError, environmentCreationCleanupErrorData, readEnvironmentCreationCleanupError, readEnvironmentAcquisitionDiagnostic, ENVIRONMENT_ACQUISITION_PROVIDER_STATES } from "./environment-creation-cleanup.js";
export type { PluginEnvironmentCreationCleanup, PluginEnvironmentAcquisitionDiagnostic, PluginEnvironmentAcquisitionProviderState } from "./environment-creation-cleanup.js";
export { preserveEnvironmentSyncErrorDiagnostic, environmentSyncErrorData, readEnvironmentSyncErrorDiagnostic, withEnvironmentSyncErrorCapture, withEnvironmentSyncTransferStep, recordEnvironmentSyncError } from "./environment-sync-error.js";
export type { PluginEnvironmentSyncErrorDiagnostic } from "./environment-sync-error.js";
@@ -92,6 +92,20 @@ describe("acquisition failure observations", () => {
expect(readEnvironmentAcquisitionDiagnostic({ data: { schema, cleanup: ownership } })).toBeNull();
});
it("carries a fixed-enum provider state and omits unknown or private states", async () => {
const withState = { ...diagnostic, phase: "create", providerState: "pulling_snapshot" } as const;
const response = await invoke("environmentAcquireLease", new PluginEnvironmentCreationCleanupError([], "Cleanup required", ownership, withState));
if (!("error" in response) || !response.error) throw new Error("Expected RPC error");
expect(readEnvironmentAcquisitionDiagnostic(new JsonRpcCallError(response.error))).toEqual(withState);
for (const providerState of ["private-state", "STARTED", 3, null]) {
const error = new PluginEnvironmentCreationCleanupError([], "Cleanup required", ownership,
{ ...withState, providerState } as unknown as typeof withState);
// An unrecognized optional state never invalidates the other observations.
expect(readEnvironmentAcquisitionDiagnostic(error)).toEqual({ ...diagnostic, phase: "create" });
expect(JSON.stringify(environmentCreationCleanupErrorData(error, true))).not.toContain("private-");
}
});
it.each(["environmentDestroyLease", "environmentProbe"])("omits acquisition diagnostics from %s", async method => {
const response = await invoke(method, new PluginEnvironmentCreationCleanupError([], "Cleanup required", ownership, diagnostic));
expect("error" in response && response.error).not.toHaveProperty("data.acquisitionDiagnostic");
@@ -24,6 +24,9 @@ describe("run failure diagnostics", () => {
expect(collectSetup(error, run({ ...fixture, errorCode: "adapter_failed" }))).not.toHaveProperty("environmentAcquisitionPhase");
expect(collectRunFailureDiagnostics(fixture, { error, phase: "execute" }).execution).not.toHaveProperty("environmentAcquisitionPhase");
expect(Object.getOwnPropertyDescriptors(error)).toEqual(properties);
expect(collectSetup(error)).not.toHaveProperty("environmentAcquisitionProviderState");
captureEnvironmentAcquisitionDiagnostic(error, scope, { phase: "create", elapsedMs: 2_000, budgetMs: 2_000, providerState: "pulling_snapshot" });
expect(collectSetup(error)).toMatchObject({ environmentAcquisitionPhase: "create", environmentAcquisitionProviderState: "pulling_snapshot" });
captureEnvironmentAcquisitionDiagnostic(error, scope, null);
expect(collectSetup(error)).not.toHaveProperty("environmentAcquisitionPhase");
});
@@ -256,6 +256,7 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReport
execution.environmentAcquisitionPhase = acquisition.phase;
execution.environmentAcquisitionElapsedMs = acquisition.elapsedMs;
execution.environmentAcquisitionBudgetMs = acquisition.budgetMs;
if (acquisition.providerState) execution.environmentAcquisitionProviderState = acquisition.providerState;
}
if (execution.restoreLockOwnerState === undefined && read(error, "code") === "ERR_WORKSPACE_RESTORE_LOCK_TIMEOUT") {
const lock = read(error, "workspaceRestoreLock");