diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 82f7055c75a..1240c665d95 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -506,11 +506,16 @@ function finalRelaunchContainerFailureDetail( return "Docker could not stop the replacement container for the final recovery handoff. NemoClaw did not start the primary dashboard/API host forward"; } if (completion.lifecycleReleaseObserved === false) { - return "OpenShell did not release the sandbox name before the final recovery handoff. NemoClaw did not restart the replacement container or start the primary dashboard/API host forward"; + return "OpenShell did not retire the previous lifecycle record before the final replacement start. NemoClaw did not start the primary dashboard/API host forward"; } if (completion.replacementRestarted === false) { return "Docker could not start the replacement container to complete the final recovery handoff. NemoClaw did not start the primary dashboard/API host forward"; } + if (completion.finalHandoffAcknowledged === false) { + return `OpenShell did not acknowledge the final replacement container handoff${ + completion.lastSandboxPhase ? `; last sandbox phase was ${completion.lastSandboxPhase}` : "" + }. NemoClaw did not start the primary dashboard/API host forward`; + } return null; } @@ -759,6 +764,15 @@ function recoverSandboxProcesses( quiet, deps: { runOpenshell, + runCaptureOpenshell: (args, options) => + captureOpenshell(args, { + ignoreError: true, + includeStderr: true, + killProcessTreeOnTimeout: options?.killProcessTreeOnTimeout === true, + killSignal: options?.killSignal === "SIGKILL" ? "SIGKILL" : undefined, + timeout: + typeof options?.timeout === "number" ? options.timeout : OPENSHELL_PROBE_TIMEOUT_MS, + }).output, confirmMissingSupervisor: (containerId) => isExactlyMissingManagedSupervisor( requestPinnedGatewaySupervisorAction(sandboxName, "probe", 210000, containerId), @@ -830,32 +844,32 @@ export function restartSandboxGateway( return withUnsupportedHermesPortableGatewayRestartFence(sandboxName, () => { return withTimerBoundShieldsMutationLock(sandboxName, "gateway restart", () => restartSandboxGatewayWithDeps(sandboxName, { - quiet, - deps: { - getSessionAgent: agentRuntime.getSessionAgent, - getSandbox: registry.getSandbox, - resolveSandboxDashboardPort, - requestGatewaySupervisorAction: executeGatewaySupervisorAction, - executeSandboxExecCommand, - waitForRecoveredSandboxGateway: (name, options) => - waitForRecoveredSandboxGateway(name, { - ...options, - initialManagedHealthPassed: true, - timeoutSeconds: gatewayRecoveryTimeoutSeconds(agentRuntime.getSessionAgent(name)), - managedProbeImpl: (sandboxName) => - confirmRecoveredSandboxGatewayManaged(sandboxName, { - requestGatewaySupervisorActionImpl: - deps.requestGatewaySupervisorAction ?? executeGatewaySupervisorAction, - }), + quiet, + deps: { + getSessionAgent: agentRuntime.getSessionAgent, + getSandbox: registry.getSandbox, + resolveSandboxDashboardPort, + requestGatewaySupervisorAction: executeGatewaySupervisorAction, + executeSandboxExecCommand, + waitForRecoveredSandboxGateway: (name, options) => + waitForRecoveredSandboxGateway(name, { + ...options, + initialManagedHealthPassed: true, + timeoutSeconds: gatewayRecoveryTimeoutSeconds(agentRuntime.getSessionAgent(name)), + managedProbeImpl: (sandboxName) => + confirmRecoveredSandboxGatewayManaged(sandboxName, { + requestGatewaySupervisorActionImpl: + deps.requestGatewaySupervisorAction ?? executeGatewaySupervisorAction, + }), }), - ensureSandboxPortForward, - ensureHermesDashboardPortForwardIfEnabled, - recoverMessagingHostForward, - recoverDeclaredAgentForwardPorts, - printGatewayWedgeDiagnostics, - inspectHermesMcpReconciliationRefusal, - ...deps, - }, + ensureSandboxPortForward, + ensureHermesDashboardPortForwardIfEnabled, + recoverMessagingHostForward, + recoverDeclaredAgentForwardPorts, + printGatewayWedgeDiagnostics, + inspectHermesMcpReconciliationRefusal, + ...deps, + }, }), ); }); @@ -879,10 +893,7 @@ const OPENSHELL_RELAY_TARGET_NOT_FOUND = 'message: "No such file or directory (o const OPENSHELL_RELAY_TARGET_REFUSED = 'message: "Connection refused (os error 111)"'; function normalizeOpenshellStructuredError(value: string): string { - return stripAnsi(value) - .replace(/[×│]/gu, " ") - .replace(/\s+/gu, " ") - .trim(); + return stripAnsi(value).replace(/[×│]/gu, " ").replace(/\s+/gu, " ").trim(); } function hasRetryableOpenshellFailureShape(result: ReturnType): boolean { diff --git a/src/lib/actions/sandbox/supervisor-relaunch.test.ts b/src/lib/actions/sandbox/supervisor-relaunch.test.ts index 08ea2622049..8a3d48bcedb 100644 --- a/src/lib/actions/sandbox/supervisor-relaunch.test.ts +++ b/src/lib/actions/sandbox/supervisor-relaunch.test.ts @@ -75,10 +75,11 @@ function baseDeps(overrides: ManagedSupervisorRelaunchDeps = {}) { })), removeBackup: vi.fn(() => true), runOpenshell: vi.fn(() => ({ status: 0, stdout: "No sandboxes found.\n" })), + runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:00 Ready\n"), recreate: vi.fn(() => patchResult()), finalize: vi.fn(({ supervisorReady }) => supervisorReady - ? { backupRemoved: true, rolledBack: false } + ? { backupRemoved: true, finalHandoffAcknowledged: true, rolledBack: false } : { backupRemoved: false, rolledBack: true }, ), ...overrides, @@ -148,6 +149,7 @@ describe("relaunchManagedSupervisorSession", () => { expect(relaunch?.finalize(true)).toEqual({ backupRemoved: true, + finalHandoffAcknowledged: true, rolledBack: false, stateRestored: true, stateBackupRemoved: true, @@ -156,12 +158,15 @@ describe("relaunchManagedSupervisorSession", () => { expect(deps.removeBackup).toHaveBeenCalledWith("alpha", "/tmp/rebuild-backups/alpha/recovery"); expect(deps.finalize).toHaveBeenCalledWith( { - lifecycleReleaseTimeoutSecs: 900, + finalHandoffTimeoutSecs: 900, result: expect.objectContaining({ newContainerId: "new-container-id" }), sandboxName: "alpha", supervisorReady: true, }, - { runOpenshell: deps.runOpenshell }, + { + runCaptureOpenshell: deps.runCaptureOpenshell, + runOpenshell: deps.runOpenshell, + }, ); }); @@ -389,12 +394,15 @@ describe("relaunchManagedSupervisorSession", () => { expect(deps.restartRestoredManagedGateway).toHaveBeenCalledWith("new-container-id"); expect(deps.finalize).toHaveBeenCalledWith( { - lifecycleReleaseTimeoutSecs: 900, + finalHandoffTimeoutSecs: 900, result: expect.objectContaining({ newContainerId: "new-container-id" }), sandboxName: "alpha", supervisorReady: true, }, - { runOpenshell: deps.runOpenshell }, + { + runCaptureOpenshell: deps.runCaptureOpenshell, + runOpenshell: deps.runOpenshell, + }, ); }); @@ -405,6 +413,7 @@ describe("relaunchManagedSupervisorSession", () => { expect(relaunch?.finalize(true)).toMatchObject({ backupRemoved: true, rolledBack: false }); expect(deps.finalize).toHaveBeenCalledWith(expect.objectContaining({ supervisorReady: true }), { + runCaptureOpenshell: deps.runCaptureOpenshell, runOpenshell: deps.runOpenshell, sleep, }); @@ -492,12 +501,34 @@ describe("relaunchManagedSupervisorSession", () => { expect(relaunch?.finalize(true)).toEqual({ backupRemoved: true, + finalHandoffAcknowledged: true, rolledBack: false, stateRestored: true, stateBackupRemoved: false, }); }); + it("retains the restored state backup when final handoff is not acknowledged (#9531)", () => { + const deps = baseDeps({ + finalize: vi.fn(() => ({ + backupRemoved: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: "Deleting", + rolledBack: false, + })), + }); + const relaunch = relaunchManagedSupervisorSession("alpha", { quiet: true, deps }); + + expect(relaunch?.finalize(true)).toEqual({ + backupRemoved: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: "Deleting", + rolledBack: false, + stateRestored: true, + }); + expect(deps.removeBackup).not.toHaveBeenCalled(); + }); + it("returns null when the pinned recreation fails", () => { const deps = baseDeps({ recreate: vi.fn(() => { diff --git a/src/lib/actions/sandbox/supervisor-relaunch.ts b/src/lib/actions/sandbox/supervisor-relaunch.ts index cf71bf3bf68..14d403e2316 100644 --- a/src/lib/actions/sandbox/supervisor-relaunch.ts +++ b/src/lib/actions/sandbox/supervisor-relaunch.ts @@ -59,6 +59,9 @@ export type ManagedSupervisorRelaunchDeps = { recreate?: typeof recreateOpenShellDockerSandboxWithStartupCommand; finalize?: typeof finalizeDockerGpuPatchBackup; runOpenshell?: NonNullable[1]>["runOpenshell"]; + runCaptureOpenshell?: NonNullable< + Parameters[1] + >["runCaptureOpenshell"]; }; function inspectContainer(containerId: string): DockerContainerInspect { @@ -287,23 +290,28 @@ export function relaunchManagedSupervisorSession( return finalizeFailure(); } const runLifecycleProbe = deps.runOpenshell; - if (!runLifecycleProbe) return finalizeFailure(); + const captureLifecycleProbe = deps.runCaptureOpenshell; + if (!runLifecycleProbe || !captureLifecycleProbe) return finalizeFailure(); const lifecycleDeps = { + runCaptureOpenshell: captureLifecycleProbe, runOpenshell: runLifecycleProbe, ...(deps.sleep ? { sleep: deps.sleep } : {}), }; + const finalized = finalize( + { + result, + supervisorReady: true, + sandboxName, + finalHandoffTimeoutSecs: getDockerGpuSupervisorReconnectTimeoutSecs(1), + }, + lifecycleDeps, + ); const outcome = { - ...finalize( - { - result, - supervisorReady: true, - sandboxName, - lifecycleReleaseTimeoutSecs: getDockerGpuSupervisorReconnectTimeoutSecs(1), - }, - lifecycleDeps, - ), + ...finalized, stateRestored: true, - stateBackupRemoved: removeSettledStateBackup(), + ...(finalized.finalHandoffAcknowledged === true + ? { stateBackupRemoved: removeSettledStateBackup() } + : {}), }; completed = { supervisorReady, outcome }; return outcome; diff --git a/src/lib/adapters/openshell/client.test.ts b/src/lib/adapters/openshell/client.test.ts index 038be1d759d..6f2a83da194 100644 --- a/src/lib/adapters/openshell/client.test.ts +++ b/src/lib/adapters/openshell/client.test.ts @@ -17,6 +17,7 @@ import { stripAnsi, versionGte, } from "./client"; +import { processTreeBoundedOpenshellInvocation } from "./process-tree-timeout"; interface SpawnResultSpec { status: number | null; @@ -51,6 +52,21 @@ function exitWithCode(code: number): never { } describe("openshell helpers", () => { + it("wraps a synchronous Linux probe in a process-group timeout (#10238)", () => { + expect( + processTreeBoundedOpenshellInvocation( + "/opt/openshell", + ["sandbox", "list"], + { killProcessTreeOnTimeout: true, timeout: 1000 }, + { platform: "linux", timeoutExecutableExists: () => true }, + ), + ).toEqual({ + binary: "/usr/bin/timeout", + args: ["--signal=KILL", "0.75s", "/opt/openshell", "sandbox", "list"], + killSignal: "SIGKILL", + }); + }); + afterEach(() => { vi.unstubAllEnvs(); }); diff --git a/src/lib/adapters/openshell/client.ts b/src/lib/adapters/openshell/client.ts index 012546d0422..14ca2134699 100644 --- a/src/lib/adapters/openshell/client.ts +++ b/src/lib/adapters/openshell/client.ts @@ -12,6 +12,7 @@ import { import { redirectInheritedChildStdoutToStderr } from "../../cli/stdout-guard"; import { buildSubprocessEnv } from "../../subprocess-env"; +import { processTreeBoundedOpenshellInvocation } from "./process-tree-timeout"; export { openshellSandboxSshHost, resolveOpenshellSandboxSshHost } from "./sandbox-ssh-host"; @@ -28,6 +29,7 @@ interface OpenshellSpawnOptions { env?: NodeJS.ProcessEnv; replaceEnv?: boolean; timeout?: number; + killProcessTreeOnTimeout?: boolean; ignoreError?: boolean; spawnSyncImpl?: OpenshellSpawnSync; errorLine?: (message: string) => void; @@ -53,6 +55,7 @@ export interface RunOpenshellOptions extends OpenshellSpawnOptions { export interface CaptureOpenshellOptions extends OpenshellSpawnOptions { includeStderr?: boolean; includeStreams?: boolean; + killSignal?: SpawnSyncOptions["killSignal"]; maxBuffer?: number; } @@ -207,14 +210,15 @@ export function runOpenshellCommand( opts: RunOpenshellOptions = {}, ): SpawnSyncReturns { const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; - const result = spawnSyncImpl(binary, args, { + const bounded = processTreeBoundedOpenshellInvocation(binary, args, opts); + const result = spawnSyncImpl(bounded.binary, bounded.args, { cwd: opts.cwd, env: openshellSpawnEnv(opts), encoding: "utf-8", stdio: redirectInheritedChildStdoutToStderr(opts.stdio ?? "inherit"), input: opts.input, timeout: opts.timeout, - killSignal: opts.killSignal, + killSignal: bounded.killSignal, maxBuffer: opts.maxBuffer, }); if (result.error) { @@ -236,12 +240,14 @@ export function captureOpenshellCommand( opts: CaptureOpenshellOptions = {}, ): CaptureOpenshellResult { const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; - const result = spawnSyncImpl(binary, args, { + const bounded = processTreeBoundedOpenshellInvocation(binary, args, opts); + const result = spawnSyncImpl(bounded.binary, bounded.args, { cwd: opts.cwd, env: openshellSpawnEnv(opts), encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], timeout: opts.timeout, + killSignal: bounded.killSignal, maxBuffer: opts.maxBuffer, }); if (result.error) { diff --git a/src/lib/adapters/openshell/process-tree-timeout.ts b/src/lib/adapters/openshell/process-tree-timeout.ts new file mode 100644 index 00000000000..cf494aa81ba --- /dev/null +++ b/src/lib/adapters/openshell/process-tree-timeout.ts @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { SpawnSyncOptions } from "node:child_process"; +import fs from "node:fs"; + +type ProcessTreeTimeoutDeps = { + platform?: NodeJS.Platform; + timeoutExecutableExists?: (pathname: string) => boolean; +}; + +export type ProcessTreeTimeoutOptions = { + killProcessTreeOnTimeout?: boolean; + killSignal?: SpawnSyncOptions["killSignal"]; + timeout?: number; +}; + +/** + * #10238 ownership decision: NemoClaw owns the wall-clock bound at its + * synchronous OpenShell adapter boundary. This remains opt-in for lifecycle + * probes; ordinary commands keep their existing execution behavior. Linux uses + * a process-group timeout so descendants cannot retain captured pipes after the + * direct CLI is killed. Real DGX Spark confirmation remains tracked by #10238. + */ +export function processTreeBoundedOpenshellInvocation( + binary: string, + args: readonly string[], + opts: ProcessTreeTimeoutOptions, + deps: ProcessTreeTimeoutDeps = {}, +): { binary: string; args: string[]; killSignal?: SpawnSyncOptions["killSignal"] } { + if (opts.killProcessTreeOnTimeout !== true) { + return { binary, args: [...args], killSignal: opts.killSignal }; + } + const timeoutMs = Number(opts.timeout); + const platform = deps.platform ?? process.platform; + const timeoutExecutableExists = deps.timeoutExecutableExists ?? fs.existsSync; + if ( + platform !== "linux" || + !timeoutExecutableExists("/usr/bin/timeout") || + !Number.isFinite(timeoutMs) || + timeoutMs <= 0 + ) { + return { binary, args: [...args], killSignal: "SIGKILL" }; + } + const groupTimeoutSeconds = Math.max(1, Math.floor(timeoutMs) - 250) / 1000; + return { + binary: "/usr/bin/timeout", + args: ["--signal=KILL", `${String(groupTimeoutSeconds)}s`, binary, ...args], + killSignal: "SIGKILL", + }; +} diff --git a/src/lib/adapters/openshell/runtime.ts b/src/lib/adapters/openshell/runtime.ts index 87a21b47359..c6dc0435afb 100644 --- a/src/lib/adapters/openshell/runtime.ts +++ b/src/lib/adapters/openshell/runtime.ts @@ -31,6 +31,7 @@ type RunnerOptions = { includeStreams?: boolean; timeout?: number; killSignal?: NodeJS.Signals; + killProcessTreeOnTimeout?: boolean; maxBuffer?: number; }; @@ -59,6 +60,7 @@ export function runOpenshell(args: CommandArgs, opts: RunnerOptions = {}) { ignoreError: opts.ignoreError, timeout: opts.timeout, killSignal: opts.killSignal, + killProcessTreeOnTimeout: opts.killProcessTreeOnTimeout, maxBuffer: opts.maxBuffer, errorLine: console.error, exit: (code: number) => process.exit(code), @@ -79,6 +81,8 @@ export function captureOpenshell(args: CommandArgs, opts: RunnerOptions = {}) { includeStderr: opts.includeStderr, includeStreams: opts.includeStreams, timeout: opts.timeout, + killSignal: opts.killSignal, + killProcessTreeOnTimeout: opts.killProcessTreeOnTimeout, maxBuffer: opts.maxBuffer, errorLine: console.error, exit: (code: number) => process.exit(code), @@ -98,6 +102,8 @@ export function captureResolvedOpenshell(args: CommandArgs, opts: RunnerOptions includeStderr: opts.includeStderr, includeStreams: opts.includeStreams, timeout: opts.timeout, + killSignal: opts.killSignal, + killProcessTreeOnTimeout: opts.killProcessTreeOnTimeout, maxBuffer: opts.maxBuffer, errorLine: console.error, exit: (code: number) => process.exit(code), diff --git a/src/lib/onboard/docker-gpu-patch-diagnostics.ts b/src/lib/onboard/docker-gpu-patch-diagnostics.ts index ef9fda3317e..cfb61b78ef2 100644 --- a/src/lib/onboard/docker-gpu-patch-diagnostics.ts +++ b/src/lib/onboard/docker-gpu-patch-diagnostics.ts @@ -243,6 +243,8 @@ export function collectDockerGpuPatchDiagnostics( `old_container_id=${redactor.redactText(context?.oldContainerId ?? "unknown")}`, `new_container_id=${redactor.redactText(context?.newContainerId ?? "unknown")}`, `backup_container_name=${redactor.redactText(context?.backupContainerName ?? "none")}`, + `backup_removed=${confirmationValue(context?.backupRemoved)}`, + `last_openshell_phase=${redactor.redactText(context?.lastSandboxPhase ?? "unknown")}`, `rolled_back=${cleanupPendingRollback ? "pending" : context?.rolledBack === true ? "yes" : context?.rolledBack === false ? "failed" : "no"}`, ...(context?.replacementStopConfirmed !== undefined ? [`replacement_stop_confirmed=${confirmationValue(context.replacementStopConfirmed)}`] diff --git a/src/lib/onboard/docker-gpu-patch-finalize.test.ts b/src/lib/onboard/docker-gpu-patch-finalize.test.ts index b3348d8fb30..5c917ebe1cb 100644 --- a/src/lib/onboard/docker-gpu-patch-finalize.test.ts +++ b/src/lib/onboard/docker-gpu-patch-finalize.test.ts @@ -30,6 +30,25 @@ function deferredCreateResult(): DockerGpuPatchResult { }; } +function exactDeferredCreateResult(): DockerGpuPatchResult { + return { + ...deferredCreateResult(), + oldContainerId: "a".repeat(64), + newContainerId: "b".repeat(64), + }; +} + +function readyHandoffDeps() { + return { + runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:00 Ready\n"), + runOpenshell: vi.fn((args: readonly string[]) => + args[1] === "list" + ? { status: 0, stdout: "beta 2026-08-23 10:00:00 Ready\n" } + : { status: 0 }, + ), + }; +} + function collectRollbackDiagnostics( newContainerId: string, outcome: DockerGpuPatchFinalizeOutcome, @@ -63,52 +82,35 @@ function collectRollbackDiagnostics( } describe("finalizeDockerGpuPatchBackup", () => { - it("makes the replacement restart the final lifecycle event after removing the backup", () => { + it("retains both containers when final acknowledgement probes are unavailable (#9531)", () => { const dockerStop = vi.fn(() => ({ status: 0 })); - const dockerRm = vi.fn((_name: string) => ({ status: 0 })); + const dockerRm = vi.fn(() => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( - { - result: deferredCreateResult(), - supervisorReady: true, - sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, - }, - { - dockerStop, - dockerRm, - dockerStart, - runOpenshell: vi.fn(() => ({ status: 0, stdout: "No sandboxes found.\n" })), - }, - ); - expect(outcome).toEqual({ - backupRemoved: true, + + expect( + finalizeDockerGpuPatchBackup( + { + result: exactDeferredCreateResult(), + supervisorReady: true, + sandboxName: "alpha", + finalHandoffTimeoutSecs: 60, + }, + { dockerRm, dockerStart, dockerStop }, + ), + ).toEqual({ + backupRemoved: false, rolledBack: false, - replacementStoppedForCommit: true, - replacementRestarted: true, - lifecycleReleaseObserved: true, + replacementStoppedForCommit: false, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, }); - expect(dockerStop).toHaveBeenCalledWith( - "new-container-id", - expect.objectContaining({ ignoreError: true }), - ); - expect(dockerRm).toHaveBeenCalledWith( - "openshell-alpha-nemoclaw-gpu-backup-1780491860342", - expect.objectContaining({ ignoreError: true }), - ); - expect(dockerStart).toHaveBeenCalledWith( - "new-container-id", - expect.objectContaining({ ignoreError: true }), - ); - expect(dockerStop.mock.invocationCallOrder[0]).toBeLessThan( - dockerRm.mock.invocationCallOrder[0], - ); - expect(dockerRm.mock.invocationCallOrder[0]).toBeLessThan( - dockerStart.mock.invocationCallOrder[0], - ); + expect(dockerStop).not.toHaveBeenCalled(); + expect(dockerRm).not.toHaveBeenCalled(); + expect(dockerStart).not.toHaveBeenCalled(); }); - it("waits for the sandbox name to disappear before restarting the replacement (#9531)", () => { + it("uses one exact stop, remove, start, and Ready acknowledgement handoff (#9531)", () => { + const result = exactDeferredCreateResult(); const events: string[] = []; const dockerStop = vi.fn(() => { events.push("stop replacement"); @@ -122,216 +124,218 @@ describe("finalizeDockerGpuPatchBackup", () => { events.push("start replacement"); return { status: 0 }; }); - const runOpenshell = vi - .fn() - .mockImplementationOnce(() => { - events.push("observe deleting"); - return { status: 0, stdout: "alpha 2026-08-21 05:53:16 Deleting\n" }; - }) - .mockImplementationOnce(() => { - events.push("observe error"); - return { status: 0, stdout: "alpha 2026-08-21 05:53:18 Error\n" }; - }) - .mockImplementationOnce(() => { - events.push("observe name absence"); - return { status: 0, stdout: "beta 2026-08-21 05:53:20 Ready\n" }; - }); + const runCaptureOpenshell = vi.fn(() => { + events.push("observe ready"); + return "alpha 2026-08-23 10:00:00 Ready\n"; + }); + const runOpenshellResults = { + exec: { event: "exec ready", result: { status: 0 } }, + list: { + event: "observe lifecycle release", + result: { status: 0, stdout: "beta 2026-08-23 10:00:00 Ready\n" }, + }, + } as const; + const runOpenshell = vi.fn((args: readonly string[]) => { + const response = runOpenshellResults[args[1] === "list" ? "list" : "exec"]; + events.push(response.event); + return response.result; + }); + const dockerResults = { + ps: { + event: "confirm sole replacement", + result: { status: 0, stdout: `${result.newContainerId}\n` }, + }, + inspect: { event: "confirm running replacement", result: { status: 0, stdout: "true\n" } }, + } as const; + const dockerRun = vi.fn((args: readonly string[]) => { + const response = dockerResults[String(args[0]) as keyof typeof dockerResults]; + events.push(response.event); + return response.result; + }); const outcome = finalizeDockerGpuPatchBackup( { - result: deferredCreateResult(), + result, supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, + finalHandoffTimeoutSecs: 60, + }, + { + dockerStop, + dockerRm, + dockerRun, + dockerStart, + runCaptureOpenshell, + runOpenshell, + sleep: vi.fn(), }, - { dockerStop, dockerRm, dockerStart, runOpenshell, sleep: vi.fn() }, ); - expect(outcome).toMatchObject({ + expect(outcome).toEqual({ backupRemoved: true, - lifecycleReleaseObserved: true, + rolledBack: false, + replacementStoppedForCommit: true, replacementRestarted: true, + lifecycleReleaseObserved: true, + finalHandoffAcknowledged: true, + lastSandboxPhase: "Ready", }); expect(events).toEqual([ "stop replacement", "remove backup", - "observe deleting", - "observe error", - "observe name absence", + "observe lifecycle release", "start replacement", + "observe ready", + "exec ready", + "confirm sole replacement", + "confirm running replacement", ]); + expect(dockerStop).toHaveBeenCalledWith( + result.newContainerId, + expect.objectContaining({ ignoreError: true }), + ); + expect(dockerRm).toHaveBeenCalledWith( + result.oldContainerId, + expect.objectContaining({ ignoreError: true }), + ); + expect(dockerStart).toHaveBeenCalledWith( + result.newContainerId, + expect.objectContaining({ ignoreError: true }), + ); }); - it.each(["Error", "Deleting"])( - "accepts %s for the exact stopped replacement despite stale legacy name metadata (#9962)", - (phase) => { - const replacementContainerId = "a".repeat(64); + it("fails immediately when OpenShell reports Deleting after the final start (#9531)", () => { + const result = exactDeferredCreateResult(); const events: string[] = []; - const dockerStop = vi.fn(() => { - events.push("stop replacement"); - return { status: 0 }; - }); - const dockerRm = vi.fn(() => { - events.push("remove backup"); - return { status: 0 }; - }); - const dockerRun = vi.fn((_args: readonly string[]) => { - events.push("confirm exact replacement"); - return { status: 0, stdout: `${replacementContainerId}\n` }; - }); - const dockerStart = vi.fn(() => { - events.push("start replacement"); - return { status: 0 }; - }); - const runOpenshell = vi.fn(() => { - events.push("observe retiring phase"); - return { status: 0, stdout: `restored-name 2026-08-23 01:40:35 ${phase}\n` }; - }); - + const sleep = vi.fn(); const outcome = finalizeDockerGpuPatchBackup( { - result: { ...deferredCreateResult(), newContainerId: replacementContainerId }, + result, supervisorReady: true, - sandboxName: "restored-name", - lifecycleReleaseTimeoutSecs: 60, + sandboxName: "alpha", + finalHandoffTimeoutSecs: 60, + }, + { + dockerStop: vi.fn(() => { + events.push("stop replacement"); + return { status: 0 }; + }), + dockerRm: vi.fn(() => { + events.push("remove backup"); + return { status: 0 }; + }), + dockerStart: vi.fn(() => { + events.push("start replacement"); + return { status: 0 }; + }), + runCaptureOpenshell: vi.fn(() => { + events.push("observe deleting"); + return "alpha 2026-08-23 10:00:00 Deleting\n"; + }), + runOpenshell: vi.fn((args: readonly string[]) => + args[1] === "list" + ? { status: 0, stdout: "beta 2026-08-23 10:00:00 Ready\n" } + : { status: 1 }, + ), + dockerRun: vi.fn(() => ({ status: 0, stdout: `${result.newContainerId}\n` })), + sleep, }, - { dockerStop, dockerRm, dockerRun, dockerStart, runOpenshell, sleep: vi.fn() }, ); - expect(outcome).toMatchObject({ + expect(outcome).toEqual({ backupRemoved: true, - lifecycleReleaseObserved: true, + rolledBack: false, + replacementStoppedForCommit: true, replacementRestarted: true, + lifecycleReleaseObserved: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: "Deleting", }); expect(events).toEqual([ "stop replacement", "remove backup", - "observe retiring phase", - "confirm exact replacement", "start replacement", + "observe deleting", ]); - expect(dockerRun).toHaveBeenCalledWith( - [ - "ps", - "-a", - "--no-trunc", - "--filter", - `id=${replacementContainerId}`, - "--filter", - "label=openshell.ai/managed-by=openshell", - "--format", - "{{.ID}}", - ], - expect.objectContaining({ ignoreError: true, suppressOutput: true }), - ); - expect(dockerRun.mock.calls[0]?.[0]).not.toContain( - "label=openshell.ai/sandbox-name=restored-name", - ); - }, - ); - - it("caps Error corroboration to the remaining lifecycle-release budget (#9962)", () => { - const replacementContainerId = "a".repeat(64); - vi.useFakeTimers(); - vi.setSystemTime(0); - const dockerRun = vi.fn(() => ({ - status: 0, - stdout: `${replacementContainerId}\n`, - })); - - let outcome: DockerGpuPatchFinalizeOutcome; - try { - outcome = finalizeDockerGpuPatchBackup( - { - result: { ...deferredCreateResult(), newContainerId: replacementContainerId }, - supervisorReady: true, - sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 1, - }, - { - dockerStop: vi.fn(() => ({ status: 0 })), - dockerRm: vi.fn(() => ({ status: 0 })), - dockerRun, - dockerStart: vi.fn(() => ({ status: 0 })), - runOpenshell: vi.fn(() => { - vi.setSystemTime(750); - return { - status: 0, - stdout: "alpha 2026-08-23 01:40:35 Error\n", - }; - }), - sleep: vi.fn(), - }, - ); - } finally { - vi.useRealTimers(); - } + expect(sleep).not.toHaveBeenCalled(); + }); - expect(outcome).toMatchObject({ - lifecycleReleaseObserved: true, - replacementRestarted: true, - }); - expect(dockerRun).toHaveBeenCalledWith( - expect.any(Array), - expect.objectContaining({ timeout: 250 }), + it("accepts a retiring Error row only when the exact replacement has the OpenShell label (#9962)", () => { + const result = exactDeferredCreateResult(); + const dockerRunResults = { + inspect: { status: 0, stdout: "true\n" }, + ps: { status: 0, stdout: `${result.newContainerId}\n` }, + } as const; + const dockerRun = vi.fn( + (args: readonly string[]) => + dockerRunResults[String(args[0]) as keyof typeof dockerRunResults], ); - }); - it.each([ - ["a failed Docker query", { status: 1, stderr: "daemon unavailable" }], - ["no labeled container", { status: 0, stdout: "" }], - ["another labeled container", { status: 0, stdout: `${"b".repeat(64)}\n` }], - [ - "multiple labeled containers", - { status: 0, stdout: `${"a".repeat(64)}\n${"b".repeat(64)}\n` }, - ], - ["a truncated replacement ID", { status: 0, stdout: `${"a".repeat(12)}\n` }], - ])("does not accept Error when exact replacement corroboration returns %s (#9962)", (_case, dockerResult) => { - const replacementContainerId = "a".repeat(64); - const dockerStart = vi.fn(() => ({ status: 0 })); const outcome = finalizeDockerGpuPatchBackup( { - result: { ...deferredCreateResult(), newContainerId: replacementContainerId }, + result, supervisorReady: true, - sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 1, + sandboxName: "restored-name", + finalHandoffTimeoutSecs: 60, }, { dockerStop: vi.fn(() => ({ status: 0 })), dockerRm: vi.fn(() => ({ status: 0 })), - dockerRun: vi.fn(() => dockerResult), - dockerStart, - runOpenshell: vi.fn(() => ({ - status: 0, - stdout: "alpha 2026-08-23 01:40:35 Error\n", - })), + dockerStart: vi.fn(() => ({ status: 0 })), + dockerRun, + runCaptureOpenshell: vi.fn(() => "restored-name 2026-08-23 01:40:35 Ready\n"), + runOpenshell: vi.fn((args: readonly string[]) => + args[1] === "list" + ? { status: 0, stdout: "restored-name 2026-08-23 01:40:35 Error\n" } + : { status: 0 }, + ), sleep: vi.fn(), }, ); expect(outcome).toMatchObject({ - lifecycleReleaseObserved: false, - replacementRestarted: false, + backupRemoved: true, + lifecycleReleaseObserved: true, + finalHandoffAcknowledged: true, }); - expect(dockerStart).not.toHaveBeenCalled(); + expect(dockerRun.mock.calls[0]?.[0]).toEqual([ + "ps", + "-a", + "--no-trunc", + "--filter", + "label=openshell.ai/managed-by=openshell", + "--filter", + "label=openshell.ai/sandbox-name=restored-name", + "--format", + "{{.ID}}", + ]); }); - it("does not accept Error when the exact Docker query throws (#9962)", () => { + it.each([ + ["a failed query", { status: 1, stderr: "daemon unavailable" }], + ["no labeled replacement", { status: 0, stdout: "" }], + ["a different replacement", { status: 0, stdout: `${"c".repeat(64)}\n` }], + [ + "multiple labeled replacements", + { status: 0, stdout: `${"b".repeat(64)}\n${"c".repeat(64)}\n` }, + ], + ])("rejects retiring Error when the canonical query returns %s (#9531)", (_case, query) => { + const result = exactDeferredCreateResult(); const dockerStart = vi.fn(() => ({ status: 0 })); + const outcome = finalizeDockerGpuPatchBackup( { - result: { ...deferredCreateResult(), newContainerId: "a".repeat(64) }, + result, supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 1, + finalHandoffTimeoutSecs: 1, }, { dockerStop: vi.fn(() => ({ status: 0 })), dockerRm: vi.fn(() => ({ status: 0 })), - dockerRun: vi.fn(() => { - throw new Error("daemon unavailable"); - }), + dockerRun: vi.fn(() => query), dockerStart, + runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 01:40:35 Ready\n"), runOpenshell: vi.fn(() => ({ status: 0, stdout: "alpha 2026-08-23 01:40:35 Error\n", @@ -340,74 +344,11 @@ describe("finalizeDockerGpuPatchBackup", () => { }, ); - expect(outcome).toMatchObject({ - lifecycleReleaseObserved: false, - replacementRestarted: false, - }); - expect(dockerStart).not.toHaveBeenCalled(); - }); - - it("does not treat failed lifecycle probes as a release receipt (#9531)", () => { - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 0, stdout: "Error: gateway unavailable" }) - .mockReturnValueOnce({ status: 1, stderr: "gateway unavailable" }); - const dockerStart = vi.fn(() => ({ status: 0 })); - - const outcome = finalizeDockerGpuPatchBackup( - { - result: deferredCreateResult(), - supervisorReady: true, - sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 1, - }, - { - dockerStop: vi.fn(() => ({ status: 0 })), - dockerRm: vi.fn(() => ({ status: 0 })), - dockerStart, - runOpenshell, - sleep: vi.fn(), - }, - ); - expect(outcome).toMatchObject({ backupRemoved: true, lifecycleReleaseObserved: false, replacementRestarted: false, }); - expect(runOpenshell).toHaveBeenCalledTimes(2); - expect(runOpenshell.mock.calls[0]?.[1]?.timeout).toBeGreaterThan(0); - expect(runOpenshell.mock.calls[0]?.[1]?.timeout).toBeLessThanOrEqual(1000); - expect(runOpenshell.mock.calls[1]?.[1]?.timeout).toBeGreaterThan(0); - expect(runOpenshell.mock.calls[1]?.[1]?.timeout).toBeLessThanOrEqual(1000); - expect(dockerStart).not.toHaveBeenCalled(); - }); - - it("does not treat an unrelated terminal lifecycle phase as the stopped replacement (#9531)", () => { - const runOpenshell = vi.fn(() => ({ - status: 0, - stdout: "alpha 2026-08-21 05:53:18 Failed\n", - })); - - const dockerStart = vi.fn(() => ({ status: 0 })); - const outcome = finalizeDockerGpuPatchBackup( - { - result: deferredCreateResult(), - supervisorReady: true, - sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 1, - }, - { - dockerStop: vi.fn(() => ({ status: 0 })), - dockerRm: vi.fn(() => ({ status: 0 })), - dockerStart, - runOpenshell, - sleep: vi.fn(), - }, - ); - - expect(outcome.lifecycleReleaseObserved).toBe(false); - expect(runOpenshell).toHaveBeenCalledTimes(2); expect(dockerStart).not.toHaveBeenCalled(); }); @@ -505,7 +446,7 @@ describe("finalizeDockerGpuPatchBackup", () => { result, supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, + finalHandoffTimeoutSecs: 60, }, { dockerRm }, ); @@ -525,22 +466,26 @@ describe("finalizeDockerGpuPatchBackup", () => { result: deferredCreateResult(), supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, + finalHandoffTimeoutSecs: 60, }, - { dockerStop, dockerRm, dockerStart }, + { dockerStop, dockerRm, dockerStart, ...readyHandoffDeps() }, ); expect(outcome).toEqual({ backupRemoved: false, rolledBack: false, replacementStoppedForCommit: true, - replacementRestarted: false, - lifecycleReleaseObserved: false, + replacementRestarted: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, }); expect(dockerRm).toHaveBeenCalledWith( - "openshell-alpha-nemoclaw-gpu-backup-1780491860342", + "old-container-id", + expect.objectContaining({ ignoreError: true }), + ); + expect(dockerStart).toHaveBeenCalledWith( + "new-container-id", expect.objectContaining({ ignoreError: true }), ); - expect(dockerStart).not.toHaveBeenCalled(); }); it("fails closed when backup removal has no exit status", () => { @@ -552,18 +497,22 @@ describe("finalizeDockerGpuPatchBackup", () => { result: deferredCreateResult(), supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, + finalHandoffTimeoutSecs: 60, }, - { dockerStop, dockerRm, dockerStart }, + { dockerStop, dockerRm, dockerStart, ...readyHandoffDeps() }, ); expect(outcome).toEqual({ backupRemoved: false, rolledBack: false, replacementStoppedForCommit: true, - replacementRestarted: false, - lifecycleReleaseObserved: false, + replacementRestarted: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, }); - expect(dockerStart).not.toHaveBeenCalled(); + expect(dockerStart).toHaveBeenCalledWith( + "new-container-id", + expect.objectContaining({ ignoreError: true }), + ); }); it("retains the backup when the replacement cannot be stopped for the final handoff", () => { @@ -576,9 +525,9 @@ describe("finalizeDockerGpuPatchBackup", () => { result: deferredCreateResult(), supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, + finalHandoffTimeoutSecs: 60, }, - { dockerStop, dockerRm, dockerStart }, + { dockerStop, dockerRm, dockerStart, ...readyHandoffDeps() }, ); expect(outcome).toEqual({ @@ -596,13 +545,13 @@ describe("finalizeDockerGpuPatchBackup", () => { result: deferredCreateResult(), supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 60, + finalHandoffTimeoutSecs: 60, }, { dockerStop: vi.fn(() => ({ status: 0 })), dockerRm: vi.fn(() => ({ status: 0 })), dockerStart: vi.fn(() => ({ status: 1 })), - runOpenshell: vi.fn(() => ({ status: 0, stdout: "No sandboxes found.\n" })), + ...readyHandoffDeps(), }, ); @@ -611,7 +560,8 @@ describe("finalizeDockerGpuPatchBackup", () => { rolledBack: false, replacementStoppedForCommit: true, replacementRestarted: false, - lifecycleReleaseObserved: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, }); }); diff --git a/src/lib/onboard/docker-gpu-patch-finalize.ts b/src/lib/onboard/docker-gpu-patch-finalize.ts index b1cd396a087..7a1c09fe3c1 100644 --- a/src/lib/onboard/docker-gpu-patch-finalize.ts +++ b/src/lib/onboard/docker-gpu-patch-finalize.ts @@ -9,19 +9,23 @@ // that natively accepts NVIDIA GPU access would remove the need for the // post-create container recreation NemoClaw performs here. Until OpenShell // supports that natively, NemoClaw recreates the container with GPU access -// and uses this module to either confirm the new container or restore the -// pre-patch backup. Regression coverage: +// and uses this module to either restore the pre-patch backup before commit or +// complete the exact stop/remove/start handoff and require OpenShell's final +// Ready acknowledgement. Removing the old container is the irreversible +// commit point: later failures require a sandbox rebuild rather than automatic +// rollback. Regression coverage: // * src/lib/onboard/docker-gpu-patch-finalize.test.ts — direct unit tests -// for finalize success / rollback / no-op / rollback failure outcomes. +// for exact final handoff, terminal phase, rollback, and failure outcomes. // * src/lib/onboard/docker-gpu-patch-rollback.test.ts — composed // recreate-with-rollback scenarios. -// * src/lib/onboard/docker-gpu-sandbox-create.test.ts — composed create +// * src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts — composed create // flow driving maybeApplyDuringCreate → waitForSupervisorReconnect → // finalizeBackup. // Removal condition: when OpenShell supports native Docker-driver GPU // creation/reconnect, drop the NemoClaw post-create container recreation -// and delete this module along with its callers in docker-gpu-patch.ts and -// docker-gpu-sandbox-create.ts. +// and delete this module along with its direct callers in +// docker-gpu-patch-recreate.ts, docker-gpu-sandbox-create.ts, and +// src/lib/actions/sandbox/supervisor-relaunch.ts. import { hasZeroDockerExitStatus } from "./docker-command-result"; import { DOCKER_GPU_PATCH_TIMEOUT_MS } from "./docker-gpu-patch-constants"; @@ -31,11 +35,11 @@ import { } from "./docker-gpu-patch-rollback"; import { fullDockerContainerId } from "./docker-gpu-patch-clone"; import type { DockerGpuPatchDeps, DockerGpuPatchResult } from "./docker-gpu-patch-types"; -import { waitForOpenShellSandboxLifecycleRelease } from "./docker-gpu-supervisor-reconnect"; import { - OPENSHELL_MANAGED_BY_LABEL, - OPENSHELL_MANAGED_BY_VALUE, -} from "./openshell-docker-sandbox-containers"; + waitForOpenShellFinalHandoff, + waitForOpenShellSandboxLifecycleRelease, +} from "./docker-gpu-supervisor-reconnect"; +import { queryOpenShellDockerSandboxContainers } from "./openshell-docker-sandbox-containers"; export { restoreDockerGpuPatchBackupAfterRecreateFailure as rollbackDockerGpuPatchOnRecreateFailure, @@ -51,21 +55,25 @@ export type DockerGpuPatchFinalizeOptions = result: DockerGpuPatchResult; supervisorReady: true; sandboxName: string; - lifecycleReleaseTimeoutSecs: number; + finalHandoffTimeoutSecs: number; }; export type DockerGpuPatchFinalizeOutcome = { + /** True once the old container has crossed the irreversible removal boundary. */ backupRemoved: boolean; rolledBack: boolean; replacementStoppedForCommit?: boolean; replacementRestarted?: boolean; lifecycleReleaseObserved?: boolean; + finalHandoffAcknowledged?: boolean; + lastSandboxPhase?: string | null; replacementStopConfirmed?: boolean; replacementRemovalConfirmed?: boolean; replacementPresence?: "absent" | "present" | "unknown"; }; -function isExactOpenShellReplacement( +function isExactRunningReplacement( + sandboxName: string, replacementContainerId: string, dockerRun: NonNullable, timeoutMs: number, @@ -73,33 +81,33 @@ function isExactOpenShellReplacement( const expectedContainerId = fullDockerContainerId(replacementContainerId); if (!expectedContainerId || timeoutMs <= 0) return false; try { - const query = dockerRun( + const deadline = Date.now() + timeoutMs; + const containers = queryOpenShellDockerSandboxContainers(sandboxName, { dockerRun }, timeoutMs); + if ( + !containers.ok || + containers.ids.length !== 1 || + fullDockerContainerId(containers.ids[0]) !== expectedContainerId + ) { + return false; + } + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) return false; + const inspect = dockerRun( [ - "ps", - "-a", - "--no-trunc", - "--filter", - `id=${expectedContainerId}`, - "--filter", - `label=${OPENSHELL_MANAGED_BY_LABEL}=${OPENSHELL_MANAGED_BY_VALUE}`, + "inspect", + "--type", + "container", "--format", - "{{.ID}}", + "{{json .State.Running}}", + expectedContainerId, ], { ignoreError: true, suppressOutput: true, - timeout: Math.max(1, Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, Math.floor(timeoutMs))), + timeout: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingMs), }, ); - if (!hasZeroDockerExitStatus(query)) return false; - const containerIds = String(query.stdout ?? "") - .split(/\r?\n/u) - .map((line) => line.trim()) - .filter(Boolean); - return ( - containerIds.length === 1 && - fullDockerContainerId(containerIds[0]) === expectedContainerId - ); + return hasZeroDockerExitStatus(inspect) && String(inspect.stdout ?? "").trim() === "true"; } catch { return false; } @@ -119,12 +127,21 @@ export function finalizeDockerGpuPatchBackup( return { backupRemoved: true, rolledBack: false }; } if (options.supervisorReady) { - // Stop the replacement before retiring the labelled backup, then start it - // afterward. OpenShell observes Docker lifecycle events for both containers; - // leaving the backup's removal as the final event can demote the already - // reconnected replacement back to not-ready. The final start makes the live - // replacement's registration authoritative while the rollback container is - // still retained until the destructive removal succeeds. + // Stop the exact replacement before retiring the exact backup, then start + // the replacement afterward. The final start is the authoritative Docker + // lifecycle event. Backup removal is the irreversible commit point; + // failures after it require a sandbox rebuild. Success is withheld until + // OpenShell reports Ready and Docker still proves the exact replacement is + // the sole running labeled container (#9531). + if (!deps.runOpenshell || !deps.runCaptureOpenshell) { + return { + backupRemoved: false, + rolledBack: false, + replacementStoppedForCommit: false, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, + }; + } const stopResult = resolved.dockerStop(options.result.newContainerId, containerOpts); if (!hasZeroDockerExitStatus(stopResult)) { return { @@ -133,48 +150,96 @@ export function finalizeDockerGpuPatchBackup( replacementStoppedForCommit: false, }; } - const rmResult = resolved.dockerRm(options.result.backupContainerName, containerOpts); + const rmResult = resolved.dockerRm(options.result.oldContainerId, containerOpts); const backupRemoved = hasZeroDockerExitStatus(rmResult); - const sandboxName = options.sandboxName; - const lifecycleReleaseTimeoutSecs = options.lifecycleReleaseTimeoutSecs; - const hasLifecycleContext = - sandboxName.length > 0 && - Number.isFinite(lifecycleReleaseTimeoutSecs) && - lifecycleReleaseTimeoutSecs > 0; - if (backupRemoved && hasLifecycleContext) { - console.log( - ` Waiting for OpenShell to retire the previous lifecycle record before restarting the replacement (up to ${lifecycleReleaseTimeoutSecs}s)...`, + if (!backupRemoved) { + const replacementRestarted = hasZeroDockerExitStatus( + resolved.dockerStart(options.result.newContainerId, containerOpts), ); + return { + backupRemoved: false, + rolledBack: false, + replacementStoppedForCommit: true, + replacementRestarted, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, + }; } - const lifecycleReleaseObserved = - backupRemoved && hasLifecycleContext - ? waitForOpenShellSandboxLifecycleRelease(sandboxName, lifecycleReleaseTimeoutSecs, { - runOpenshell: deps.runOpenshell, - sleep: deps.sleep, - soleLabeledReplacementCorroboratesRetiringPhase: (remainingMs) => - isExactOpenShellReplacement( - options.result.newContainerId, - resolved.dockerRun, - remainingMs, - ), - }) - : false; + console.log( + ` Waiting for OpenShell to retire the previous lifecycle record before restarting the replacement (up to ${options.finalHandoffTimeoutSecs}s)...`, + ); + const lifecycleReleaseObserved = waitForOpenShellSandboxLifecycleRelease( + options.sandboxName, + options.finalHandoffTimeoutSecs, + { + runOpenshell: deps.runOpenshell, + sleep: deps.sleep, + soleLabeledReplacementCorroboratesRetiringPhase: (remainingMs) => { + const expectedContainerId = fullDockerContainerId(options.result.newContainerId); + if (!expectedContainerId || remainingMs <= 0) return false; + const containers = queryOpenShellDockerSandboxContainers( + options.sandboxName, + { dockerRun: resolved.dockerRun }, + remainingMs, + ); + return ( + containers.ok && + containers.ids.length === 1 && + fullDockerContainerId(containers.ids[0]) === expectedContainerId + ); + }, + }, + ); if (!lifecycleReleaseObserved) { return { - backupRemoved, + backupRemoved: true, rolledBack: false, replacementStoppedForCommit: true, replacementRestarted: false, lifecycleReleaseObserved: false, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, }; } const startResult = resolved.dockerStart(options.result.newContainerId, containerOpts); + const replacementRestarted = hasZeroDockerExitStatus(startResult); + if (!replacementRestarted) { + return { + backupRemoved: true, + rolledBack: false, + replacementStoppedForCommit: true, + replacementRestarted, + finalHandoffAcknowledged: false, + lastSandboxPhase: null, + }; + } + console.log( + ` Waiting for OpenShell to confirm the final replacement handoff (up to ${options.finalHandoffTimeoutSecs}s)...`, + ); + const acknowledgement = waitForOpenShellFinalHandoff( + options.sandboxName, + options.finalHandoffTimeoutSecs, + { + runCaptureOpenshell: deps.runCaptureOpenshell, + runOpenshell: deps.runOpenshell, + sleep: deps.sleep, + replacementIsExactAndRunning: (remainingMs) => + isExactRunningReplacement( + options.sandboxName, + options.result.newContainerId, + resolved.dockerRun, + remainingMs, + ), + }, + ); return { - backupRemoved, + backupRemoved: true, rolledBack: false, replacementStoppedForCommit: true, - replacementRestarted: hasZeroDockerExitStatus(startResult), + replacementRestarted: true, lifecycleReleaseObserved: true, + finalHandoffAcknowledged: acknowledgement.acknowledged, + lastSandboxPhase: acknowledgement.lastSandboxPhase, }; } const rollback = rollbackToBackupContainer( @@ -187,39 +252,3 @@ export function finalizeDockerGpuPatchBackup( ); return { backupRemoved: false, ...rollback }; } - -export type SupervisorReconnectOutcome = - | { execReady: true; backupRemoved: boolean } - | ({ execReady: false; error: Error } & Omit); - -export function reconcileSupervisorReconnect( - execReady: boolean, - refs: { newContainerId: string; backupContainerName: string; originalName: string }, - deps: DockerGpuPatchDeps, -): SupervisorReconnectOutcome { - const resolved = resolveDockerGpuPatchRollbackDeps(deps); - const containerOpts = { - ignoreError: true, - suppressOutput: true, - timeout: DOCKER_GPU_PATCH_TIMEOUT_MS, - }; - if (execReady) { - // Backup removal is best-effort here too: the supervisor probe already - // confirmed the new container is reachable, so a failed rm leaves a - // leaked backup container but the user-visible sandbox is healthy. - // Surface the actual rm status so callers can fold it into diagnostics - // alongside the deferred-finalize path in `finalizeDockerGpuPatchBackup`. - const rmResult = resolved.dockerRm(refs.backupContainerName, containerOpts); - return { execReady: true, backupRemoved: hasZeroDockerExitStatus(rmResult) }; - } - const rollback = rollbackToBackupContainer(refs, resolved); - return { - execReady: false, - ...rollback, - error: new Error( - rollback.rolledBack - ? "OpenShell supervisor did not reconnect to the GPU-enabled container; pre-patch sandbox restored." - : "OpenShell supervisor did not reconnect to the GPU-enabled container and rollback failed; pre-patch sandbox was NOT restored.", - ), - }; -} diff --git a/src/lib/onboard/docker-gpu-patch-jetson.test.ts b/src/lib/onboard/docker-gpu-patch-jetson.test.ts index e091c45a137..fc6c769e70b 100644 --- a/src/lib/onboard/docker-gpu-patch-jetson.test.ts +++ b/src/lib/onboard/docker-gpu-patch-jetson.test.ts @@ -59,7 +59,7 @@ describe("Jetson device-node group propagation (#4231, #7610)", () => { ); recreateOpenShellDockerSandboxWithGpu( - { sandboxName: "alpha", timeoutSecs: 1, backend: "jetson" }, + { sandboxName: "alpha", timeoutSecs: 1, backend: "jetson", waitForSupervisor: false }, { dockerCapture: dockerCaptureFixture(), dockerRun: vi.fn(() => ({ status: 0, stdout: "probe-id\n" })), @@ -90,7 +90,7 @@ describe("Jetson device-node group propagation (#4231, #7610)", () => { const detectTegraDeviceGroupGidsStub = vi.fn(() => ["44"]); recreateOpenShellDockerSandboxWithGpu( - { sandboxName: "alpha", timeoutSecs: 1, backend: "generic" }, + { sandboxName: "alpha", timeoutSecs: 1, backend: "generic", waitForSupervisor: false }, { dockerCapture: dockerCaptureFixture(), dockerRun: vi.fn(() => ({ status: 0, stdout: "probe-id\n" })), diff --git a/src/lib/onboard/docker-gpu-patch-mode-selection.test.ts b/src/lib/onboard/docker-gpu-patch-mode-selection.test.ts index d52d78316b4..eaaeee7454d 100644 --- a/src/lib/onboard/docker-gpu-patch-mode-selection.test.ts +++ b/src/lib/onboard/docker-gpu-patch-mode-selection.test.ts @@ -448,7 +448,7 @@ describe("docker-gpu-patch CDI-first mode selection (#4948)", () => { const detectSandboxFallbackDns = vi.fn(() => null); const result = recreateOpenShellDockerSandboxWithGpu( - { sandboxName: "alpha", timeoutSecs: 1 }, + { sandboxName: "alpha", timeoutSecs: 1, waitForSupervisor: false }, { dockerCapture, readDir: host.readDir, diff --git a/src/lib/onboard/docker-gpu-patch-recreate-dns.test.ts b/src/lib/onboard/docker-gpu-patch-recreate-dns.test.ts index 42f33fb00b5..55be092092c 100644 --- a/src/lib/onboard/docker-gpu-patch-recreate-dns.test.ts +++ b/src/lib/onboard/docker-gpu-patch-recreate-dns.test.ts @@ -92,7 +92,10 @@ describe("Docker GPU recreate DNS fallback (#3579)", () => { it("plumbs the discovered upstream through recreate into clone args", () => { const deps = recreateDeps("9.9.9.9"); - recreateOpenShellDockerSandboxWithGpu({ sandboxName: "alpha", timeoutSecs: 1 }, deps); + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1, waitForSupervisor: false }, + deps, + ); expect(deps.detectSandboxFallbackDns).toHaveBeenCalled(); expect(deps.probeContainerDns).toHaveBeenCalledWith({ dnsServer: "9.9.9.9" }); @@ -104,7 +107,10 @@ describe("Docker GPU recreate DNS fallback (#3579)", () => { it("does not add DNS through recreate when no upstream is discovered", () => { const deps = recreateDeps(null); - recreateOpenShellDockerSandboxWithGpu({ sandboxName: "alpha", timeoutSecs: 1 }, deps); + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1, waitForSupervisor: false }, + deps, + ); expect(deps.dockerRunDetached).not.toHaveBeenCalledWith( expect.arrayContaining(["--dns"]), @@ -123,7 +129,10 @@ describe("Docker GPU recreate DNS fallback (#3579)", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { - recreateOpenShellDockerSandboxWithGpu({ sandboxName: "alpha", timeoutSecs: 1 }, deps); + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1, waitForSupervisor: false }, + deps, + ); expect(warn).toHaveBeenCalledWith( expect.stringContaining( @@ -152,7 +161,10 @@ describe("Docker GPU recreate DNS fallback (#3579)", () => { }; const deps = recreateDeps("9.9.9.9", inspect); - recreateOpenShellDockerSandboxWithGpu({ sandboxName: "alpha", timeoutSecs: 1 }, deps); + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1, waitForSupervisor: false }, + deps, + ); expect(deps.probeContainerDns).not.toHaveBeenCalled(); expect(deps.dockerRunDetached).not.toHaveBeenCalledWith( @@ -170,7 +182,10 @@ describe("Docker GPU recreate DNS fallback (#3579)", () => { }); expect(() => - recreateOpenShellDockerSandboxWithGpu({ sandboxName: "alpha", timeoutSecs: 1 }, deps), + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1, waitForSupervisor: false }, + deps, + ), ).toThrow(/using --dns 9\.9\.9\.9.*servers_unreachable.*before container recreation/s); expect(deps.dockerStop).not.toHaveBeenCalled(); }); diff --git a/src/lib/onboard/docker-gpu-patch-recreate.test.ts b/src/lib/onboard/docker-gpu-patch-recreate.test.ts index bd4f3889618..98867a8a3d4 100644 --- a/src/lib/onboard/docker-gpu-patch-recreate.test.ts +++ b/src/lib/onboard/docker-gpu-patch-recreate.test.ts @@ -3,11 +3,17 @@ import { describe, expect, it, vi } from "vitest"; import { createDockerGpuInspectFixture as inspectFixture } from "./__test-helpers__/docker-gpu-patch-fixtures"; -import { recreateOpenShellDockerSandboxWithGpu } from "./docker-gpu-patch"; +import { + getDockerGpuPatchFailureContext, + recreateOpenShellDockerSandboxWithGpu, +} from "./docker-gpu-patch"; + +const OLD_CONTAINER_ID = "a".repeat(64); +const NEW_CONTAINER_ID = "b".repeat(64); function dockerCaptureFixture() { const responses: Record = { - ps: "old-container-id\n", + ps: `${OLD_CONTAINER_ID}\n`, inspect: JSON.stringify([inspectFixture()]), info: "", }; @@ -17,12 +23,26 @@ function dockerCaptureFixture() { describe("Docker GPU recreate orchestration", () => { it("recreates the OpenShell-managed container and waits for supervisor exec", () => { const dockerCapture = dockerCaptureFixture(); - const dockerRun = vi.fn(() => ({ status: 0, stdout: "probe-id\n" })); - const dockerRunDetached = vi.fn(() => ({ status: 0, stdout: "new-container-id\n" })); + const dockerRunResults = { + ps: { status: 0, stdout: `${NEW_CONTAINER_ID}\n` }, + inspect: { status: 0, stdout: "true\n" }, + }; + const dockerRun = vi.fn( + (args: readonly string[]) => + dockerRunResults[String(args[0]) as keyof typeof dockerRunResults] ?? { + status: 0, + stdout: "probe-id\n", + }, + ); + const dockerRunDetached = vi.fn(() => ({ status: 0, stdout: `${NEW_CONTAINER_ID}\n` })); const dockerRename = vi.fn(() => ({ status: 0 })); const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn(() => ({ status: 0 })); - const runOpenshell = vi.fn(() => ({ status: 0 })); + const dockerStart = vi.fn(() => ({ status: 0 })); + const runOpenshell = vi.fn((args: readonly string[]) => + args[1] === "list" ? { status: 0, stdout: "No sandboxes found.\n" } : { status: 0 }, + ); + const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 10:00:00 Ready\n"); const result = recreateOpenShellDockerSandboxWithGpu( { sandboxName: "alpha", timeoutSecs: 1 }, @@ -33,6 +53,8 @@ describe("Docker GPU recreate orchestration", () => { dockerRename, dockerStop, dockerRm, + dockerStart, + runCaptureOpenshell, runOpenshell, sleep: vi.fn(), now: () => new Date("2026-05-12T00:00:00Z"), @@ -42,10 +64,11 @@ describe("Docker GPU recreate orchestration", () => { }, ); - expect(result.newContainerId).toBe("new-container-id"); + expect(result.newContainerId).toBe(NEW_CONTAINER_ID); + expect(result.backupRemoved).toBe(true); expect(result.mode.kind).toBe("gpus"); expect(dockerStop).toHaveBeenCalledWith( - "old-container-id", + OLD_CONTAINER_ID, expect.objectContaining({ timeout: 90_000 }), ); expect(dockerRunDetached).toHaveBeenCalledWith( @@ -74,13 +97,60 @@ describe("Docker GPU recreate orchestration", () => { expect.objectContaining({ ignoreError: true, suppressOutput: true }), ); const dockerRmCalls = dockerRm.mock.calls as unknown[][]; - const backupRmCall = dockerRmCalls.findIndex((call) => - String(call[0]).includes("nemoclaw-gpu-backup"), - ); + const backupRmCall = dockerRmCalls.findIndex((call) => call[0] === OLD_CONTAINER_ID); expect(backupRmCall).toBeGreaterThanOrEqual(0); expect(dockerRm.mock.invocationCallOrder[backupRmCall]).toBeGreaterThan( runOpenshell.mock.invocationCallOrder[0], ); + expect(dockerStart).toHaveBeenCalledWith( + NEW_CONTAINER_ID, + expect.objectContaining({ ignoreError: true }), + ); + expect(runCaptureOpenshell).toHaveBeenCalledWith( + ["sandbox", "list"], + expect.objectContaining({ ignoreError: true, suppressOutput: true }), + ); + }); + + it("does not report success when the final OpenShell phase is Deleting (#9531)", () => { + let failure: unknown; + try { + recreateOpenShellDockerSandboxWithGpu( + { sandboxName: "alpha", timeoutSecs: 1 }, + { + dockerCapture: dockerCaptureFixture(), + dockerRun: vi.fn(() => ({ status: 0, stdout: `${NEW_CONTAINER_ID}\n` })), + dockerRunDetached: vi.fn(() => ({ status: 0, stdout: `${NEW_CONTAINER_ID}\n` })), + dockerRename: vi.fn(() => ({ status: 0 })), + dockerStop: vi.fn(() => ({ status: 0 })), + dockerRm: vi.fn(() => ({ status: 0 })), + dockerStart: vi.fn(() => ({ status: 0 })), + runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:00 Deleting\n"), + runOpenshell: vi.fn((args: readonly string[]) => + args[1] === "list" ? { status: 0, stdout: "No sandboxes found.\n" } : { status: 0 }, + ), + sleep: vi.fn(), + now: () => new Date("2026-05-12T00:00:00Z"), + detectSandboxFallbackDns: vi.fn(() => null), + readDir: vi.fn(() => null), + readFile: vi.fn(() => null), + }, + ); + } catch (error) { + failure = error; + } + + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("final replacement handoff"); + expect((failure as Error).message).toContain("automatic rollback is unavailable"); + expect((failure as Error).message).toContain("Rebuild the sandbox before retrying"); + expect(getDockerGpuPatchFailureContext(failure)).toMatchObject({ + backupRemoved: true, + oldContainerId: OLD_CONTAINER_ID, + newContainerId: NEW_CONTAINER_ID, + lastSandboxPhase: "Deleting", + rolledBack: false, + }); }); it("can recreate during sandbox create before supervisor exec is allowed", () => { diff --git a/src/lib/onboard/docker-gpu-patch-recreate.ts b/src/lib/onboard/docker-gpu-patch-recreate.ts index 4eb1c0ad8d4..7d2310ff366 100644 --- a/src/lib/onboard/docker-gpu-patch-recreate.ts +++ b/src/lib/onboard/docker-gpu-patch-recreate.ts @@ -26,7 +26,7 @@ import { DOCKER_GPU_PATCH_STOP_TIMEOUT_MS, DOCKER_GPU_PATCH_TIMEOUT_MS, } from "./docker-gpu-patch-constants"; -import { reconcileSupervisorReconnect } from "./docker-gpu-patch-finalize"; +import { finalizeDockerGpuPatchBackup } from "./docker-gpu-patch-finalize"; import { selectDockerGpuPatchMode } from "./docker-gpu-patch-mode"; import { restoreDockerGpuPatchBackupAfterRecreateFailure } from "./docker-gpu-patch-rollback"; import type { @@ -393,19 +393,40 @@ export function recreateOpenShellDockerSandboxContainer( options.timeoutSecs ?? DOCKER_GPU_PATCH_WAIT_SECS, deps, ); - const reconcile = reconcileSupervisorReconnect( - execReady, - { newContainerId, backupContainerName, originalName }, - deps, - ); - if (!reconcile.execReady) { - context.rolledBack = reconcile.rolledBack; - context.replacementStopConfirmed = reconcile.replacementStopConfirmed; - context.replacementRemovalConfirmed = reconcile.replacementRemovalConfirmed; - context.replacementPresence = reconcile.replacementPresence; - throw reconcile.error; + const patchResult = result(false); + const finalization = execReady + ? finalizeDockerGpuPatchBackup( + { + result: patchResult, + supervisorReady: true, + sandboxName: options.sandboxName, + finalHandoffTimeoutSecs: options.timeoutSecs ?? DOCKER_GPU_PATCH_WAIT_SECS, + }, + deps, + ) + : finalizeDockerGpuPatchBackup({ result: patchResult, supervisorReady: false }, deps); + context.rolledBack = finalization.rolledBack; + context.backupRemoved = finalization.backupRemoved; + context.replacementStopConfirmed = finalization.replacementStopConfirmed; + context.replacementRemovalConfirmed = finalization.replacementRemovalConfirmed; + context.replacementPresence = finalization.replacementPresence; + context.lastSandboxPhase = finalization.lastSandboxPhase; + if (!execReady) { + throw new Error( + finalization.rolledBack + ? "OpenShell supervisor did not reconnect to the GPU-enabled container; pre-patch sandbox restored." + : "OpenShell supervisor did not reconnect to the GPU-enabled container and rollback failed; pre-patch sandbox was NOT restored.", + ); } - return result(reconcile.backupRemoved); + if (finalization.finalHandoffAcknowledged) return result(true); + const rebuildRequired = finalization.backupRemoved + ? " The previous container was removed at the final handoff commit point; automatic rollback is unavailable. Rebuild the sandbox before retrying." + : ""; + throw new Error( + finalization.lastSandboxPhase + ? `OpenShell did not acknowledge the final replacement handoff; last sandbox phase was ${finalization.lastSandboxPhase}.${rebuildRequired}` + : `OpenShell did not acknowledge the final replacement handoff.${rebuildRequired}`, + ); } catch (error) { throw decoratePatchError(error instanceof Error ? error : new Error(String(error)), context); } diff --git a/src/lib/onboard/docker-gpu-patch-rollback.test.ts b/src/lib/onboard/docker-gpu-patch-rollback.test.ts index 094e4ae8bf1..6c6af7c26ac 100644 --- a/src/lib/onboard/docker-gpu-patch-rollback.test.ts +++ b/src/lib/onboard/docker-gpu-patch-rollback.test.ts @@ -177,8 +177,9 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { const runByCommand: Record { status: number; stdout: string }> = { ps: () => ({ status: 0, - stdout: replacementPresent ? `${replacementId}\n` : "", + stdout: `${alphaContainerIds().join("\n")}\n`, }), + inspect: () => ({ status: 0, stdout: "true\n" }), }; const dockerRun = vi.fn( (args: readonly string[]) => @@ -227,6 +228,7 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { return successfulRemoval(); }; removalHandlers.set(restoredName, removeRestored); + removalHandlers.set(restoredId, removeRestored); const dockerRm = vi.fn((target: string) => { removeTargets.push(target); return removalHandlers.get(target)?.() ?? successfulRemoval(); @@ -271,8 +273,10 @@ describe("recreateOpenShellDockerSandboxWithGpu rollback path", () => { dockerRename, dockerStart, dockerLogs: vi.fn(() => ""), - runOpenshell: vi.fn(() => ({ status: 0 })), - runCaptureOpenshell: vi.fn(() => "alpha Ready\n"), + runOpenshell: vi.fn((args: readonly string[]) => + args[1] === "list" ? { status: 0, stdout: "No sandboxes found.\n" } : { status: 0 }, + ), + runCaptureOpenshell: vi.fn(() => "alpha 2026-08-23 10:00:00 Ready\n"), sleep: vi.fn(), homedir: () => tmpDir, now: () => new Date("2026-07-03T00:00:00Z"), diff --git a/src/lib/onboard/docker-gpu-patch-types.ts b/src/lib/onboard/docker-gpu-patch-types.ts index 02be3c624c7..972cd858f54 100644 --- a/src/lib/onboard/docker-gpu-patch-types.ts +++ b/src/lib/onboard/docker-gpu-patch-types.ts @@ -79,12 +79,14 @@ export type DockerGpuPatchFailureContext = { oldContainerId?: string | null; newContainerId?: string | null; backupContainerName?: string | null; + backupRemoved?: boolean; selectedMode?: DockerGpuPatchMode | null; modeAttempts?: DockerGpuPatchModeAttempt[]; rolledBack?: boolean; replacementStopConfirmed?: boolean; replacementRemovalConfirmed?: boolean; replacementPresence?: "absent" | "present" | "unknown"; + lastSandboxPhase?: string | null; }; export type DockerGpuPatchResult = { @@ -94,11 +96,11 @@ export type DockerGpuPatchResult = { originalName: string; backupContainerName: string; mode: DockerGpuPatchMode; - // True when the patch path also confirmed supervisor reconnect AND removed - // the backup container. False when the caller deferred the reconnect wait - // (via `waitForSupervisor: false`); the backup is still in place and the - // caller is responsible for calling `finalizeDockerGpuPatchBackup` after - // its own supervisor wait completes. + // True when the patch path confirmed the initial supervisor reconnect, + // removed the exact backup, restarted the exact replacement, and received + // the final OpenShell handoff acknowledgement. False means the caller used + // `waitForSupervisor: false`; the backup remains until the caller invokes + // `finalizeDockerGpuPatchBackup` after its own initial readiness check. backupRemoved: boolean; }; diff --git a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts index 36bc94980ca..fde42865d83 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create-lifecycle.test.ts @@ -50,8 +50,9 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { const finalizeBackup = vi.fn(() => ({ backupRemoved: true, rolledBack: false, - lifecycleReleaseObserved: true, replacementRestarted: true, + finalHandoffAcknowledged: true, + lastSandboxPhase: "Ready", })); const capturePreRollbackDiagnostics = vi.fn(() => null); const onPatchFailureExit = vi.fn(); @@ -97,11 +98,11 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { result, supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 900, + finalHandoffTimeoutSecs: 900, }, deps, ); - expect(waitForSupervisor).toHaveBeenCalledTimes(2); + expect(waitForSupervisor).toHaveBeenCalledOnce(); expect(capturePreRollbackDiagnostics).not.toHaveBeenCalled(); expect(onPatchFailureExit).not.toHaveBeenCalled(); }); @@ -138,7 +139,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { result, supervisorReady: true, sandboxName: "alpha", - lifecycleReleaseTimeoutSecs: 900, + finalHandoffTimeoutSecs: 900, }, deps, ); @@ -170,11 +171,14 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { patch.maybeApplyDuringCreate(); patch.waitForSupervisorReconnectIfNeeded(); - await expect(patch.commitAfterReady()).rejects.toThrow("final runtime handoff"); + await expect(patch.commitAfterReady()).rejects.toThrow("automatic rollback is unavailable"); expect(onPatchFailureExit).toHaveBeenCalledOnce(); + expect(onPatchFailureExit.mock.calls[0]?.[2]?.context).toMatchObject({ + backupRemoved: true, + }); }); - it("rejects final handoff when OpenShell never releases the deleting lifecycle record (#9531)", async () => { + it("rejects final handoff when OpenShell reports Deleting after restart (#9531)", async () => { const deps = makeDeps(); const result = deferredCreateResult(); const waitForSupervisor = vi.fn(() => true); @@ -191,8 +195,9 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { finalizeBackup: vi.fn(() => ({ backupRemoved: true, rolledBack: false, - lifecycleReleaseObserved: false, replacementRestarted: true, + finalHandoffAcknowledged: false, + lastSandboxPhase: "Deleting", })), onPatchFailureExit, }, @@ -200,7 +205,7 @@ describe("createDockerGpuSandboxCreatePatch composed flow", () => { patch.maybeApplyDuringCreate(); patch.waitForSupervisorReconnectIfNeeded(); - await expect(patch.commitAfterReady()).rejects.toThrow("final runtime handoff"); + await expect(patch.commitAfterReady()).rejects.toThrow("automatic rollback is unavailable"); expect(waitForSupervisor).toHaveBeenCalledOnce(); expect(onPatchFailureExit).toHaveBeenCalledOnce(); diff --git a/src/lib/onboard/docker-gpu-sandbox-create.ts b/src/lib/onboard/docker-gpu-sandbox-create.ts index 9e2eacdd07c..e4ed566917b 100644 --- a/src/lib/onboard/docker-gpu-sandbox-create.ts +++ b/src/lib/onboard/docker-gpu-sandbox-create.ts @@ -493,14 +493,13 @@ export function createDockerGpuSandboxCreatePatch( const supervisorReconnectTimeoutSecs = getDockerGpuSupervisorReconnectTimeoutSecs( options.timeoutSecs, ); - const finalHandoffDeadlineMs = Date.now() + supervisorReconnectTimeoutSecs * 1000; const finalizeOutcome = result ? finalizeBackup( { result, supervisorReady: true, sandboxName: options.sandboxName, - lifecycleReleaseTimeoutSecs: supervisorReconnectTimeoutSecs, + finalHandoffTimeoutSecs: supervisorReconnectTimeoutSecs, }, options.deps, ) @@ -513,35 +512,31 @@ export function createDockerGpuSandboxCreatePatch( if ( finalizeOutcome.backupRemoved && finalizeOutcome.replacementRestarted && - finalizeOutcome.lifecycleReleaseObserved === true + finalizeOutcome.finalHandoffAcknowledged === true ) { - const remainingReconnectTimeoutSecs = Math.max( - 0, - Math.ceil((finalHandoffDeadlineMs - Date.now()) / 1000), - ); - console.log( - ` Waiting for OpenShell supervisor to confirm the final container handoff (up to ${remainingReconnectTimeoutSecs}s)...`, - ); - if ( - remainingReconnectTimeoutSecs > 0 && - waitForSupervisor(options.sandboxName, remainingReconnectTimeoutSecs, { - runOpenshell: options.deps.runOpenshell, - runCaptureOpenshell: options.deps.runCaptureOpenshell, - sleep: options.deps.sleep, - }) - ) { - return; - } + return; } const failure = new Error( - "Managed startup passed Ready, but its final runtime handoff did not converge.", + `Managed startup passed Ready, but its final runtime handoff did not converge.${ + finalizeOutcome.lastSandboxPhase + ? ` Last OpenShell phase: ${finalizeOutcome.lastSandboxPhase}.` + : "" + }${ + finalizeOutcome.backupRemoved + ? " The previous container was removed at the final handoff commit point; automatic rollback is unavailable. Rebuild the sandbox before retrying." + : "" + }`, ); cutoverFinalizationFailure = failure; onPatchFailureExit(options.sandboxName, failure, { runCaptureOpenshell: options.deps.runCaptureOpenshell, dockerCapture: options.deps.dockerCapture, additionalSummaryLines: routeAdapter.additionalSummaryLines, - context: failureContext(), + context: { + ...failureContext(), + backupRemoved: finalizeOutcome.backupRemoved, + lastSandboxPhase: finalizeOutcome.lastSandboxPhase, + }, }); throw failure; })(); diff --git a/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts b/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts index 1c5a8adbefc..86a84d9cee2 100644 --- a/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts +++ b/src/lib/onboard/docker-gpu-supervisor-reconnect.test.ts @@ -6,37 +6,42 @@ import { describe, expect, it, vi } from "vitest"; import { getDockerGpuSupervisorReconnectErrorDebouncePolls, getDockerGpuSupervisorReconnectTimeoutSecs, + waitForOpenShellFinalHandoff, waitForOpenShellSandboxLifecycleRelease, waitForOpenShellSupervisorReconnect, } from "./docker-gpu-supervisor-reconnect"; describe("Docker GPU final lifecycle release", () => { - it.each([ - ["an explicit empty list", "No sandboxes found.\n"], - ["another phase-bearing sandbox", "beta 2026-08-21 05:53:18 Ready\n"], - ])("accepts %s as a release receipt (#9531)", (_receipt, stdout) => { - const runOpenshell = vi.fn(() => ({ status: 0, stdout })); + it("requires corroboration for a retiring lifecycle row (#9962)", () => { + const corroborate = vi.fn(() => true); + const runOpenshell = vi.fn(() => ({ + status: 0, + stdout: "alpha 2026-08-23 01:40:35 Deleting\n", + })); expect( waitForOpenShellSandboxLifecycleRelease("alpha", 1, { runOpenshell, sleep: vi.fn(), + soleLabeledReplacementCorroboratesRetiringPhase: corroborate, }), ).toBe(true); - expect(runOpenshell).toHaveBeenCalledOnce(); + expect(corroborate).toHaveBeenCalledOnce(); + expect(runOpenshell).toHaveBeenCalledWith( + ["sandbox", "list"], + expect.objectContaining({ + killProcessTreeOnTimeout: true, + killSignal: "SIGKILL", + timeout: expect.any(Number), + }), + ); }); - it.each([ - ["a header", "NAME CREATED PHASE\n"], - ["a gateway error", "Error: gateway unavailable\n"], - ["a phase-free row", "beta 2026-08-21 05:53:18\n"], - ["an unrecognized phase", "beta 2026-08-21 05:53:18 Retiring\n"], - ["the selected sandbox in Ready", "alpha 2026-08-21 05:53:18 Ready\n"], - ["the selected sandbox in Provisioning", "alpha 2026-08-21 05:53:18 Provisioning\n"], - ["the selected sandbox in Error", "alpha 2026-08-21 05:53:18 Error\n"], - ["the selected sandbox in Failed", "alpha 2026-08-21 05:53:18 Failed\n"], - ])("rejects %s as a release receipt (#9531)", (_case, stdout) => { - const runOpenshell = vi.fn(() => ({ status: 0, stdout })); + it("does not accept an uncorroborated retiring lifecycle row (#9962)", () => { + const runOpenshell = vi.fn(() => ({ + status: 0, + stdout: "alpha 2026-08-23 01:40:35 Error\n", + })); expect( waitForOpenShellSandboxLifecycleRelease("alpha", 1, { @@ -44,69 +49,140 @@ describe("Docker GPU final lifecycle release", () => { sleep: vi.fn(), }), ).toBe(false); - expect(runOpenshell).toHaveBeenCalledTimes(2); }); - it.each(["Error", "Deleting"])( - "accepts a corroborated stopped replacement in %s", - (phase) => { - const corroborate = vi.fn(() => true); - const runOpenshell = vi.fn(() => ({ - status: 0, - stdout: `alpha 2026-08-23 01:40:35 ${phase}\n`, - })); - - expect( - waitForOpenShellSandboxLifecycleRelease("alpha", 1, { - runOpenshell, - sleep: vi.fn(), - soleLabeledReplacementCorroboratesRetiringPhase: corroborate, - }), - ).toBe(true); - expect(corroborate).toHaveBeenCalledOnce(); - }, - ); + it("does not report reconnect without an OpenShell execution boundary (#9531)", () => { + expect(waitForOpenShellSupervisorReconnect("alpha", 1, { sleep: vi.fn() })).toBe(false); + }); +}); + +describe("Docker GPU final handoff acknowledgement", () => { + it("accepts the exact running replacement only after OpenShell reports Ready (#9531)", () => { + const events: string[] = []; + const runCaptureOpenshell = vi + .fn() + .mockImplementationOnce(() => { + events.push("observe provisioning"); + return "alpha 2026-08-23 10:00:00 Provisioning\n"; + }) + .mockImplementationOnce(() => { + events.push("observe ready"); + return "alpha 2026-08-23 10:00:02 Ready\n"; + }); + const runOpenshell = vi.fn(() => { + events.push("exec ready"); + return { status: 0 }; + }); + const replacementIsExactAndRunning = vi.fn(() => { + events.push("confirm exact replacement"); + return true; + }); - it.each([ - ["a failed probe", { status: 1, stderr: "gateway unavailable" }], - ["a probe without an exit status", { status: null, stderr: "timed out" }], - ])("rejects %s as a release receipt (#9531)", (_case, result) => { - const runOpenshell = vi.fn(() => result); + const acknowledgement = waitForOpenShellFinalHandoff("alpha", 60, { + runCaptureOpenshell, + runOpenshell, + replacementIsExactAndRunning, + sleep: vi.fn(), + }); + + expect(acknowledgement).toEqual({ acknowledged: true, lastSandboxPhase: "Ready" }); + expect(events).toEqual([ + "observe provisioning", + "confirm exact replacement", + "observe ready", + "exec ready", + "confirm exact replacement", + ]); + expect(runCaptureOpenshell).toHaveBeenCalledWith( + ["sandbox", "list"], + expect.objectContaining({ + killProcessTreeOnTimeout: true, + killSignal: "SIGKILL", + timeout: expect.any(Number), + }), + ); + expect(runOpenshell).toHaveBeenCalledWith( + ["sandbox", "exec", "-n", "alpha", "--", "true"], + expect.objectContaining({ + killProcessTreeOnTimeout: true, + killSignal: "SIGKILL", + timeout: expect.any(Number), + }), + ); + }); + + it("treats Deleting after the replacement start as terminal (#9531)", () => { + const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 10:00:00 Deleting\n"); + const runOpenshell = vi.fn(() => ({ status: 1 })); + const replacementIsExactAndRunning = vi.fn(() => true); + const sleep = vi.fn(); expect( - waitForOpenShellSandboxLifecycleRelease("alpha", 1, { + waitForOpenShellFinalHandoff("alpha", 60, { + runCaptureOpenshell, runOpenshell, + replacementIsExactAndRunning, + sleep, + }), + ).toEqual({ acknowledged: false, lastSandboxPhase: "Deleting" }); + expect(runCaptureOpenshell).toHaveBeenCalledOnce(); + expect(runOpenshell).not.toHaveBeenCalled(); + expect(replacementIsExactAndRunning).not.toHaveBeenCalled(); + expect(sleep).not.toHaveBeenCalled(); + }); + + it("continues through Error only while the exact replacement is running (#9531)", () => { + const runCaptureOpenshell = vi.fn(() => "alpha 2026-08-23 10:00:00 Error\n"); + const replacementIsExactAndRunning = vi.fn(() => false); + + expect( + waitForOpenShellFinalHandoff("alpha", 60, { + runCaptureOpenshell, + runOpenshell: vi.fn(() => ({ status: 1 })), + replacementIsExactAndRunning, sleep: vi.fn(), }), - ).toBe(false); - expect(runOpenshell).toHaveBeenCalledTimes(2); + ).toEqual({ acknowledged: false, lastSandboxPhase: "Error" }); + expect(replacementIsExactAndRunning).toHaveBeenCalledOnce(); }); - it("does not start Error corroboration after the lifecycle-release deadline (#9962)", () => { - vi.useFakeTimers(); - vi.setSystemTime(0); - const corroborate = vi.fn(() => true); - const runOpenshell = vi.fn(() => { - vi.setSystemTime(1000); - return { - status: 0, - stdout: "alpha 2026-08-23 01:40:35 Error\n", - }; - }); + it("allows a running replacement to progress from Error to Ready (#9531)", () => { + const runCaptureOpenshell = vi + .fn() + .mockReturnValueOnce("alpha 2026-08-23 10:00:00 Error\n") + .mockReturnValueOnce("alpha 2026-08-23 10:00:02 Ready\n"); + const runOpenshell = vi.fn(() => ({ status: 0 })); + const replacementIsExactAndRunning = vi.fn(() => true); - try { - expect( - waitForOpenShellSandboxLifecycleRelease("alpha", 1, { - runOpenshell, - sleep: vi.fn(), - soleLabeledReplacementCorroboratesRetiringPhase: corroborate, - }), - ).toBe(false); - } finally { - vi.useRealTimers(); - } + expect( + waitForOpenShellFinalHandoff("alpha", 60, { + runCaptureOpenshell, + runOpenshell, + replacementIsExactAndRunning, + sleep: vi.fn(), + }), + ).toEqual({ acknowledged: true, lastSandboxPhase: "Ready" }); + expect(replacementIsExactAndRunning).toHaveBeenCalledTimes(2); + expect(runOpenshell).toHaveBeenCalledOnce(); + }); + + it("does not reuse a stale Ready phase after the sandbox row disappears (#9531)", () => { + const runCaptureOpenshell = vi + .fn() + .mockReturnValueOnce("alpha 2026-08-23 10:00:00 Ready\n") + .mockReturnValue(""); + const runOpenshell = vi.fn(() => ({ status: 1 })); + const replacementIsExactAndRunning = vi.fn().mockReturnValueOnce(true).mockReturnValue(false); + + expect( + waitForOpenShellFinalHandoff("alpha", 60, { + runCaptureOpenshell, + runOpenshell, + replacementIsExactAndRunning, + sleep: vi.fn(), + }), + ).toEqual({ acknowledged: false, lastSandboxPhase: "Ready" }); expect(runOpenshell).toHaveBeenCalledOnce(); - expect(corroborate).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/docker-gpu-supervisor-reconnect.ts b/src/lib/onboard/docker-gpu-supervisor-reconnect.ts index aaf035d0d06..9f41580f7ee 100644 --- a/src/lib/onboard/docker-gpu-supervisor-reconnect.ts +++ b/src/lib/onboard/docker-gpu-supervisor-reconnect.ts @@ -77,41 +77,37 @@ type DockerLifecycleReleaseDeps = Pick< DockerGpuSupervisorReconnectDeps, "runOpenshell" | "sleep" > & { - /** - * Corroborating evidence for an Error or Deleting row from a Docker query - * that confirms the transaction-owned replacement is the sole labeled - * sandbox container. - * The callback must fail closed and keep its child within the supplied - * remaining lifecycle-release budget. - */ + /** Corroborates a retiring lifecycle row with the stopped exact replacement. */ soleLabeledReplacementCorroboratesRetiringPhase?: (remainingMs: number) => boolean; }; +type DockerFinalHandoffDeps = Required< + Pick +> & + Pick & { + /** + * Prove that the transaction-owned replacement is the sole labeled + * container and is still running. The callback must fail closed and keep + * its Docker queries within the supplied remaining handoff budget. + */ + replacementIsExactAndRunning: (remainingMs: number) => boolean; + }; + +export type DockerFinalHandoffAcknowledgement = { + acknowledged: boolean; + lastSandboxPhase: string | null; +}; + +const FINAL_HANDOFF_TERMINAL_PHASES = new Set(["Deleting", "Failed", "CrashLoopBackOff"]); +const PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS = { + killProcessTreeOnTimeout: true, + killSignal: "SIGKILL", +} as const; + /** - * Workaround contract for the OpenShell lifecycle race in #9531: - * - * - Removing the rollback backup can strand the exact sandbox in `Deleting` - * while its replacement container is healthy. - * - `openshell sandbox list` owns lifecycle authority. Docker health cannot - * prove that OpenShell retired the previous record. - * - This layer waits after backup removal and before replacement restart so - * OpenShell processes the stale deletion before the new registration. - * - The caller enters this wait only after the replacement reached Ready and - * was deliberately stopped. A successful list normally omits the sandbox - * name. An Error or Deleting row is also sufficient only when a separate - * bounded Docker query confirms that the transaction-owned full replacement - * ID still identifies exactly one OpenShell-managed container. This - * corroborates the release condition; the OpenShell row alone is not an - * identity-bound ownership receipt. The Deleting case breaks the otherwise - * circular wait where OpenShell retains the row until that exact replacement - * emits its restart event. - * - `waits for the sandbox name to disappear before restarting the - * replacement (#9531)` protects the event order. `rejects final handoff when - * OpenShell never releases the deleting lifecycle record (#9531)` protects - * the composed failure path. - * - * Remove this wait only when OpenShell binds deletion to the removed container - * identity or provides an identity-bound lifecycle-release receipt. + * Wait for OpenShell to retire the pre-replacement lifecycle record before + * restarting the replacement. A retiring Error or Deleting row is accepted + * only with an identity-bound Docker corroboration. */ export function waitForOpenShellSandboxLifecycleRelease( sandboxName: string, @@ -120,39 +116,35 @@ export function waitForOpenShellSandboxLifecycleRelease( ): boolean { if (!deps.runOpenshell) return false; const sleep = deps.sleep ?? defaultSleep; - const boundedTimeoutSecs = Math.max(1, Math.round(timeoutSecs)); - const deadline = Date.now() + boundedTimeoutSecs * 1000; - const maxAttempts = Math.max(1, Math.ceil(boundedTimeoutSecs / 2) + 1); + const deadline = Date.now() + Math.max(1, Math.round(timeoutSecs)) * 1000; + const maxAttempts = Math.max(1, Math.ceil(Math.max(1, Math.round(timeoutSecs)) / 2) + 1); for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { - const remainingBeforeProbeMs = deadline - Date.now(); - if (remainingBeforeProbeMs <= 0) break; + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) break; const result = deps.runOpenshell(["sandbox", "list"], { ignoreError: true, + ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, suppressOutput: true, - timeout: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingBeforeProbeMs), + timeout: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingMs), }); if (hasZeroDockerExitStatus(result)) { const output = String(result.stdout ?? "").trim(); const entries = parseLiveSandboxEntries(output); const sandboxPresent = entries.some((entry) => entry.name === sandboxName); - const stoppedReplacementRetiring = entries.some( + const retiring = entries.some( (entry) => entry.name === sandboxName && (entry.phase === "Error" || entry.phase === "Deleting"), ); - const hasPhaseBearingEntry = entries.some((entry) => entry.phase !== null); + const corroborated = + retiring && + deadline - Date.now() > 0 && + deps.soleLabeledReplacementCorroboratesRetiringPhase?.(deadline - Date.now()) === true; const explicitEmptyList = output === "No sandboxes found" || output === "No sandboxes found."; - const remainingBeforeCorroborationMs = deadline - Date.now(); - const soleLabeledReplacementCorroboratesRetiringPhase = - stoppedReplacementRetiring && - remainingBeforeCorroborationMs > 0 && - deps.soleLabeledReplacementCorroboratesRetiringPhase?.( - remainingBeforeCorroborationMs, - ) === true; if ( explicitEmptyList || - soleLabeledReplacementCorroboratesRetiringPhase || - (hasPhaseBearingEntry && !sandboxPresent) + corroborated || + (entries.some((entry) => entry.phase !== null) && !sandboxPresent) ) { return true; } @@ -165,6 +157,100 @@ export function waitForOpenShellSandboxLifecycleRelease( return false; } +function exactReplacementIsRunning( + callback: DockerFinalHandoffDeps["replacementIsExactAndRunning"], + remainingMs: number, +): boolean { + if (remainingMs <= 0) return false; + try { + return callback(remainingMs); + } catch { + return false; + } +} + +/** + * Confirm the final Docker replacement handoff through OpenShell and Docker. + * + * The final replacement start is the authoritative lifecycle event. Success + * requires both an OpenShell Ready row with a working sandbox exec and a + * bounded Docker proof that the exact transaction-owned replacement is the + * sole running labeled container. Deleting is terminal after that start. + * Error remains transient only while the exact replacement stays running. + */ +export function waitForOpenShellFinalHandoff( + sandboxName: string, + timeoutSecs: number, + deps: DockerFinalHandoffDeps, +): DockerFinalHandoffAcknowledgement { + const sleep = deps.sleep ?? defaultSleep; + const boundedTimeoutSecs = Math.max(1, Math.round(timeoutSecs)); + const deadline = Date.now() + boundedTimeoutSecs * 1000; + const maxAttempts = Math.max(1, Math.ceil(boundedTimeoutSecs / 2) + 1); + let lastSandboxPhase: string | null = null; + + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + const remainingBeforeListMs = deadline - Date.now(); + if (remainingBeforeListMs <= 0) break; + let listOutput = ""; + try { + listOutput = deps.runCaptureOpenshell(["sandbox", "list"], { + ignoreError: true, + ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, + suppressOutput: true, + timeout: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingBeforeListMs), + }); + } catch { + listOutput = ""; + } + const entry = parseLiveSandboxEntries(listOutput).find((item) => item.name === sandboxName); + const currentPhase = entry?.phase ?? null; + if (currentPhase) lastSandboxPhase = currentPhase; + if (currentPhase && FINAL_HANDOFF_TERMINAL_PHASES.has(currentPhase)) { + return { acknowledged: false, lastSandboxPhase }; + } + + const remainingBeforeRuntimeProofMs = deadline - Date.now(); + if ( + currentPhase === "Error" && + !exactReplacementIsRunning(deps.replacementIsExactAndRunning, remainingBeforeRuntimeProofMs) + ) { + return { acknowledged: false, lastSandboxPhase }; + } + + if (currentPhase === "Ready") { + const remainingBeforeExecMs = deadline - Date.now(); + if (remainingBeforeExecMs <= 0) break; + const execResult = deps.runOpenshell(["sandbox", "exec", "-n", sandboxName, "--", "true"], { + ignoreError: true, + ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, + suppressOutput: true, + timeout: Math.min(DOCKER_GPU_PATCH_TIMEOUT_MS, remainingBeforeExecMs), + }); + const remainingAfterExecMs = deadline - Date.now(); + const replacementIsRunning = exactReplacementIsRunning( + deps.replacementIsExactAndRunning, + remainingAfterExecMs, + ); + if (hasZeroDockerExitStatus(execResult) && replacementIsRunning) { + return { acknowledged: true, lastSandboxPhase }; + } + if (!replacementIsRunning) return { acknowledged: false, lastSandboxPhase }; + } else if ( + currentPhase !== "Error" && + !exactReplacementIsRunning(deps.replacementIsExactAndRunning, deadline - Date.now()) + ) { + return { acknowledged: false, lastSandboxPhase }; + } + + const remainingBeforeSleepMs = deadline - Date.now(); + if (attempt < maxAttempts && remainingBeforeSleepMs > 0) { + sleep(Math.min(2, remainingBeforeSleepMs / 1000)); + } + } + return { acknowledged: false, lastSandboxPhase }; +} + function defaultSleep(seconds: number): void { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.max(0, seconds) * 1000); } @@ -189,6 +275,7 @@ function sandboxListShowsErrorPhase( try { const list = runCaptureOpenshell(["sandbox", "list"], { ignoreError: true, + ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, suppressOutput: true, timeout: DOCKER_GPU_PATCH_TIMEOUT_MS, }); @@ -203,7 +290,7 @@ export function waitForOpenShellSupervisorReconnect( timeoutSecs: number, deps: DockerGpuSupervisorReconnectDeps, ): boolean { - if (!deps.runOpenshell) return true; + if (!deps.runOpenshell) return false; const sleep = deps.sleep ?? defaultSleep; const deadline = Date.now() + Math.max(1, timeoutSecs) * 1000; const errorPhaseDebouncePolls = @@ -216,6 +303,7 @@ export function waitForOpenShellSupervisorReconnect( while (Date.now() <= deadline) { const result = deps.runOpenshell(["sandbox", "exec", "-n", sandboxName, "--", "true"], { ignoreError: true, + ...PROCESS_TREE_BOUNDED_OPENSHELL_OPTIONS, suppressOutput: true, timeout: DOCKER_GPU_PATCH_TIMEOUT_MS, }); diff --git a/src/lib/onboard/openshell-cli.ts b/src/lib/onboard/openshell-cli.ts index 69bf9ef0fca..9abf61ae6e4 100644 --- a/src/lib/onboard/openshell-cli.ts +++ b/src/lib/onboard/openshell-cli.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { processTreeBoundedOpenshellInvocation } from "../adapters/openshell/process-tree-timeout"; import { resolveOpenshell } from "../adapters/openshell/resolve"; import { ROOT, run, runCapture, shellQuote } from "../runner"; import { @@ -19,6 +20,8 @@ export interface OpenshellCliDeps { setCachedBinary(binary: string): void; getGatewayPort(): number; getDockerDriverGatewayEndpoint(): string; + runCommand?: typeof run; + runCaptureCommand?: typeof runCapture; } export interface OpenshellCliHelpers { @@ -34,6 +37,9 @@ export interface OpenshellCliHelpers { } export function createOpenshellCliHelpers(deps: OpenshellCliDeps): OpenshellCliHelpers { + const runCommand = deps.runCommand ?? run; + const runCaptureCommand = deps.runCaptureCommand ?? runCapture; + function getOpenshellBinary(): string { const cached = deps.getCachedBinary(); if (cached) return cached; @@ -60,12 +66,28 @@ export function createOpenshellCliHelpers(deps: OpenshellCliDeps): OpenshellCliH return [openshellBinary, ...args]; } + function processTreeBoundedInvocation(args: string[], opts: any) { + const [binary, ...commandArgs] = openshellArgv(args, opts); + const { killProcessTreeOnTimeout, ...runnerOptions } = opts; + const bounded = processTreeBoundedOpenshellInvocation(binary, commandArgs, { + killProcessTreeOnTimeout, + killSignal: runnerOptions.killSignal, + timeout: runnerOptions.timeout, + }); + return { + argv: [bounded.binary, ...bounded.args], + runnerOptions: { ...runnerOptions, killSignal: bounded.killSignal }, + }; + } + function runOpenshell(args: string[], opts: any = {}) { - return run(openshellArgv(args, opts), opts); + const invocation = processTreeBoundedInvocation(args, opts); + return runCommand(invocation.argv, invocation.runnerOptions); } function runCaptureOpenshell(args: string[], opts: any = {}) { - return runCapture(openshellArgv(args, opts), opts); + const invocation = processTreeBoundedInvocation(args, opts); + return runCaptureCommand(invocation.argv, invocation.runnerOptions); } function captureOpenshell(args: string[], opts: CaptureOpenshellOptions = {}) { diff --git a/src/lib/onboard/sandbox-create-launch.test.ts b/src/lib/onboard/sandbox-create-launch.test.ts index 7bddef4eee7..a873639748c 100644 --- a/src/lib/onboard/sandbox-create-launch.test.ts +++ b/src/lib/onboard/sandbox-create-launch.test.ts @@ -565,6 +565,39 @@ describe("prepareSandboxCreateLaunch", () => { } }); + it("routes bounded OpenShell probes through the process-tree timeout adapter (#10238)", () => { + const runCommand = vi.fn((_command: readonly string[], _options?: unknown) => { + return { status: 0 } as never; + }); + const helpers = createOpenshellCliHelpers({ + getCachedBinary: () => "/opt/openshell", + setCachedBinary: vi.fn(), + getGatewayPort: () => 31818, + getDockerDriverGatewayEndpoint: () => "http://127.0.0.1:31818", + runCommand, + }); + + helpers.runOpenshell(["sandbox", "list"], { + ignoreError: true, + killProcessTreeOnTimeout: true, + timeout: 1000, + }); + + const expectedArgv = + process.platform === "linux" && fs.existsSync("/usr/bin/timeout") + ? ["/usr/bin/timeout", "--signal=KILL", "0.75s", "/opt/openshell", "sandbox", "list"] + : ["/opt/openshell", "sandbox", "list"]; + expect(runCommand).toHaveBeenCalledWith( + expectedArgv, + expect.objectContaining({ + ignoreError: true, + killSignal: "SIGKILL", + timeout: 1000, + }), + ); + expect(runCommand.mock.calls[0]?.[1]).not.toHaveProperty("killProcessTreeOnTimeout"); + }); + it("forwards the validated sandbox name into the Deep Agents Code sandbox create env", () => { const result = prepareSandboxCreateLaunch({ agent: { name: "langchain-deepagents-code" } as any, diff --git a/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts b/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts index 6007aba571f..c96798c7eb4 100644 --- a/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts +++ b/test/e2e/live/gateway-guard-legacy-keepalive-fixture.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import * as dockerRunNamespace from "../../../src/lib/adapters/docker/run.ts"; +import * as openshellRuntimeNamespace from "../../../src/lib/adapters/openshell/runtime.ts"; import * as managedBootstrapAdapterNamespace from "../../../src/lib/onboard/managed-bootstrap/adapter.ts"; import * as dockerGpuPatchCloneNamespace from "../../../src/lib/onboard/docker-gpu-patch-clone.ts"; import type { @@ -53,6 +54,11 @@ const dockerRun = ( "default" in dockerRunNamespace ? dockerRunNamespace.default : dockerRunNamespace ) as typeof import("../../../src/lib/adapters/docker/run.ts"); const { dockerCapture: defaultDockerCapture } = dockerRun; +const openshellRuntime = ( + "default" in openshellRuntimeNamespace + ? openshellRuntimeNamespace.default + : openshellRuntimeNamespace +) as typeof import("../../../src/lib/adapters/openshell/runtime.ts"); type StartupCommandRecreate = typeof recreateOpenShellDockerSandboxWithStartupCommand; type DockerCapture = NonNullable; @@ -66,11 +72,20 @@ export type LegacyKeepaliveFixtureOptions = { export type LegacyKeepaliveFixtureDeps = { recreate: StartupCommandRecreate; dockerCapture: DockerCapture; + runOpenshell: NonNullable; + runCaptureOpenshell: NonNullable; }; const defaultDeps: LegacyKeepaliveFixtureDeps = { recreate: recreateOpenShellDockerSandboxWithStartupCommand, dockerCapture: defaultDockerCapture, + runOpenshell: openshellRuntime.runOpenshell, + runCaptureOpenshell: (args, options) => + openshellRuntime.captureOpenshell(args, { + ignoreError: true, + includeStderr: true, + timeout: typeof options?.timeout === "number" ? options.timeout : undefined, + }).output, }; function requireFixtureInput(condition: boolean, message: string): asserts condition { @@ -253,6 +268,8 @@ export function createLegacyKeepaliveFixture( const recreate = deps.recreate ?? defaultDeps.recreate; const dockerCapture = deps.dockerCapture ?? defaultDeps.dockerCapture; + const runOpenshell = deps.runOpenshell ?? defaultDeps.runOpenshell; + const runCaptureOpenshell = deps.runCaptureOpenshell ?? defaultDeps.runCaptureOpenshell; const result = recreate( { sandboxName: options.sandboxName, @@ -262,6 +279,8 @@ export function createLegacyKeepaliveFixture( }, { dockerCapture: legacyKeepaliveDockerCapture(options.expectedContainerId, dockerCapture), + runCaptureOpenshell, + runOpenshell, }, ); diff --git a/test/e2e/live/gateway-guard-recovery.test.ts b/test/e2e/live/gateway-guard-recovery.test.ts index 53101ee26c7..8df89fe17bb 100644 --- a/test/e2e/live/gateway-guard-recovery.test.ts +++ b/test/e2e/live/gateway-guard-recovery.test.ts @@ -574,6 +574,10 @@ test( }, ); expect(createLegacyKeepalive.exitCode, resultText(createLegacyKeepalive)).toBe(0); + const handoffReceipt = JSON.parse(createLegacyKeepalive.stdout) as { + newContainerId?: unknown; + }; + expect(handoffReceipt.newContainerId).toMatch(/^[0-9a-f]{64}$/iu); // Do not overlap the fixture's recreation with the restart below. The // fixture runs in its own process, so the host must observe the replacement // through OpenShell before starting the next container lifecycle transition. @@ -585,6 +589,7 @@ test( ); const legacyContainerId = await findSandboxContainer(host, "legacy-restart-container-before"); + expect(legacyContainerId).toBe(handoffReceipt.newContainerId); expect(legacyContainerId).not.toBe(recoveredContainerId); expect( await inspectStartupCommand(host, legacyContainerId, "legacy-restart-command-before"), diff --git a/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts b/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts index 98b7d89e692..b14ed1124b2 100644 --- a/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts +++ b/test/e2e/support/gateway-guard-legacy-keepalive-fixture.test.ts @@ -159,7 +159,11 @@ describe("gateway guard legacy keepalive fixture", () => { openshellSandboxCommand: ["sleep", "infinity"], timeoutSecs: 180, }, - { dockerCapture: expect.any(Function) }, + { + dockerCapture: expect.any(Function), + runCaptureOpenshell: expect.any(Function), + runOpenshell: expect.any(Function), + }, ); }); diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index 9873d4d7e68..a7978657307 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -308,6 +308,9 @@ function mockSandboxExecCurl(command, options = {}) { } function mockOnboardRunCapture(command, options = {}) { + // The companion runner seam models the exact post-commit Docker proof. Install + // it lazily after each scenario has replaced runner.run with its local recorder. + mockDockerSandboxLifecycleReleaseFromRunner(); const normalized = normalizeCommand(command); if ( normalized.startsWith("docker ps -a --no-trunc ") && @@ -388,11 +391,35 @@ function mockStandaloneGatewayTeardownAuthority() { function mockDockerSandboxLifecycleReleaseFromRunner() { const runner = require(path.resolve(__dirname, "../../src/lib/runner.ts")); + if (runner.run.__nemoclawDockerLifecycleFixture === true) return; const run = runner.run; + let finalCommitReleased = false; let lifecycleReleased = false; - runner.run = (command, options) => { + const wrappedRun = (command, options) => { const normalized = normalizeCommand(command); - if (normalized.startsWith("docker rm ")) lifecycleReleased = true; + if ( + finalCommitReleased && + normalized.startsWith("docker ps -a --no-trunc ") && + normalized.includes("label=openshell.ai/sandbox-name=my-assistant") && + normalized.endsWith("--format {{.ID}}") + ) { + return { + status: 0, + stdout: Buffer.from(`${ONBOARD_SANDBOX_NEW_CONTAINER_ID}\n`), + stderr: Buffer.alloc(0), + }; + } + if ( + finalCommitReleased && + normalized === + `docker inspect --type container --format {{json .State.Running}} ${ONBOARD_SANDBOX_NEW_CONTAINER_ID}` + ) { + return { + status: 0, + stdout: Buffer.from("true\n"), + stderr: Buffer.alloc(0), + }; + } if (lifecycleReleased && normalized.includes("sandbox list")) { return { status: 0, @@ -400,8 +427,17 @@ function mockDockerSandboxLifecycleReleaseFromRunner() { stderr: Buffer.alloc(0), }; } - return run(command, options); + const result = run(command, options); + if (normalized.startsWith("docker rm ") && result?.status === 0) { + lifecycleReleased = true; + if (normalized === `docker rm ${ONBOARD_SANDBOX_OLD_CONTAINER_ID}`) { + finalCommitReleased = true; + } + } + return result; }; + wrappedRun.__nemoclawDockerLifecycleFixture = true; + runner.run = wrappedRun; } function mockManagedImageFallback() { diff --git a/test/onboarding/onboard-sandbox-build.test.ts b/test/onboarding/onboard-sandbox-build.test.ts index 259ab7e9e3e..70c10f59311 100644 --- a/test/onboarding/onboard-sandbox-build.test.ts +++ b/test/onboarding/onboard-sandbox-build.test.ts @@ -450,6 +450,7 @@ platform.isWsl = () => false; const commands = []; const logs = []; const baseResolutionCalls = []; +let sandboxCreated = false; const originalLog = console.log; console.log = (...args) => { logs.push(args.join(" ")); @@ -506,7 +507,9 @@ runner.runFile = (file, args = [], opts = {}) => { return { status: 0 }; }; runner.runCapture = (command) => { - if (_n(command).includes("sandbox get") && _n(command).includes("my-assistant")) return ""; + if (_n(command).includes("sandbox get") && _n(command).includes("my-assistant")) { + return sandboxCreated ? "Name: my-assistant\\nPhase: Ready\\n" : ""; + } if (_n(command).includes("sandbox list")) return "my-assistant Ready"; { const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); @@ -524,6 +527,7 @@ preflight.checkPortAvailable = async () => ({ ok: true }); credentials.prompt = async () => ""; childProcess.spawn = (...args) => { + sandboxCreated = true; const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); diff --git a/test/process-recovery/process-recovery-supervisor-relaunch.test.ts b/test/process-recovery/process-recovery-supervisor-relaunch.test.ts index fec84eefa2f..e110f53b2a6 100644 --- a/test/process-recovery/process-recovery-supervisor-relaunch.test.ts +++ b/test/process-recovery/process-recovery-supervisor-relaunch.test.ts @@ -72,11 +72,15 @@ function composedRelaunchTransaction( : { backupRemoved: false, rolledBack: true }; }, ), + containerIds: { old: string; replacement: string } = { + old: "old-container-id", + replacement: "replacement-container-id", + }, ) { const resolveContainer = vi .fn() - .mockReturnValueOnce("old-container-id") - .mockReturnValue("replacement-container-id"); + .mockReturnValueOnce(containerIds.old) + .mockReturnValue(containerIds.replacement); const runOpenshell = vi.fn(() => ({ status: 0, stdout: "No sandboxes found.\n" })); const relaunchManagedSupervisorSessionImpl = vi.fn( (sandboxName: string, options: Parameters[1]) => @@ -113,8 +117,8 @@ function composedRelaunchTransaction( runOpenshell, recreate: vi.fn(() => ({ applied: true as const, - oldContainerId: "old-container-id", - newContainerId: "replacement-container-id", + oldContainerId: containerIds.old, + newContainerId: containerIds.replacement, originalName: "openshell-recovery-box", backupContainerName: "openshell-recovery-box-nemoclaw-backup", mode: { @@ -454,11 +458,14 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { expect(finalizeTransaction).toHaveBeenCalledOnce(); expect(finalizeTransaction).toHaveBeenCalledWith( expect.objectContaining({ - lifecycleReleaseTimeoutSecs: 900, + finalHandoffTimeoutSecs: 900, sandboxName: "recovered-box", supervisorReady: true, }), - { runOpenshell }, + { + runCaptureOpenshell: expect.any(Function), + runOpenshell, + }, ); }); @@ -470,15 +477,30 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { const dockerStop = vi.fn(() => ({ status: 0 })); const dockerRm = vi.fn(() => ({ status: 0 })); const dockerStart = vi.fn(() => ({ status: 0 })); + const oldContainerId = "a".repeat(64); + const replacementContainerId = "b".repeat(64); + const dockerRun = vi.fn((args: readonly string[]) => + args[0] === "ps" + ? { status: 0, stdout: `${replacementContainerId}\n` } + : { status: 0, stdout: "true\n" }, + ); const finalizeTransaction = vi.fn( ( options: Parameters[0], deps: Parameters[1], - ) => finalizeDockerGpuPatchBackup(options, { ...deps, dockerStop, dockerRm, dockerStart }), + ) => + finalizeDockerGpuPatchBackup(options, { + ...deps, + dockerRm, + dockerRun, + dockerStart, + dockerStop, + }), ); const { relaunchManagedSupervisorSessionImpl } = composedRelaunchTransaction( order, finalizeTransaction, + { old: oldContainerId, replacement: replacementContainerId }, ); const requestGatewaySupervisorAction = vi.fn((_name: string, action: string) => action === "recover" ? { status: 1, stdout: "", stderr: "SUPERVISOR_NOT_RUNNING" } : null, @@ -501,7 +523,8 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { options?.beforeProbe?.(1000) === true, ); vi.spyOn(forwardHealth, "isLocalForwardReachable").mockImplementation(() => forwardStarted); - vi.spyOn(openshellRuntime, "captureOpenshell").mockImplementation((args) => { + const captureOpenshell = vi.spyOn(openshellRuntime, "captureOpenshell"); + captureOpenshell.mockImplementation((args) => { const responses = { "forward list": () => ({ status: 0, @@ -509,6 +532,10 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ? "SANDBOX BIND PORT PID STATUS\nlegacy-handoff-box 127.0.0.1 18789 12345 running" : "SANDBOX BIND PORT PID STATUS", }), + "sandbox list": () => ({ + status: 0, + output: "legacy-handoff-box 2026-08-23 10:00:00 Ready\n", + }), }; return ( responses[args.join(" ") as keyof typeof responses]?.() ?? { @@ -540,15 +567,15 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { forwardRecovered: true, }); expect(dockerStop).toHaveBeenCalledWith( - "replacement-container-id", + replacementContainerId, expect.objectContaining({ ignoreError: true }), ); expect(dockerRm).toHaveBeenCalledWith( - "openshell-recovery-box-nemoclaw-backup", + oldContainerId, expect.objectContaining({ ignoreError: true }), ); expect(dockerStart).toHaveBeenCalledWith( - "replacement-container-id", + replacementContainerId, expect.objectContaining({ ignoreError: true }), ); expect(waitForRecreatedSandboxOpenShellReadyImpl).toHaveBeenCalledTimes(2); @@ -562,6 +589,13 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { ["forward", "start", "--background", "18789", "legacy-handoff-box"], expect.objectContaining({ ignoreError: true }), ); + expect(captureOpenshell).toHaveBeenCalledWith( + ["sandbox", "list"], + expect.objectContaining({ + killProcessTreeOnTimeout: true, + killSignal: "SIGKILL", + }), + ); }); it.each([ @@ -579,7 +613,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { finalReadinessReady: true, }, { - condition: "OpenShell does not release the sandbox name", + condition: "OpenShell does not retire the previous lifecycle record", finalizeOutcome: () => ({ backupRemoved: true, lifecycleReleaseObserved: false, @@ -588,7 +622,7 @@ describe("checkAndRecoverSandboxProcesses supervisor relaunch", () => { rolledBack: false, stateRestored: true, }), - expectedDetail: "OpenShell did not release the sandbox name", + expectedDetail: "OpenShell did not retire the previous lifecycle record", expectedReadinessCalls: 1, finalPinnedAction: () => ACCEPTED_MANAGED_PROBE, finalReadinessReady: true,