The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(daytona): record provider state when lease creation hits its deadline (#15946)
Devin Foley657e71584a00
diff --git a/doc/observability.md b/doc/observability.mdindex 327f588c51..cb6b75c1af 100644--- a/doc/observability.md+++ b/doc/observability.md@@ -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 ormalformed 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 leaseacquisition. The host accepts them only from an actual RPC error with matchingcompany, environment, and run ownership. A private receipt binds the report todiff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.test.tsindex 98de4492ed..78330ddc3f 100644--- a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts+++ b/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts@@ -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");diff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.tsindex 6813867075..b8e71c2ab8 100644--- a/packages/plugins/sandbox-providers/daytona/src/plugin.ts+++ b/packages/plugins/sandbox-providers/daytona/src/plugin.ts@@ -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 {diff --git a/packages/plugins/sdk/src/environment-creation-cleanup.ts b/packages/plugins/sdk/src/environment-creation-cleanup.tsindex 6328b9ee42..35f23cd19a 100644--- a/packages/plugins/sdk/src/environment-creation-cleanup.ts+++ b/packages/plugins/sdk/src/environment-creation-cleanup.ts@@ -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): PluginEnviconst 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; }}diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.tsindex f361b5c435..98fa405f85 100644--- a/packages/plugins/sdk/src/index.ts+++ b/packages/plugins/sdk/src/index.ts@@ -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";diff --git a/packages/plugins/sdk/tests/environment-creation-cleanup.test.ts b/packages/plugins/sdk/tests/environment-creation-cleanup.test.tsindex 64fa237f43..532a0fa8f2 100644--- a/packages/plugins/sdk/tests/environment-creation-cleanup.test.ts+++ b/packages/plugins/sdk/tests/environment-creation-cleanup.test.ts@@ -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");diff --git a/server/src/services/__tests__/run-failure-diagnostics.test.ts b/server/src/services/__tests__/run-failure-diagnostics.test.tsindex 4a7384c5db..731c569e0e 100644--- a/server/src/services/__tests__/run-failure-diagnostics.test.ts+++ b/server/src/services/__tests__/run-failure-diagnostics.test.ts@@ -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");});diff --git a/server/src/services/run-failure-diagnostics.ts b/server/src/services/run-failure-diagnostics.tsindex 9d2f766269..7a14c7e3d8 100644--- a/server/src/services/run-failure-diagnostics.ts+++ b/server/src/services/run-failure-diagnostics.ts@@ -256,6 +256,7 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReportexecution.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");