Skip to content
24 changes: 5 additions & 19 deletions src/lib/actions/sandbox/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import {
import { preflightVllmModelEnvOrExit } from "./connect-vllm-preflight";
import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier";
import {
createSandboxStartErrorGrace,
ensureLiveSandboxOrExit,
buildHermesPortableCommandAuthority,
defaultPortableDemoStateDir,
Expand Down Expand Up @@ -1979,16 +1980,6 @@ type WaitForSandboxReadyOptions = {
successLogs?: readonly string[];
};

// OpenShell can transiently publish `Error` immediately after `sandbox start`
// before the same sandbox advances through `Provisioning` to `Ready`. Its list
// output exposes no structured transition reason. A caller opts into twenty
// three-second grace polls only after it starts the container; every other
// terminal phase still fails immediately, and a persistent Error fails after
// the bound. Remove this compatibility exception once OpenShell exposes a
// structured restart signal or guarantees that post-start recovery never emits
// the terminal Error phase.
const START_INITIAL_ERROR_GRACE_POLLS = 20;

// Readiness budget for the repair paths that wait for a restarted sandbox
// before they touch in-sandbox processes or host forwards. A cold agent boot on
// a constrained host can exceed the interactive budget, and `start` and
Expand Down Expand Up @@ -2050,9 +2041,9 @@ export async function waitForSandboxReadyOrExit(
if (status && /^unknown$/i.test(status)) {
await failIfGatewayBlocksConnectReadiness(sandboxName);
}
let remainingInitialErrorGracePolls =
allowInitialErrorAfterStart && status === "Error" ? START_INITIAL_ERROR_GRACE_POLLS - 1 : 0;
if (status && TERMINAL_SANDBOX_PHASES.has(status) && remainingInitialErrorGracePolls === 0) {
const allowInitialError = createSandboxStartErrorGrace(allowInitialErrorAfterStart);
const initialErrorAllowed = allowInitialError(status);
if (status && TERMINAL_SANDBOX_PHASES.has(status) && !initialErrorAllowed) {
failConnectReadinessTerminalPhase(sandboxName, `is in '${status}'`, {
inspectDockerIdentity: allowDockerRuntimeInspection,
retryCommand,
Expand Down Expand Up @@ -2083,12 +2074,7 @@ export async function waitForSandboxReadyOrExit(
await failIfGatewayBlocksConnectReadiness(sandboxName);
}
if (cur !== "unknown") everSeen = true;
const waitingThroughInitialError = cur === "Error" && remainingInitialErrorGracePolls > 0;
if (waitingThroughInitialError) {
remainingInitialErrorGracePolls -= 1;
} else {
remainingInitialErrorGracePolls = 0;
}
const waitingThroughInitialError = allowInitialError(cur);
if (TERMINAL_SANDBOX_PHASES.has(cur) && !waitingThroughInitialError) {
failConnectReadinessTerminalPhase(sandboxName, `entered '${cur}'`, {
inspectDockerIdentity: allowDockerRuntimeInspection,
Expand Down
1 change: 1 addition & 0 deletions src/lib/actions/sandbox/gateway-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
TERMINAL_SANDBOX_PHASES,
} from "../../state/gateway";
export { isTerminalSandboxPhase, sandboxPhaseNeedsLifecycleStart, TERMINAL_SANDBOX_PHASES };
export { createSandboxStartErrorGrace } from "../../domain/lifecycle/sandbox-start-error-grace";
import { selectNamedGateway, selectSandboxOwningGateway } from "./gateway-select";
import {
gatewayNamePattern,
Expand Down
24 changes: 15 additions & 9 deletions src/lib/actions/sandbox/start-wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,23 @@ describe("sandbox start readiness", () => {
expect(harness.captureOpenshellSpy).toHaveBeenCalledTimes(3);
});

it("waits through the next OpenShell health reconciliation after a slow restart (#9485)", async () => {
const harness = createConnectHarness({
listOutputs: [...Array.from({ length: 11 }, () => "alpha Error"), "alpha Ready"],
});
it.each([11, 20])(
"waits through %s initial Error observations after a slow restart (#9485)",
async (errorObservations) => {
const harness = createConnectHarness({
listOutputs: [
...Array.from({ length: errorObservations }, () => "alpha Error"),
"alpha Ready",
],
});

await expect(
harness.waitForSandboxReadyOrExit("alpha", { allowInitialErrorAfterStart: true }),
).resolves.toBeUndefined();
await expect(
harness.waitForSandboxReadyOrExit("alpha", { allowInitialErrorAfterStart: true }),
).resolves.toBeUndefined();

expect(harness.captureOpenshellSpy).toHaveBeenCalledTimes(12);
});
expect(harness.captureOpenshellSpy).toHaveBeenCalledTimes(errorObservations + 1);
},
);

it("fails after the stopped sandbox Error phase remains terminal (#9753)", async () => {
const harness = createConnectHarness({
Expand Down
142 changes: 125 additions & 17 deletions src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,31 @@ function harness() {
const response = { sandbox: { metadata: { id: sandboxId } } };
const startSandbox = vi.fn(async () => response);
const stopSandbox = vi.fn(async () => response);
const get = vi.fn(async () => ({ id: sandboxId, phase: "stopped" }));
const get = vi.fn(async () => ({ id: sandboxId, phase: "ready" }));
const waitReady = vi.fn(async () => ({ id: sandboxId, phase: "ready" }));
const connect = vi.fn(async () => ({
raw: { startSandbox, stopSandbox },
sandbox: { get, waitReady },
}));
const lifecycle = createSdkOpenShellSandboxStateLifecycle({ connect });
return { connect, get, lifecycle, startSandbox, stopSandbox, waitReady };
const waitForStartPoll = vi.fn(async () => undefined);
const lifecycle = createSdkOpenShellSandboxStateLifecycle({ connect, waitForStartPoll });
return { connect, get, lifecycle, startSandbox, stopSandbox, waitForStartPoll, waitReady };
}

describe("OpenShell SDK sandbox lifecycle", () => {
it("starts and stops the named sandbox through typed SDK RPCs", async () => {
const { connect, get, lifecycle, startSandbox, stopSandbox, waitReady } = harness();
const { connect, get, lifecycle, startSandbox, stopSandbox } = harness();

await expect(lifecycle.startSandbox(request)).resolves.toEqual({
kind: "accepted",
});
get.mockResolvedValue({ id: sandboxId, phase: "stopped" });
await expect(lifecycle.stopSandbox(request)).resolves.toEqual({
kind: "accepted",
});

expect(connect).toHaveBeenCalledTimes(2);
expect(get).toHaveBeenCalledTimes(3);
expect(get).toHaveBeenCalledTimes(4);
expect(startSandbox).toHaveBeenCalledWith(
{ name: "alpha", workspace: "default" },
{ signal: expect.any(AbortSignal) },
Expand All @@ -46,10 +48,7 @@ describe("OpenShell SDK sandbox lifecycle", () => {
{ name: "alpha", workspace: "default" },
{ signal: expect.any(AbortSignal) },
);
expect(waitReady).toHaveBeenCalledOnce();
expect(waitReady).toHaveBeenCalledWith("alpha", 75, {
signal: expect.any(AbortSignal),
});
expect(get).toHaveBeenCalledWith("alpha", { signal: expect.any(AbortSignal) });
});

it("rejects an invalid name before it connects", async () => {
Expand All @@ -62,13 +61,124 @@ describe("OpenShell SDK sandbox lifecycle", () => {
expect(connect).not.toHaveBeenCalled();
});

it("waits through the initial restart Error until the same sandbox is Ready", async () => {
const test = harness();
// The pinned SDK rejects this initial Error as a connect failure.
test.waitReady.mockRejectedValue(
Object.assign(new Error("sandbox entered error phase"), { code: "connect" }),
);
test.get
.mockResolvedValueOnce({ id: sandboxId, phase: "stopped" })
.mockResolvedValueOnce({ id: sandboxId, phase: "Error" })
.mockResolvedValueOnce({ id: sandboxId, phase: "Error" })
.mockResolvedValueOnce({ id: sandboxId, phase: "Provisioning" });

await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({ kind: "accepted" });
expect(test.waitForStartPoll).toHaveBeenCalledTimes(3);
expect(test.startSandbox).toHaveBeenCalledOnce();
expect(test.waitReady).not.toHaveBeenCalled();
});

it("accepts Ready after twenty initial Error observations", async () => {
const test = harness();
const phases = ["stopped", ...Array<string>(20).fill("Error"), "Ready"];
test.get.mockImplementation(async () => ({
id: sandboxId,
phase: phases.shift() ?? "Error",
}));

await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({ kind: "accepted" });
expect(test.waitForStartPoll).toHaveBeenCalledTimes(20);
expect(test.startSandbox).toHaveBeenCalledOnce();
});

it.each([
{ firstPhase: "Error", expectedPolls: 20 },
{ firstPhase: "Provisioning", expectedPolls: 1 },
])("fails on Error after $firstPhase", async ({ firstPhase, expectedPolls }) => {
const test = harness();
test.get
.mockResolvedValueOnce({ id: sandboxId, phase: "stopped" })
.mockResolvedValueOnce({ id: sandboxId, phase: firstPhase })
.mockResolvedValue({ id: sandboxId, phase: "Error" });

await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({
kind: "failed",
error: {
kind: "command",
reason: "failed",
message: "OpenShell sandbox entered Error while waiting for readiness after start.",
},
});
expect(test.waitForStartPoll).toHaveBeenCalledTimes(expectedPolls);
expect(test.startSandbox).toHaveBeenCalledOnce();
});

it("rejects replacement identity during initial Error without retrying the start", async () => {
const test = harness();
test.get
.mockResolvedValueOnce({ id: sandboxId, phase: "stopped" })
.mockResolvedValueOnce({ id: sandboxId, phase: "Error" })
.mockResolvedValueOnce({ id: "replacement-id", phase: "Error" });

await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({
kind: "failed",
error: {
kind: "transport",
reason: "identity_mismatch",
message: "OpenShell readiness changed sandbox identity.",
},
});
expect(test.startSandbox).toHaveBeenCalledOnce();
});

it.each(
["Failed", "CrashLoopBackOff", "ImagePullBackOff", "Unknown", "Evicted"].flatMap((phase) => [
phase,
phase.toLowerCase(),
]),
)("fails immediately when start reports %s", async (phase) => {
const test = harness();
test.get
.mockResolvedValueOnce({ id: sandboxId, phase: "stopped" })
.mockResolvedValue({ id: sandboxId, phase });
test.waitForStartPoll.mockImplementation(() => new Promise(() => undefined));

await expect(test.lifecycle.startSandbox({ ...request, timeoutMs: 50 })).resolves.toEqual({
kind: "failed",
error: {
kind: "command",
reason: "failed",
message: `OpenShell sandbox entered ${phase} while waiting for readiness after start.`,
},
});
expect(test.waitForStartPoll).not.toHaveBeenCalled();
expect(test.get).toHaveBeenCalledTimes(2);
expect(test.startSandbox).toHaveBeenCalledOnce();
});

it.each([
["rpc", "14", "transport"],
["auth", undefined, "authentication"],
])("fails immediately on a readiness %s failure", async (code, connectCode, kind) => {
const test = harness();
test.get
.mockResolvedValueOnce({ id: sandboxId, phase: "stopped" })
.mockResolvedValueOnce({ id: sandboxId, phase: "Error" })
.mockRejectedValueOnce(Object.assign(new Error("secret detail"), { code, connectCode }));

const result = await test.lifecycle.startSandbox(request);
expect(result.kind === "failed" && result.error.kind).toBe(kind);
expect(test.startSandbox).toHaveBeenCalledOnce();
expect(test.waitForStartPoll).toHaveBeenCalledOnce();
});

it("classifies an SDK authorization denial without exposing its detail", async () => {
const denied = Object.assign(new Error("token=secret"), { code: "auth" });
const lifecycle = createSdkOpenShellSandboxStateLifecycle({
connect: async () => ({
sandbox: {
get: async () => ({ id: sandboxId, phase: "stopped" }),
waitReady: async () => ({ id: sandboxId, phase: "ready" }),
},
raw: {
startSandbox: async () => Promise.reject(denied),
Expand Down Expand Up @@ -120,7 +230,7 @@ describe("OpenShell SDK sandbox lifecycle", () => {
message: `OpenShell rejected the ${operation === "startSandbox" ? "start" : "stop"} request because the sandbox is in Error state.`,
},
});
expect(test.waitReady).not.toHaveBeenCalled();
expect(test.get).toHaveBeenCalledOnce();
},
);

Expand Down Expand Up @@ -149,7 +259,6 @@ describe("OpenShell SDK sandbox lifecycle", () => {
},
sandbox: {
get: async () => ({ id: sandboxId, phase: "stopped" }),
waitReady: async () => ({ id: sandboxId, phase: "ready" }),
},
}),
});
Expand All @@ -168,8 +277,10 @@ describe("OpenShell SDK sandbox lifecycle", () => {
stopSandbox: async () => ({ sandbox: { metadata: { id: sandboxId } } }),
},
sandbox: {
get: async () => ({ id: sandboxId, phase: "stopped" }),
waitReady: () => new Promise(() => undefined),
get: vi
.fn()
.mockResolvedValueOnce({ id: sandboxId, phase: "stopped" })
.mockImplementation(() => new Promise(() => undefined)),
},
}),
});
Expand Down Expand Up @@ -213,7 +324,6 @@ describe("OpenShell SDK sandbox lifecycle", () => {
},
sandbox: {
get,
waitReady: async () => ({ id: sandboxId, phase: "ready" }),
},
}),
});
Expand Down Expand Up @@ -245,7 +355,6 @@ describe("OpenShell SDK sandbox lifecycle", () => {
},
sandbox: {
get,
waitReady: async () => ({ id: sandboxId, phase: "ready" }),
},
}),
waitForStopPoll,
Expand All @@ -265,7 +374,6 @@ describe("OpenShell SDK sandbox lifecycle", () => {
},
sandbox: {
get: async () => ({ id: sandboxId, phase: "stopping" }),
waitReady: async () => ({ id: sandboxId, phase: "ready" }),
},
}),
waitForStopPoll: async () => await new Promise(() => undefined),
Expand Down
Loading
Loading