From ae875d19a26355fb9083633467c93e7e2816784f Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 8 Oct 2026 19:48:13 +0700 Subject: [PATCH 1/6] fix(onboard): suppress expected missing-sandbox provider warnings Signed-off-by: San Dang --- .../provider-adapter-cli-uncertainty.test.ts | 16 ++++++++++++++ .../openshell/provider-diagnostic-cli.ts | 6 +++++- .../sandbox/sandbox-provider-cleanup.test.ts | 21 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts index c5b96d2d177..483a901aee0 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts @@ -10,6 +10,8 @@ function captured(status: number | null, stderr: string) { return { status, stdout: "", stderr }; } +const STRUCTURED_MISSING_SANDBOX = `Error: × code: 'Some requested entity was not found', message: "sandbox not found"`; + describe("CLI OpenShell provider adapter uncertain mutations", () => { it("captures delete diagnostics without printing raw command output", async () => { const run = vi.fn(() => captured(1, "provider remains attached")); @@ -57,6 +59,15 @@ describe("CLI OpenShell provider adapter uncertain mutations", () => { ["status: NotFound, code: PermissionDenied, message: \"sandbox 'alpha' not found\"", "failed"], ["sandbox 'other' not found, message: \"sandbox 'alpha' not found\"", "failed"], ["status: NotFound, message: \"sandbox 'alpha' not found\"", "sandbox_not_found"], + [STRUCTURED_MISSING_SANDBOX, "sandbox_not_found"], + [ + `Error: × code: 'Some requested entity was not found', message: "sandbox\n │ not found"`, + "sandbox_not_found", + ], + ['Error: status: Not Found, message: "sandbox not found"', "sandbox_not_found"], + ['Error: code: PermissionDenied, message: "sandbox not found"', "failed"], + [`${STRUCTURED_MISSING_SANDBOX}\nsandbox 'other-box' not found`, "failed"], + [`sandbox 'other-box' not found, message: ${STRUCTURED_MISSING_SANDBOX}`, "failed"], ["sandbox not found", "failed"], ["sandbox alpha not found", "failed"], ["sandbox 'alpha' not found\nsandbox 'other-box' not found", "failed"], @@ -115,6 +126,11 @@ describe("CLI OpenShell provider adapter uncertain mutations", () => { "signaled", { ...captured(null, "provider search-prod is not attached"), signal: "SIGTERM" as const }, ], + ["status-less sandbox absence", captured(null, STRUCTURED_MISSING_SANDBOX)], + [ + "signaled sandbox absence", + { ...captured(1, STRUCTURED_MISSING_SANDBOX), signal: "SIGTERM" as const }, + ], ])("rejects an uncertain idempotent detach result: %s (#9806)", async (_case, result) => { const adapter = createCliOpenShellProviderAdapter({ run: () => result }); diff --git a/src/lib/adapters/openshell/provider-diagnostic-cli.ts b/src/lib/adapters/openshell/provider-diagnostic-cli.ts index b0ea56266af..e24aa6ec135 100644 --- a/src/lib/adapters/openshell/provider-diagnostic-cli.ts +++ b/src/lib/adapters/openshell/provider-diagnostic-cli.ts @@ -242,7 +242,7 @@ export function reportsExactProviderNotFound( return diagnosticLines.every((line) => providerNameFromNotFoundLine(line) === providerName); } -/** A missing sandbox permits cleanup only when every diagnostic names the requested sandbox. */ +/** Recognize named sandbox absence and OpenShell's structured response for the requested operation. */ export function reportsExactSandboxNotFound( output: string, sandboxName: string, @@ -250,6 +250,10 @@ export function reportsExactSandboxNotFound( ): boolean { if (output.length > diagnosticLimit) return false; const lines = output.split(/\r?\n/).map(stripIssueDecoration).filter(Boolean); + // OpenShell's structured response omits the name; require the complete absence diagnostic. + const structuredNotFound = + /^(?:error:\s*)?(?:×\s*)?(?:code:\s*(["'])Some requested entity was not found\1|status:\s*(["']?)Not\s*Found\2)\s*,\s*message:\s*(["'])sandbox not found\3$/iu; + if (structuredNotFound.test(joinDiagnosticLines(lines))) return true; return ( lines.length > 0 && lines.every((line) => { diff --git a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts index e38b4b6ea69..0e090e70130 100644 --- a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts +++ b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts @@ -291,6 +291,27 @@ describe("detachSandboxProviders", () => { }); describe("runSandboxProviderPreDeleteCleanup", () => { + it.each([true, false])( + "reports structured sandbox absence only when it is unexpected (tolerateMissingSandbox=%s)", + async (tolerateMissingSandbox) => { + const { runOpenshell } = buildRunOpenshell(new Map(), { + status: 1, + stderr: `Error: × code: 'Some requested entity was not found', message: "sandbox not found"`, + }); + const warn = vi.fn(); + + const result = await runSandboxProviderPreDeleteCleanup("my-assistant", { + runOpenshell, + warn, + tolerateMissingSandbox, + }); + + const failureCount = tolerateMissingSandbox ? 0 : SANDBOX_PROVIDER_SUFFIXES.length; + expect(result.failures).toHaveLength(failureCount); + expect(warn).toHaveBeenCalledTimes(failureCount); + }, + ); + it("emits no warning when every detach succeeds", async () => { const { runOpenshell } = buildRunOpenshell(new Map()); const warn = vi.fn(); From 7fab748b7e2c310b98b188e4e8cbf6407ff507a6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 8 Oct 2026 21:26:19 +0700 Subject: [PATCH 2/6] fix(onboard): remove provider detach sweep before sandbox creation Signed-off-by: San Dang --- .../provider-adapter-cli-uncertainty.test.ts | 16 ----- .../openshell/provider-diagnostic-cli.ts | 6 +- .../onboard-orchestration.test.ts | 3 - .../managed-workload/onboard-orchestration.ts | 2 - .../onboard/sandbox-create-intent-types.ts | 3 - .../sandbox-create-plan-materialization.ts | 2 - src/lib/onboard/sandbox-create-plan.test.ts | 53 +--------------- .../sandbox-create/orchestration.test.ts | 31 --------- .../onboard/sandbox-create/orchestration.ts | 59 +++-------------- src/lib/onboard/sandbox-provider-cleanup.ts | 16 ----- test/onboarding/onboard-messaging.test.ts | 16 ++--- .../sandbox/sandbox-provider-cleanup.test.ts | 63 +------------------ 12 files changed, 20 insertions(+), 250 deletions(-) diff --git a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts index 483a901aee0..c5b96d2d177 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli-uncertainty.test.ts @@ -10,8 +10,6 @@ function captured(status: number | null, stderr: string) { return { status, stdout: "", stderr }; } -const STRUCTURED_MISSING_SANDBOX = `Error: × code: 'Some requested entity was not found', message: "sandbox not found"`; - describe("CLI OpenShell provider adapter uncertain mutations", () => { it("captures delete diagnostics without printing raw command output", async () => { const run = vi.fn(() => captured(1, "provider remains attached")); @@ -59,15 +57,6 @@ describe("CLI OpenShell provider adapter uncertain mutations", () => { ["status: NotFound, code: PermissionDenied, message: \"sandbox 'alpha' not found\"", "failed"], ["sandbox 'other' not found, message: \"sandbox 'alpha' not found\"", "failed"], ["status: NotFound, message: \"sandbox 'alpha' not found\"", "sandbox_not_found"], - [STRUCTURED_MISSING_SANDBOX, "sandbox_not_found"], - [ - `Error: × code: 'Some requested entity was not found', message: "sandbox\n │ not found"`, - "sandbox_not_found", - ], - ['Error: status: Not Found, message: "sandbox not found"', "sandbox_not_found"], - ['Error: code: PermissionDenied, message: "sandbox not found"', "failed"], - [`${STRUCTURED_MISSING_SANDBOX}\nsandbox 'other-box' not found`, "failed"], - [`sandbox 'other-box' not found, message: ${STRUCTURED_MISSING_SANDBOX}`, "failed"], ["sandbox not found", "failed"], ["sandbox alpha not found", "failed"], ["sandbox 'alpha' not found\nsandbox 'other-box' not found", "failed"], @@ -126,11 +115,6 @@ describe("CLI OpenShell provider adapter uncertain mutations", () => { "signaled", { ...captured(null, "provider search-prod is not attached"), signal: "SIGTERM" as const }, ], - ["status-less sandbox absence", captured(null, STRUCTURED_MISSING_SANDBOX)], - [ - "signaled sandbox absence", - { ...captured(1, STRUCTURED_MISSING_SANDBOX), signal: "SIGTERM" as const }, - ], ])("rejects an uncertain idempotent detach result: %s (#9806)", async (_case, result) => { const adapter = createCliOpenShellProviderAdapter({ run: () => result }); diff --git a/src/lib/adapters/openshell/provider-diagnostic-cli.ts b/src/lib/adapters/openshell/provider-diagnostic-cli.ts index e24aa6ec135..b0ea56266af 100644 --- a/src/lib/adapters/openshell/provider-diagnostic-cli.ts +++ b/src/lib/adapters/openshell/provider-diagnostic-cli.ts @@ -242,7 +242,7 @@ export function reportsExactProviderNotFound( return diagnosticLines.every((line) => providerNameFromNotFoundLine(line) === providerName); } -/** Recognize named sandbox absence and OpenShell's structured response for the requested operation. */ +/** A missing sandbox permits cleanup only when every diagnostic names the requested sandbox. */ export function reportsExactSandboxNotFound( output: string, sandboxName: string, @@ -250,10 +250,6 @@ export function reportsExactSandboxNotFound( ): boolean { if (output.length > diagnosticLimit) return false; const lines = output.split(/\r?\n/).map(stripIssueDecoration).filter(Boolean); - // OpenShell's structured response omits the name; require the complete absence diagnostic. - const structuredNotFound = - /^(?:error:\s*)?(?:×\s*)?(?:code:\s*(["'])Some requested entity was not found\1|status:\s*(["']?)Not\s*Found\2)\s*,\s*message:\s*(["'])sandbox not found\3$/iu; - if (structuredNotFound.test(joinDiagnosticLines(lines))) return true; return ( lines.length > 0 && lines.every((line) => { diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index babd6c317fc..f0f57fba2f6 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -616,7 +616,6 @@ describe("managed workload onboard orchestration", () => { plan: { intent: { sandboxGpuLogMessage: null }, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), @@ -699,7 +698,6 @@ describe("managed workload onboard orchestration", () => { plan: { intent: { sandboxGpuLogMessage: null }, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), @@ -1022,7 +1020,6 @@ describe("managed workload onboard orchestration", () => { intent: {}, portableLifecycle: testCase.portableLifecycle === true, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index 4a0902cbb90..b5f7a09a559 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -461,7 +461,6 @@ export interface PrepareOnboardSandboxWorkloadLaunchInput { readonly deferSandboxEffectsUntilIdentityVerification?: boolean; readonly skipProviderEffects?: boolean; readonly rebindMessagingTokenDefs: () => Promise; - readonly runProviderPreDeleteCleanup: MaterializeSandboxCreatePlanInput["runProviderPreDeleteCleanup"]; readonly upsertMessagingProviders: MaterializeSandboxCreatePlanInput["upsertMessagingProviders"]; readonly getHermesToolGatewayProviderName: (sandboxName: string) => string; readonly discloseInitialSandboxPolicy: (policy: InitialSandboxPolicy) => void; @@ -551,7 +550,6 @@ export async function prepareOnboardSandboxWorkloadLaunch( messagingTokenDefs: [...messagingTokenDefs], messagingConfig: input.messagingConfig ?? getMessagingChannelConfigFromPlan(input.plannedMessagingPlan), - runProviderPreDeleteCleanup: input.plan.runProviderPreDeleteCleanup, upsertMessagingProviders: input.plan.upsertMessagingProviders, getHermesToolGatewayProviderName: input.plan.getHermesToolGatewayProviderName, discloseInitialSandboxPolicy: input.plan.discloseInitialSandboxPolicy, diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index 2fabf1ebc3c..d12c693881f 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -109,9 +109,6 @@ export type MaterializeSandboxCreatePlanInput = { messagingTokenDefs: MessagingTokenDef[]; /** Non-secret config captured in the messaging plan that owns exact policy endpoints. */ messagingConfig?: MessagingChannelConfig | null; - runProviderPreDeleteCleanup( - revalidateSandboxIdentity?: (operation: string) => void, - ): Promise; upsertMessagingProviders( tokenDefs: MessagingTokenDef[], options: { diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index e9dfcee08de..245bb543877 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -366,7 +366,6 @@ export async function materializeSandboxCreatePlan({ skipProviderEffects = false, messagingTokenDefs, messagingConfig, - runProviderPreDeleteCleanup, upsertMessagingProviders, getHermesToolGatewayProviderName, discloseInitialSandboxPolicy, @@ -422,7 +421,6 @@ export async function materializeSandboxCreatePlan({ const activateProviderEffects = async ( revalidateSandboxIdentity?: (operation: string) => void, ): Promise => { - await runProviderPreDeleteCleanup(revalidateSandboxIdentity); const activatedMessagingProviders = filterMessagingProvidersForSandboxCreate( [ ...(await upsertMessagingProviders(enabledMessagingTokenDefs, { diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 858b7fcf57c..b568c0552ba 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -118,7 +118,6 @@ type DiscordPlanOverrides = Partial< Pick< Parameters[0], | "prepareInitialSandboxCreatePolicy" - | "runProviderPreDeleteCleanup" | "upsertMessagingProviders" | "getHermesToolGatewayProviderName" > @@ -131,7 +130,6 @@ function materializeDiscordCreatePlan( return materializeSandboxCreatePlan({ ...resolved, fromRef: "/tmp/Dockerfile", - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [discordProviderName]), getHermesToolGatewayProviderName: vi.fn(), ...overrides, @@ -170,7 +168,6 @@ async function expectCredentialBindingFailure({ policyPath: "/tmp/policy.yaml", appliedPresets: [], })); - const cleanupProviders = vi.fn(async () => {}); const upsertProviders = vi.fn(() => []); await expect( @@ -179,13 +176,11 @@ async function expectCredentialBindingFailure({ fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: materializedTokenDefs, prepareInitialSandboxCreatePolicy: preparePolicy, - runProviderPreDeleteCleanup: cleanupProviders, upsertMessagingProviders: upsertProviders, getHermesToolGatewayProviderName: vi.fn(), }), ).rejects.toThrow(expectedMessage); expect(preparePolicy).not.toHaveBeenCalled(); - expect(cleanupProviders).not.toHaveBeenCalled(); expect(upsertProviders).not.toHaveBeenCalled(); } @@ -272,7 +267,6 @@ describe("prepareSandboxCreatePolicy", () => { fromRef: "/tmp/Dockerfile", messagingTokenDefs, messagingConfig: { WECHAT_BASE_URL: "https://idc-37.weixin.qq.com" }, - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [providerName]), getHermesToolGatewayProviderName: vi.fn(), }); @@ -510,7 +504,6 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/Dockerfile", portableLifecycle: true, messagingTokenDefs, - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [discordProviderName]), getHermesToolGatewayProviderName: vi.fn(), }); @@ -545,7 +538,6 @@ describe("resolveSandboxCreateIntent", () => { selected: true, }); const cleanupPolicy = vi.fn(() => true); - const cleanupProviders = vi.fn(async () => {}); const upsertMessagingProviders = vi.fn(() => [discordProviderName]); await expect( @@ -558,7 +550,6 @@ describe("resolveSandboxCreateIntent", () => { credentialBindingProviders: [discordProviderName, "sandbox-missing-provider"], cleanup: cleanupPolicy, })), - runProviderPreDeleteCleanup: cleanupProviders, upsertMessagingProviders, }, ), @@ -566,7 +557,6 @@ describe("resolveSandboxCreateIntent", () => { "Cannot create sandbox; create-time policy requires credential provider 'sandbox-missing-provider', but the sandbox create plan does not attach it.", ); expect(cleanupPolicy).toHaveBeenCalledOnce(); - expect(cleanupProviders).not.toHaveBeenCalled(); expect(upsertMessagingProviders).not.toHaveBeenCalled(); }); @@ -597,7 +587,6 @@ describe("resolveSandboxCreateIntent", () => { intent, fromRef: "/tmp/Dockerfile", messagingTokenDefs: [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders, getHermesToolGatewayProviderName: vi.fn(), prepareInitialSandboxCreatePolicy: vi.fn(() => ({ @@ -645,7 +634,6 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: preparePolicy, - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "sandbox-hermes-tools"), }); @@ -693,16 +681,7 @@ describe("resolveSandboxCreateIntent", () => { }); const serializedIntent = JSON.stringify(intent); const events: string[] = []; - let completeCleanup!: () => void; - let cleanupStarted!: () => void; - const pendingCleanup = new Promise((resolve) => { - completeCleanup = resolve; - }); - const started = new Promise((resolve) => { - cleanupStarted = resolve; - }); - - const materializing = materializeSandboxCreatePlan({ + const result = await materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: tokenDefs, @@ -714,11 +693,6 @@ describe("resolveSandboxCreateIntent", () => { events.push("disclose"); expect(policy.appliedPresets).toEqual(["telegram"]); }, - runProviderPreDeleteCleanup: async () => { - cleanupStarted(); - await pendingCleanup; - events.push("cleanup"); - }, upsertMessagingProviders: vi.fn((receivedTokenDefs, options) => { events.push("upsert"); expect(receivedTokenDefs).toEqual(tokenDefs); @@ -734,14 +708,7 @@ describe("resolveSandboxCreateIntent", () => { }, }); - try { - await Promise.race([started, materializing]); - expect(events).not.toContain("upsert"); - } finally { - completeCleanup(); - } - const result = await materializing; - expect(events).toEqual(["policy", "hermes", "disclose", "cleanup", "upsert"]); + expect(events).toEqual(["policy", "hermes", "disclose", "upsert"]); expect(result.createRequest).toEqual({ sandboxName: "sandbox", source: { reference: "/tmp/nemoclaw-build-1/Dockerfile" }, @@ -796,9 +763,6 @@ describe("resolveSandboxCreateIntent", () => { events.push("policy-cleanup"); return true; }); - const runProviderPreDeleteCleanup = vi.fn(async () => { - events.push("provider-cleanup"); - }); const upsertMessagingProviders = vi.fn(() => { events.push("upsert"); return ["sandbox-telegram-bridge"]; @@ -819,7 +783,6 @@ describe("resolveSandboxCreateIntent", () => { appliedPresets: ["telegram"], cleanup: cleanupPolicy, }), - runProviderPreDeleteCleanup, upsertMessagingProviders, getHermesToolGatewayProviderName, }), @@ -827,7 +790,6 @@ describe("resolveSandboxCreateIntent", () => { expect(events).toEqual(["policy-cleanup"]); expect(cleanupPolicy).toHaveBeenCalledOnce(); - expect(runProviderPreDeleteCleanup).not.toHaveBeenCalled(); expect(upsertMessagingProviders).not.toHaveBeenCalled(); expect(getHermesToolGatewayProviderName).not.toHaveBeenCalled(); }); @@ -861,7 +823,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], }), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -932,7 +893,6 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }), @@ -966,7 +926,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1024,7 +983,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1077,7 +1035,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1124,7 +1081,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }), @@ -1149,7 +1105,6 @@ describe("resolveSandboxCreateIntent", () => { sandboxGpuLogMessage: null, }); const cleanupPolicy = vi.fn(() => true); - const cleanupProviders = vi.fn(async () => {}); const upsertProviders = vi.fn(() => []); await expect( @@ -1165,13 +1120,11 @@ describe("resolveSandboxCreateIntent", () => { discloseInitialSandboxPolicy: () => { throw new Error("disclosure failed"); }, - runProviderPreDeleteCleanup: cleanupProviders, upsertMessagingProviders: upsertProviders, getHermesToolGatewayProviderName: vi.fn(), }), ).rejects.toThrow("disclosure failed"); expect(cleanupPolicy).toHaveBeenCalledOnce(); - expect(cleanupProviders).not.toHaveBeenCalled(); expect(upsertProviders).not.toHaveBeenCalled(); }); @@ -1189,7 +1142,6 @@ describe("resolveSandboxCreateIntent", () => { appliedPresets: [], cleanup: cleanupPolicy, })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: async () => { throw providerFailure; }, @@ -1280,7 +1232,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index 433fd5c9490..a54d5a2f7d7 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -10,7 +10,6 @@ import { describe, expect, it, vi } from "vitest"; import * as processRecovery from "../../actions/sandbox/process-recovery"; import { createHermesCredentialEnvReconciliationRuntime } from "../../actions/sandbox/runtime/hermes-lifecycle"; import type { SandboxEntry } from "../../state/registry"; -import { runSandboxProviderPreDeleteCleanup } from "../sandbox-provider-cleanup"; import { releaseManagedStartupHoldWithRetry } from "../managed-startup/provider-root-apply"; import { assertApfCreateIntent, @@ -556,36 +555,6 @@ describe("deferred provider effect authority", () => { ]); }); - it("refuses provider cleanup when a sandbox appears after verified absence (#9833)", async () => { - let observationCount = 0; - const revalidateSandboxIdentity = vi.fn(); - const runOpenshell = vi.fn(() => ({ - pid: 1, - output: [null, "", ""], - stdout: "", - stderr: "", - status: 0, - signal: null, - })); - - await expect( - runAuthorityBoundProviderCleanup({ - sandboxName: "alpha", - observeSandbox: () => - observationCount++ === 0 - ? { state: "missing", liveIdentityFingerprint: null } - : { state: "ready", liveIdentityFingerprint: "f".repeat(64) }, - revalidateSandboxIdentity, - runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, - runOpenshell, - redact: (value) => value, - tolerateMissingSandbox: true, - }), - ).rejects.toThrow(/appeared after absence was verified/u); - expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); - expect(runOpenshell).not.toHaveBeenCalled(); - }); - it("refuses every deferred provider attachment before a same-name replacement can receive credentials (#9833)", async () => { const revalidateSandboxIdentity = vi.fn(); const runOpenshell = vi.fn(() => ({ status: 0 })); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index f1093b70c09..d131fd78491 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1494,42 +1494,18 @@ export function createProviderEffectBoundary(input: { }; } -type SandboxProviderCleanupAuthority = - | { - readonly revalidateSandboxIdentity: (operation: string) => void; - } - | { - readonly observeSandbox: () => ReturnType< - SandboxCreateOrchestrationRuntime["getSandboxRecreateObservation"] - >; - readonly revalidateSandboxIdentity: (operation: string) => void; - }; - -export async function runAuthorityBoundProviderCleanup( - input: { - readonly sandboxName: string; - readonly runProviderPreDeleteCleanup: SandboxCreateOrchestrationRuntime["runSandboxProviderPreDeleteCleanup"]; - readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; - readonly redact: SandboxCreateOrchestrationRuntime["redact"]; - readonly tolerateMissingSandbox?: boolean; - } & SandboxProviderCleanupAuthority, -): Promise { - const revalidateSandboxIdentity = - "observeSandbox" in input - ? (operation: string): void => { - if (input.observeSandbox().state !== "missing") { - throw new Error( - `Cannot clean up providers for sandbox '${input.sandboxName}': a sandbox with that name appeared after absence was verified while ${operation}.`, - ); - } - input.revalidateSandboxIdentity(operation); - } - : input.revalidateSandboxIdentity; +export async function runAuthorityBoundProviderCleanup(input: { + readonly sandboxName: string; + readonly runProviderPreDeleteCleanup: SandboxCreateOrchestrationRuntime["runSandboxProviderPreDeleteCleanup"]; + readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; + readonly redact: SandboxCreateOrchestrationRuntime["redact"]; + readonly revalidateSandboxIdentity: (operation: string) => void; +}): Promise { + const { revalidateSandboxIdentity } = input; revalidateSandboxIdentity(`cleaning up providers for sandbox '${input.sandboxName}'`); await input.runProviderPreDeleteCleanup(input.sandboxName, { runOpenshell: input.runOpenshell, redact: input.redact, - ...(input.tolerateMissingSandbox ? { tolerateMissingSandbox: true } : {}), revalidateSandboxIdentity, }); } @@ -2729,25 +2705,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ) ).messagingTokenDefs; }, - runProviderPreDeleteCleanup: async (verifiedIdentityRevalidation) => { - await runAuthorityBoundProviderCleanup({ - sandboxName, - runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, - runOpenshell, - redact, - tolerateMissingSandbox: true, - ...(verifiedIdentityRevalidation - ? { - revalidateSandboxIdentity: verifiedIdentityRevalidation, - } - : { - observeSandbox: () => - getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), - revalidateSandboxIdentity: (operation: string) => - revalidateSandboxIdentity(false, operation), - }), - }); - }, upsertMessagingProviders: (tokenDefs, options) => applyMessagingProviders(tokenDefs, { ...options, diff --git a/src/lib/onboard/sandbox-provider-cleanup.ts b/src/lib/onboard/sandbox-provider-cleanup.ts index b383e743009..3ff7bea32b8 100644 --- a/src/lib/onboard/sandbox-provider-cleanup.ts +++ b/src/lib/onboard/sandbox-provider-cleanup.ts @@ -46,13 +46,6 @@ export type DetachSandboxProvidersDeps = { runOpenshell?: SandboxProviderRunOpenshell; providerAdapter?: OpenShellProviderAdapter; revalidateSandboxIdentity?: (operation: string) => void; - /** - * Treat OpenShell `sandbox not found` outputs as success-equivalent. Used - * by the resume-after-prune call site where the sandbox is expected to be - * gone — the call exists only to clear any stale gateway-side attachment - * record, so a missing-sandbox response means there is nothing to clean. - */ - tolerateMissingSandbox?: boolean; }; export type DeleteProviderWithRecoveryDeps = DetachSandboxProvidersDeps & { @@ -113,7 +106,6 @@ function identityRedact(input: string): string { /** * Detach owned messaging and search providers before sandbox removal. * Return failures to the lifecycle owner; it decides whether cleanup can continue. - * Missing sandboxes are tolerated only by the explicit resume-after-prune caller. */ export async function detachSandboxProviders( sandboxName: string, @@ -142,13 +134,6 @@ export async function detachSandboxProviders( } const output = result.error.message; if (result.error.kind === "command" && result.error.reason === "not_found") continue; - if ( - deps.tolerateMissingSandbox && - result.error.kind === "command" && - result.error.reason === "sandbox_not_found" - ) { - continue; - } failures.push({ name, output: output.trim() }); } return { detached, failures }; @@ -163,7 +148,6 @@ export async function runSandboxProviderPreDeleteCleanup( providerAdapter: deps.providerAdapter, runOpenshell: deps.runOpenshell, revalidateSandboxIdentity: deps.revalidateSandboxIdentity, - tolerateMissingSandbox: deps.tolerateMissingSandbox, }); if (result.failures.length === 0) return result; const warn = deps.warn ?? ((message: string) => console.warn(message)); diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index fe8e9849d09..92871d0b571 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -168,6 +168,12 @@ const { createSandbox, setupMessagingChannels } = require(${onboardPath}); assert.equal(result.status, 0, result.stderr); const payload = parseStdoutJson(result.stdout); + assert.deepEqual( + payload.commands.filter((e: CommandEntry) => e.command.includes("sandbox provider detach")), + [], + "new sandbox creation should not detach providers", + ); + const providerCommands = payload.commands.filter((e: CommandEntry) => e.command.includes("provider create"), ); @@ -273,14 +279,8 @@ const { createSandbox, setupMessagingChannels } = require(${onboardPath}); ); const envString = JSON.stringify(createCommand.env); - assert.ok( - !envString.includes("test-discord-token-value"), - "Discord token value must not leak into sandbox env", - ); - assert.ok( - !envString.includes("xoxb-test-slack-token-value"), - "Slack bot token value must not leak into sandbox spawn env", - ); + assert.ok(!envString.includes("test-discord-token-value"), "Discord token in sandbox env"); + assert.ok(!envString.includes("xoxb-test-slack-token-value"), "Slack bot token in env"); assert.ok( !envString.includes("xapp-test-slack-app-token-value"), "Slack app token value must not leak into sandbox spawn env", diff --git a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts index 0e090e70130..e77d7f1f6c8 100644 --- a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts +++ b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts @@ -182,7 +182,7 @@ describe("detachSandboxProviders", () => { ]); }); - it("retains a detach failure for a different missing sandbox even when absence is tolerated", async () => { + it("retains a detach failure for a different missing sandbox", async () => { const { runOpenshell } = buildRunOpenshell( new Map([ [ @@ -196,7 +196,6 @@ describe("detachSandboxProviders", () => { ); const result = await detachSandboxProviders("phantom", { runOpenshell, - tolerateMissingSandbox: true, }); expect(result.failures).toEqual([ { @@ -206,45 +205,6 @@ describe("detachSandboxProviders", () => { ]); }); - it("tolerates sandbox-not-found when tolerateMissingSandbox is set (opportunistic call)", async () => { - const responses = new Map([ - [ - "sandbox provider detach phantom phantom-telegram-bridge", - { status: 1, stderr: "Error: status: NotFound, sandbox 'phantom' not found" }, - ], - ]); - const { runOpenshell } = buildRunOpenshell(responses); - - const result = await detachSandboxProviders("phantom", { - runOpenshell, - tolerateMissingSandbox: true, - }); - - expect(result.failures).toEqual([]); - }); - - it("suppresses output for tolerated missing-sandbox detach probes", async () => { - const { runOpenshell } = buildRunOpenshell(new Map(), { - status: 1, - stderr: "Error: status: NotFound, sandbox 'phantom' not found", - }); - - const result = await detachSandboxProviders("phantom", { - runOpenshell, - tolerateMissingSandbox: true, - }); - - expect(result.failures).toEqual([]); - expect(runOpenshell).toHaveBeenCalledTimes(SANDBOX_PROVIDER_SUFFIXES.length); - runOpenshell.mock.calls.forEach(([, opts]) => { - expect(opts).toMatchObject({ - ignoreError: true, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - }); - }); - }); - it("collects non-tolerated failures without aborting the loop", async () => { const responses = new Map([ [ @@ -291,27 +251,6 @@ describe("detachSandboxProviders", () => { }); describe("runSandboxProviderPreDeleteCleanup", () => { - it.each([true, false])( - "reports structured sandbox absence only when it is unexpected (tolerateMissingSandbox=%s)", - async (tolerateMissingSandbox) => { - const { runOpenshell } = buildRunOpenshell(new Map(), { - status: 1, - stderr: `Error: × code: 'Some requested entity was not found', message: "sandbox not found"`, - }); - const warn = vi.fn(); - - const result = await runSandboxProviderPreDeleteCleanup("my-assistant", { - runOpenshell, - warn, - tolerateMissingSandbox, - }); - - const failureCount = tolerateMissingSandbox ? 0 : SANDBOX_PROVIDER_SUFFIXES.length; - expect(result.failures).toHaveLength(failureCount); - expect(warn).toHaveBeenCalledTimes(failureCount); - }, - ); - it("emits no warning when every detach succeeds", async () => { const { runOpenshell } = buildRunOpenshell(new Map()); const warn = vi.fn(); From 5097f77c0d2f61b8b95f1207620f799afba4d6d3 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 8 Oct 2026 22:28:29 +0700 Subject: [PATCH 3/6] fix(runtime): allow initial Error during sandbox restart Signed-off-by: San Dang --- .../openshell/sandbox-lifecycle-sdk.test.ts | 104 +++++++++++++++--- .../openshell/sandbox-lifecycle-sdk.ts | 60 ++++++---- 2 files changed, 123 insertions(+), 41 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts index 6d407fa076c..8936448eec7 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts @@ -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) }, @@ -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 () => { @@ -62,13 +61,86 @@ 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.each([ + { firstPhase: "Error", expectedPolls: 19 }, + { 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([ + ["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), @@ -120,7 +192,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(); }, ); @@ -149,7 +221,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get: async () => ({ id: sandboxId, phase: "stopped" }), - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), }); @@ -168,8 +239,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)), }, }), }); @@ -213,7 +286,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get, - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), }); @@ -245,7 +317,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get, - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), waitForStopPoll, @@ -265,7 +336,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), diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts index a6f28228875..4f25facf6f2 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts @@ -31,7 +31,6 @@ type SdkSandboxMutationResponse = Readonly<{ type SdkClient = Readonly<{ sandbox: Readonly<{ get(name: string, options: CallOptions): Promise; - waitReady(name: string, timeoutSecs: number, options: CallOptions): Promise; }>; raw: Readonly<{ startSandbox( @@ -50,10 +49,14 @@ export type SdkOpenShellSandboxStateLifecycleDeps = Readonly<{ env?: NodeJS.ProcessEnv; homeDir?: string; loadSdk?: () => Promise; + waitForStartPoll?: (signal: AbortSignal) => Promise; waitForStopPoll?: (signal: AbortSignal) => Promise; }>; const DEFAULT_MUTATION_TIMEOUT_MS = 75_000; +// Match the public start path's bounded initial Error grace. The pinned SDK's +// waitReady rejects this restart transition before the same sandbox can recover. +const START_INITIAL_ERROR_GRACE_POLLS = 20; function lifecycleError( error: unknown, @@ -113,6 +116,7 @@ async function mutate( action: "start" | "stop", request: MutateOpenShellSandboxRequest, connect: (target: OpenShellGatewayTarget, options: CallOptions) => Promise, + waitForStartPoll: (signal: AbortSignal) => Promise, waitForStopPoll: (signal: AbortSignal) => Promise, ): Promise { if ( @@ -178,44 +182,50 @@ async function mutate( }, }; } - if (action === "start") { - const ready = await Promise.race([ - client.sandbox.waitReady( - request.sandboxName, - Math.max(1, Math.ceil((request.timeoutMs ?? DEFAULT_MUTATION_TIMEOUT_MS) / 1000)), - { signal: controller.signal }, - ), + let remainingInitialErrorGracePolls = START_INITIAL_ERROR_GRACE_POLLS; + for (;;) { + const current = await Promise.race([ + client.sandbox.get(request.sandboxName, { signal: controller.signal }), aborted, ]); - if (fingerprintOpenShellSandboxId(ready.id) !== request.sandboxIdentityFingerprint) { + if (fingerprintOpenShellSandboxId(current.id) !== request.sandboxIdentityFingerprint) { return { kind: "failed", error: { kind: "transport", reason: "identity_mismatch", - message: "OpenShell readiness changed sandbox identity.", + message: + action === "start" + ? "OpenShell readiness changed sandbox identity." + : "OpenShell stop observation changed sandbox identity.", }, }; } - } else { - for (;;) { - const stopped = await Promise.race([ - client.sandbox.get(request.sandboxName, { signal: controller.signal }), - aborted, - ]); - if (fingerprintOpenShellSandboxId(stopped.id) !== request.sandboxIdentityFingerprint) { + const phase = current.phase.toLowerCase(); + if (phase === (action === "start" ? "ready" : "stopped")) break; + if (action === "start") { + if (phase === "error") { + remainingInitialErrorGracePolls -= 1; + } else { + remainingInitialErrorGracePolls = 0; + } + if (phase === "error" && remainingInitialErrorGracePolls <= 0) { return { kind: "failed", error: { - kind: "transport", - reason: "identity_mismatch", - message: "OpenShell stop observation changed sandbox identity.", + kind: "command", + reason: "failed", + message: "OpenShell sandbox entered Error while waiting for readiness after start.", }, }; } - if (stopped.phase.toLowerCase() === "stopped") break; - await Promise.race([waitForStopPoll(controller.signal), aborted]); } + await Promise.race([ + action === "start" + ? waitForStartPoll(controller.signal) + : waitForStopPoll(controller.signal), + aborted, + ]); } return { kind: "accepted" }; } catch (error) { @@ -249,8 +259,10 @@ export function createSdkOpenShellSandboxStateLifecycle( }); const waitForStopPoll = deps.waitForStopPoll ?? ((signal: AbortSignal) => delay(250, undefined, { signal })); + const waitForStartPoll = + deps.waitForStartPoll ?? ((signal: AbortSignal) => delay(3_000, undefined, { signal })); return { - startSandbox: (request) => mutate("start", request, connect, waitForStopPoll), - stopSandbox: (request) => mutate("stop", request, connect, waitForStopPoll), + startSandbox: (request) => mutate("start", request, connect, waitForStartPoll, waitForStopPoll), + stopSandbox: (request) => mutate("stop", request, connect, waitForStartPoll, waitForStopPoll), }; } From baa6e8c46f9034d64b55e4ff6db9c1824a595575 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 00:24:14 +0700 Subject: [PATCH 4/6] test(connect): advance mocked SDK phase after start Signed-off-by: San Dang --- test/support/connect-flow-test-harness.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index cdc6cb7256f..ca94625f81e 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -621,6 +621,9 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne .spyOn(openShellSdk, "connectManagedOpenShellSdk") .mockImplementation(async (...args: unknown[]) => { const target = args[0] as { kind: string; gatewayName?: string }; + let sandboxPhase = String( + options.sandboxGetPhase ?? (options.registryEntry?.stopped === true ? "Stopped" : "Ready"), + ).toLowerCase(); return { raw: { startSandbox: async ({ name }: { name: string }) => { @@ -639,6 +642,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne code: String(completion.status ?? "unknown"), }); } + sandboxPhase = "ready"; return { sandbox: { metadata: { id: "alpha-sandbox-id" } } }; }, stopSandbox: async () => ({ sandbox: { metadata: { id: "alpha-sandbox-id" } } }), @@ -646,10 +650,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne sandbox: { get: async () => ({ id: "alpha-sandbox-id", - phase: String( - options.sandboxGetPhase ?? - (options.registryEntry?.stopped === true ? "Stopped" : "Ready"), - ).toLowerCase(), + phase: sandboxPhase, }), waitReady: async () => ({ id: "alpha-sandbox-id", phase: "ready" }), }, From 058b1d693ac4dbdf9740f27ab29396ecadddb99c Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 10:01:29 +0700 Subject: [PATCH 5/6] refactor(lifecycle): share post-start Error grace policy Signed-off-by: San Dang --- src/lib/actions/sandbox/connect.ts | 24 +++----------- src/lib/actions/sandbox/gateway-state.ts | 1 + src/lib/actions/sandbox/start-wait.test.ts | 24 ++++++++------ .../openshell/sandbox-lifecycle-sdk.test.ts | 15 ++++++++- .../openshell/sandbox-lifecycle-sdk.ts | 31 +++++++------------ .../lifecycle/sandbox-start-error-grace.ts | 20 ++++++++++++ 6 files changed, 66 insertions(+), 49 deletions(-) create mode 100644 src/lib/domain/lifecycle/sandbox-start-error-grace.ts diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 330e4eb46e0..b14fb93c2ef 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -88,6 +88,7 @@ import { import { preflightVllmModelEnvOrExit } from "./connect-vllm-preflight"; import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier"; import { + createSandboxStartErrorGrace, ensureLiveSandboxOrExit, buildHermesPortableCommandAuthority, defaultPortableDemoStateDir, @@ -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 @@ -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, @@ -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, diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index a6ac4e94d86..91edad026a4 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -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, diff --git a/src/lib/actions/sandbox/start-wait.test.ts b/src/lib/actions/sandbox/start-wait.test.ts index 0ca21e1fa09..fe2ead086cb 100644 --- a/src/lib/actions/sandbox/start-wait.test.ts +++ b/src/lib/actions/sandbox/start-wait.test.ts @@ -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({ diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts index 8936448eec7..11f69c5a759 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts @@ -79,8 +79,21 @@ describe("OpenShell SDK sandbox lifecycle", () => { expect(test.waitReady).not.toHaveBeenCalled(); }); + it("accepts Ready after twenty initial Error observations", async () => { + const test = harness(); + const phases = ["stopped", ...Array(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: 19 }, + { firstPhase: "Error", expectedPolls: 20 }, { firstPhase: "Provisioning", expectedPolls: 1 }, ])("fails on Error after $firstPhase", async ({ firstPhase, expectedPolls }) => { const test = harness(); diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts index 4f25facf6f2..7b7969a9af1 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts @@ -3,6 +3,7 @@ import { setTimeout as delay } from "node:timers/promises"; +import { createSandboxStartErrorGrace } from "../../domain/lifecycle/sandbox-start-error-grace"; import { isValidName } from "../../name-validation"; import { fingerprintOpenShellSandboxId } from "./sandbox-identity"; import type { OpenShellGatewayTarget, OpenShellSandboxError } from "./sandbox-observer"; @@ -54,9 +55,6 @@ export type SdkOpenShellSandboxStateLifecycleDeps = Readonly<{ }>; const DEFAULT_MUTATION_TIMEOUT_MS = 75_000; -// Match the public start path's bounded initial Error grace. The pinned SDK's -// waitReady rejects this restart transition before the same sandbox can recover. -const START_INITIAL_ERROR_GRACE_POLLS = 20; function lifecycleError( error: unknown, @@ -182,7 +180,7 @@ async function mutate( }, }; } - let remainingInitialErrorGracePolls = START_INITIAL_ERROR_GRACE_POLLS; + const allowInitialError = createSandboxStartErrorGrace(action === "start"); for (;;) { const current = await Promise.race([ client.sandbox.get(request.sandboxName, { signal: controller.signal }), @@ -203,22 +201,15 @@ async function mutate( } const phase = current.phase.toLowerCase(); if (phase === (action === "start" ? "ready" : "stopped")) break; - if (action === "start") { - if (phase === "error") { - remainingInitialErrorGracePolls -= 1; - } else { - remainingInitialErrorGracePolls = 0; - } - if (phase === "error" && remainingInitialErrorGracePolls <= 0) { - return { - kind: "failed", - error: { - kind: "command", - reason: "failed", - message: "OpenShell sandbox entered Error while waiting for readiness after start.", - }, - }; - } + if (action === "start" && !allowInitialError(phase) && phase === "error") { + return { + kind: "failed", + error: { + kind: "command", + reason: "failed", + message: "OpenShell sandbox entered Error while waiting for readiness after start.", + }, + }; } await Promise.race([ action === "start" diff --git a/src/lib/domain/lifecycle/sandbox-start-error-grace.ts b/src/lib/domain/lifecycle/sandbox-start-error-grace.ts new file mode 100644 index 00000000000..968993a0b76 --- /dev/null +++ b/src/lib/domain/lifecycle/sandbox-start-error-grace.ts @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// OpenShell can transiently report Error after start before advancing to Ready. +// Opt into twenty initial Error observations only after starting the sandbox; +// observing another phase ends the grace. Remove this compatibility exception +// when OpenShell exposes a structured restart signal or guarantees that restart +// recovery never emits the terminal Error phase. +const START_INITIAL_ERROR_GRACE_POLLS = 20; + +export function createSandboxStartErrorGrace( + enabled: boolean, +): (phase: string | null | undefined) => boolean { + let remainingPolls = enabled ? START_INITIAL_ERROR_GRACE_POLLS : 0; + return (phase) => { + const allowed = phase?.toLowerCase() === "error" && remainingPolls > 0; + remainingPolls = allowed ? remainingPolls - 1 : 0; + return allowed; + }; +} From fd7b2466257bc4907bf5ab73b63149c9a4786051 Mon Sep 17 00:00:00 2001 From: San Dang Date: Fri, 9 Oct 2026 10:42:22 +0700 Subject: [PATCH 6/6] fix(lifecycle): classify terminal phases during SDK start Signed-off-by: San Dang --- .../openshell/sandbox-lifecycle-sdk.test.ts | 25 +++++++++++++++++++ .../openshell/sandbox-lifecycle-sdk.ts | 5 ++-- src/lib/state/gateway.ts | 5 +++- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts index 11f69c5a759..66082768c09 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts @@ -132,6 +132,31 @@ describe("OpenShell SDK sandbox lifecycle", () => { 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"], diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts index 7b7969a9af1..feb3170fb25 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts @@ -5,6 +5,7 @@ import { setTimeout as delay } from "node:timers/promises"; import { createSandboxStartErrorGrace } from "../../domain/lifecycle/sandbox-start-error-grace"; import { isValidName } from "../../name-validation"; +import { isTerminalSandboxPhase } from "../../state/gateway"; import { fingerprintOpenShellSandboxId } from "./sandbox-identity"; import type { OpenShellGatewayTarget, OpenShellSandboxError } from "./sandbox-observer"; @@ -201,13 +202,13 @@ async function mutate( } const phase = current.phase.toLowerCase(); if (phase === (action === "start" ? "ready" : "stopped")) break; - if (action === "start" && !allowInitialError(phase) && phase === "error") { + if (action === "start" && !allowInitialError(phase) && isTerminalSandboxPhase(phase)) { return { kind: "failed", error: { kind: "command", reason: "failed", - message: "OpenShell sandbox entered Error while waiting for readiness after start.", + message: `OpenShell sandbox entered ${current.phase} while waiting for readiness after start.`, }, }; } diff --git a/src/lib/state/gateway.ts b/src/lib/state/gateway.ts index 862d8b26f47..25a35d4bf46 100644 --- a/src/lib/state/gateway.ts +++ b/src/lib/state/gateway.ts @@ -114,7 +114,10 @@ export const TERMINAL_SANDBOX_PHASES = new Set([ ]); export function isTerminalSandboxPhase(phase: string | null | undefined): boolean { - return !!phase && TERMINAL_SANDBOX_PHASES.has(phase); + return ( + !!phase && + [...TERMINAL_SANDBOX_PHASES].some((terminal) => terminal.toLowerCase() === phase.toLowerCase()) + ); } export function getSandboxStateFromOutputs(