From bd820f94d79bc361bcbd96f9d501bd4b7e988c83 Mon Sep 17 00:00:00 2001 From: simoneschiavoi <314799283+simoneschiavoi@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:46:30 +0200 Subject: [PATCH] fix(sandbox): release held rebuild windows before a CLI bail exits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The interactive CLI rebuild bail prints and calls process.exit, skipping every finally between the callsite and the process edge. A bail raised while the pipeline holds the OpenClaw gateway-down maintenance window therefore stranded that window mid-rebuild (#12919) — the destructive phases had already quiesced the source gateway, and the release finally never ran. The throwOnError callers (MCP worker, sandbox upgrade) were unaffected because their bail throws and unwinds normally. While the pipeline holds a gateway-down window, bail by throwing a RebuildBailSentinel instead: unwinding runs each finally on the way out, and a boundary catch on the pipeline's outer try then delegates to the real bail with the original message and exit code (preserving call arity for code-less bails). The two translating catches that re-bail with their own message pass the sentinel through unchanged, and the maintenance-window release in the finally is guarded so a failing release cannot mask the bail already unwinding. The sentinel lives in rebuild-post-restore-phase.ts — the phase whose doctor-window finally it exists to protect, and already part of the pipeline's runtime import surface — so the fix adds no new dependency edge to the pipeline's guarded fan-out. Signed-off-by: simoneschiavoi <314799283+simoneschiavoi@users.noreply.github.com> --- .../rebuild-pipeline-bail-sentinel.test.ts | 265 ++++++++++++++++++ src/lib/actions/sandbox/rebuild-pipeline.ts | 42 ++- .../rebuild-post-restore-phase.test.ts | 29 +- .../sandbox/rebuild-post-restore-phase.ts | 25 ++ 4 files changed, 358 insertions(+), 3 deletions(-) create mode 100644 src/lib/actions/sandbox/rebuild-pipeline-bail-sentinel.test.ts diff --git a/src/lib/actions/sandbox/rebuild-pipeline-bail-sentinel.test.ts b/src/lib/actions/sandbox/rebuild-pipeline-bail-sentinel.test.ts new file mode 100644 index 00000000000..4ade072daf1 --- /dev/null +++ b/src/lib/actions/sandbox/rebuild-pipeline-bail-sentinel.test.ts @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { rebuildSandbox } from "./rebuild-pipeline"; + +const h = vi.hoisted(() => ({ + exitBail: vi.fn(), + releaseSourceWindow: vi.fn(async () => {}), + backupPhase: vi.fn(), + destroyPhase: vi.fn(), + preflightPhase: vi.fn(), +})); + +vi.mock("./rebuild-preflight-phase", () => ({ + runRebuildPreflightPhase: h.preflightPhase, + runHermesCronRestoreBackupPreflight: vi.fn(async () => null), +})); + +vi.mock("./rebuild-backup-phase", () => ({ + captureRebuildPolicyDocument: vi.fn(async () => null), + bindRebuildSnapshotGpuAuthority: vi.fn((options: unknown) => options), + clearRebuildMcpHandoff: vi.fn(() => true), + clearRebuildPolicyHandoff: vi.fn(() => true), + readRebuildPolicyHandoff: vi.fn(() => null), + readRebuildMcpHandoff: vi.fn(() => null), + releaseRebuildSourceOpenClawWindow: h.releaseSourceWindow, + retireRebuildSourceOpenClawWindowForDelete: vi.fn(async () => undefined), + runRebuildBackupPhase: h.backupPhase, + writeRebuildMcpHandoff: vi.fn(() => true), + writeRebuildPolicyHandoff: vi.fn(() => true), +})); + +vi.mock("./rebuild-destroy-phase", () => ({ + runRebuildDestroyPhase: h.destroyPhase, +})); + +vi.mock("./rebuild-flow-helpers", () => ({ + delegateRebuildToOwningRegistry: vi.fn(async () => false), + disposeRebuildAgentBaseImagePreflight: vi.fn(() => undefined), + removeStaleRebuildDockerOrphan: vi.fn(() => undefined), + snapshotOpenShellEnv: vi.fn(() => () => undefined), +})); + +vi.mock("./rebuild-mcp-phase", () => ({ + observeMcpStateForRebuild: vi.fn(async () => ({ entries: [], runtimeSelection: null })), +})); + +vi.mock("./rebuild-preflight-guards", () => ({ + assertSandboxRebuildCommandAvailable: vi.fn(() => undefined), + revalidateManagedWorkloadRebuildBeforeDelete: vi.fn(() => null), + revalidateRebuildRouteBeforeDelete: vi.fn(() => null), +})); + +vi.mock("./rebuild-prepared-image-context", () => ({ + disposePreparedBuildContext: vi.fn(async () => undefined), + verifyPreparedBuildContext: vi.fn(async () => true), +})); + +vi.mock("./rebuild-prepared-recovery", () => ({ + revalidatePreparedRecoveryBeforeDelete: vi.fn(() => ({ + manifest: null, + registrySnapshot: null, + })), +})); + +vi.mock("./rebuild-provider-preflight", () => ({ + inspectRebuildGatewayProviderRegistration: vi.fn(async () => null), + validateRebuildHostInferenceCredential: vi.fn(async () => null), + shouldVerifyRebuildGatewayProvider: vi.fn(() => false), +})); + +vi.mock("./rebuild-recreate-journal", () => ({ + clearRebuildRecoveryBackup: vi.fn(() => undefined), + findRebuildRecoveryBackup: vi.fn(() => null), + fingerprintRebuildRecreateTargetIntent: vi.fn(() => "intent-fingerprint"), + isRebuildRecoveryCleanupOnly: vi.fn(() => false), + markRebuildRecoveryCleanupOnly: vi.fn(() => undefined), + openRebuildRecreateJournal: vi.fn(() => ({ + id: "journal-1", + acceptedTarget: null, + completeAcceptedTarget: vi.fn(), + })), + assertRebuildRecoverySource: vi.fn(() => undefined), + recordRebuildRecoveryBackup: vi.fn(() => undefined), +})); + +vi.mock("./rebuild-recreate-phase", () => ({ + runRebuildRecreatePhase: vi.fn(async () => undefined), +})); + +vi.mock("./rebuild-registry-rollback", () => ({ + createRebuildRegistryRollback: vi.fn(() => ({ recordRemoval: vi.fn() })), +})); + +vi.mock("./rebuild-restore-phase", () => ({ + runRebuildRestorePhase: vi.fn(async () => undefined), +})); + +vi.mock("../../state/registry", () => ({ + REGISTRY_FILE: "/tmp/nemoclaw-bail-sentinel-test/registry.json", + load: vi.fn(() => ({ sandboxes: {} })), + getSandbox: vi.fn(() => null), + updateSandbox: vi.fn(() => true), + restoreSandboxEntry: vi.fn(() => undefined), + restoreSandboxEntryIfMissing: vi.fn(() => undefined), +})); + +vi.mock("../../state/onboard-session", () => ({ + SESSION_FILE: "/tmp/nemoclaw-bail-sentinel-test/session.json", + loadRebuildSession: vi.fn(() => null), + loadSession: vi.fn(() => null), +})); + +vi.mock("../../state/mcp-lifecycle-lock", () => ({ + withMcpLifecycleLock: vi.fn(async (_sandboxName: string, run: () => Promise) => run()), +})); + +vi.mock("../../onboard/portable-retirement-authority", () => ({ + withPortableOnboardRetirementBoundary: vi.fn(async (_config: unknown, run: () => Promise) => + run(), + ), +})); + +vi.mock("../../state/migrations/removed-immutability", () => ({ + enforceRemovedImmutabilityMigrationBoundary: vi.fn(() => ({ stateRecord: null })), + retireRemovedImmutabilityStateRecord: vi.fn(() => undefined), +})); + +vi.mock("../../onboard/credential-env", () => ({ + hydrateCredentialEnv: vi.fn(() => ({})), +})); + +describe("rebuild pipeline bail sentinel (#12919)", () => { + beforeEach(() => { + vi.clearAllMocks(); + h.releaseSourceWindow.mockImplementation(async () => undefined); + h.preflightPhase.mockResolvedValue({ + sandboxEntry: { name: "alpha", agent: "openclaw" }, + rebuildAgent: "openclaw", + versionCheck: null, + targetConfig: { + resumeConfig: null, + sessionSnapshot: null, + sessionMatchesSandbox: true, + durableConfig: { webSearchConfig: null }, + hermesToolGateways: null, + hasHermesToolGateways: false, + credentialEnv: {}, + fromDockerfile: null, + }, + recreateOptions: { + targetGatewayName: "gw-alpha", + targetGatewayPort: 7001, + rebuildGatewayAuthority: { verified: true }, + runtimeSelection: null, + }, + messagingPlan: null, + recheckMessagingConflicts: null, + baseImagePreflight: null, + liveState: { staleRecovery: false, staleRegistrySnapshot: null }, + recoveryManifest: null, + dcodePreflight: { cleanup: vi.fn(), revalidateBeforeDelete: vi.fn(async () => true) }, + preparedImage: null, + routePreflightReceipt: null, + stoppedSource: null, + releaseOnboardLock: vi.fn(), + log: vi.fn(), + bail: h.exitBail, + } as never); + h.backupPhase.mockResolvedValue({ + ok: true, + backupManifest: { + backupPath: "/tmp/nemoclaw-bail-sentinel-test/backup.tar.zst", + rebuildPolicyHandoff: null, + rebuildMcpHandoff: null, + }, + sourceOpenClawDoctorWindow: { windowToken: "source-window" }, + } as never); + h.destroyPhase.mockResolvedValue({ removalReceipt: null } as never); + h.exitBail.mockImplementation(() => undefined); + vi.spyOn(console, "error").mockImplementation(() => undefined); + vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.spyOn(console, "warn").mockImplementation(() => undefined); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("delegates a bail that fired before any window was held without touching the release", async () => { + h.backupPhase.mockImplementationOnce( + async (input: { bail: (message: string, code?: number) => never }) => { + input.bail("injected backup failure: could not capture sandbox state"); + }, + ); + + await rebuildSandbox("alpha"); + + expect(h.exitBail).toHaveBeenCalledExactlyOnceWith( + "injected backup failure: could not capture sandbox state", + ); + expect(h.releaseSourceWindow).not.toHaveBeenCalled(); + }); + + it("releases the held OpenClaw maintenance window before the delegated CLI bail exits (#12919)", async () => { + h.destroyPhase.mockImplementationOnce( + async (input: { bail: (message: string, code?: number) => never }) => { + input.bail("injected late rebuild bail", 7); + }, + ); + + await rebuildSandbox("alpha"); + + expect(h.exitBail).toHaveBeenCalledExactlyOnceWith("injected late rebuild bail", 7); + expect(h.releaseSourceWindow).toHaveBeenCalledExactlyOnceWith({ windowToken: "source-window" }); + expect(h.releaseSourceWindow.mock.invocationCallOrder[0]).toBeLessThan( + h.exitBail.mock.invocationCallOrder[0], + ); + }); + + it("keeps the original bail message when the window release itself fails (#12919)", async () => { + h.releaseSourceWindow.mockRejectedValueOnce(new Error("release rejected")); + h.destroyPhase.mockImplementationOnce( + async (input: { bail: (message: string, code?: number) => never }) => { + input.bail("injected late rebuild bail"); + }, + ); + + await expect(rebuildSandbox("alpha")).resolves.toBeUndefined(); + + expect(h.exitBail).toHaveBeenCalledExactlyOnceWith("injected late rebuild bail"); + const warnings = vi.mocked(console.error).mock.calls.flat().join("\n"); + expect(warnings).toContain("OpenClaw maintenance window could not be released"); + expect(warnings).toContain("release rejected"); + }); + + it("still releases the window and does not convert non-bail failures into exits", async () => { + h.destroyPhase.mockImplementationOnce(async () => { + throw new Error("destroy exploded"); + }); + + await expect(rebuildSandbox("alpha")).rejects.toThrow("destroy exploded"); + + expect(h.exitBail).not.toHaveBeenCalled(); + expect(h.releaseSourceWindow).toHaveBeenCalledExactlyOnceWith({ windowToken: "source-window" }); + }); + + it("preserves the bail message and exit code when the real bail throws instead of exiting", async () => { + h.exitBail.mockImplementationOnce((message: string, code?: number) => { + throw new Error(`exit:${code}:${message}`); + }); + h.destroyPhase.mockImplementationOnce( + async (input: { bail: (message: string, code?: number) => never }) => { + input.bail("injected late rebuild bail", 7); + }, + ); + + await expect(rebuildSandbox("alpha")).rejects.toThrow("exit:7:injected late rebuild bail"); + expect(h.releaseSourceWindow.mock.invocationCallOrder[0]).toBeLessThan( + h.exitBail.mock.invocationCallOrder[0], + ); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index 3deb98867be..e029c5b67ff 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -37,6 +37,7 @@ import { writeRebuildMcpHandoff, writeRebuildPolicyHandoff, } from "./rebuild-backup-phase"; +import type { RebuildBail } from "./rebuild-credential-preflight"; import { runRebuildDestroyPhase } from "./rebuild-destroy-phase"; import { REBUILD_HERMES_DASHBOARD_ENV_KEYS } from "./rebuild-durable-config"; import { @@ -52,6 +53,7 @@ import { HermesCronRestoreIncompleteError, printHermesCronRestoreRecoveryCommand, recoverHermesCronRestore, + RebuildBailSentinel, runHermesCronRestoreTransaction, runRebuildPostRestorePhase, } from "./rebuild-post-restore-phase"; @@ -222,7 +224,7 @@ async function rebuildSandboxUnlocked( stoppedSource, releaseOnboardLock, log, - bail, + bail: exitBail, } = preflight; const { resumeConfig, @@ -243,6 +245,14 @@ async function rebuildSandboxUnlocked( let rebuildPolicyHandoffManifest: NonNullable | null = null; const preparedBackupRecovery = recoveryManifest !== null; const recoveryRecreate = staleRecovery || preparedBackupRecovery; + // #12919: the CLI bail exits the process, which would skip every finally + // below — including the OpenClaw maintenance-window release held across the + // destructive phases. Bail by sentinel instead so unwinding releases held + // windows exactly as the throwOnError callers already experience; the + // boundary catch delegates to the real bail (exitBail) afterwards. + const bail: RebuildBail = (message, code) => { + throw new RebuildBailSentinel(message, code); + }; // A stopped source has no live DCode route to probe. Keep the replacement, // registry, image, and gateway-schema checks, but use the same route-probe // exemption at every destructive-boundary revalidation that preflight used. @@ -716,6 +726,9 @@ async function rebuildSandboxUnlocked( } log(`Hermes cron restore recovery for accepted replacement: ${outcome}`); } catch (error) { + // A bail already carries its own message; translating it here + // would replace the operator-facing reason mid-unwind (#12919). + if (error instanceof RebuildBailSentinel) throw error; console.error(""); console.error( ` Hermes cron restore could not validate and release the accepted replacement: ${rebuildFailureDetail(error)}`, @@ -1000,6 +1013,9 @@ async function rebuildSandboxUnlocked( hermesCronRestoreIdentity = transaction.identity; return transaction.result; } catch (error) { + // A bail already carries its own message; translating it here + // would replace the operator-facing reason mid-unwind (#12919). + if (error instanceof RebuildBailSentinel) throw error; console.error(""); console.error( error instanceof HermesCronRestoreIncompleteError @@ -1043,8 +1059,17 @@ async function rebuildSandboxUnlocked( retainPolicyHandoffForRecovery = false; } finally { if (sourceOpenClawDoctorWindow) { - await releaseRebuildSourceOpenClawWindow(sourceOpenClawDoctorWindow); + const retainedSourceWindow = sourceOpenClawDoctorWindow; sourceOpenClawDoctorWindow = null; + try { + await releaseRebuildSourceOpenClawWindow(retainedSourceWindow); + } catch (releaseError) { + // A failing release must not mask the failure already unwinding — + // the boundary still needs to see the original bail or error. + console.error( + ` Warning: the OpenClaw maintenance window could not be released: ${rebuildFailureDetail(releaseError)}`, + ); + } } const handoffManifest = rebuildPolicyHandoffManifest; if ( @@ -1065,6 +1090,19 @@ async function rebuildSandboxUnlocked( ); } } + } catch (error) { + if (error instanceof RebuildBailSentinel) { + // Every finally above — the OpenClaw maintenance-window release, the + // recovery-handoff cleanups, the onboard lock — has already unwound by + // the time a bail sentinel reaches this boundary, so delegating here + // cannot strand them the way an in-flight process.exit would (#12919). + // Preserve the original call arity: code-less bails keep reaching the + // real bail as single-argument calls (the CLI default stays exit 1). + return error.code === undefined + ? exitBail(error.message) + : exitBail(error.message, error.code); + } + throw error; } finally { if (stoppedSource) runBestEffortRebuildCleanup( diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts index 0447cc3291b..320e5e4abd2 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts @@ -29,7 +29,7 @@ import * as restoreWindow from "./runtime/openclaw-lifecycle"; import * as rebuildHermesPostRestore from "./rebuild-hermes-post-restore"; import * as rebuildMcp from "./rebuild-mcp-phase"; import * as rebuildMessaging from "./rebuild-messaging-phase"; -import { runRebuildPostRestorePhase } from "./rebuild-post-restore-phase"; +import { RebuildBailSentinel, runRebuildPostRestorePhase } from "./rebuild-post-restore-phase"; import { createRebuildCommandContext } from "./rebuild-preflight-confirmation"; const processRecovery = restoreWindow; @@ -330,6 +330,33 @@ describe("rebuild post-restore phase", () => { }, ); + it("aborts the OpenClaw maintenance window before a sentinel bail escapes the phase (#12919)", async () => { + agentName = "openclaw"; + vi.mocked(rebuildMessaging.reapplyMessagingManifestBeforeAgentStart).mockImplementationOnce( + async () => { + order.push("messaging"); + throw new Error("injected reapply failure"); + }, + ); + // The pipeline supplies a sentinel-throwing bail while it holds the + // gateway-down window; the phase must unwind its abort before that bail + // escapes, exactly as it does for the throwOnError callers. + const args = { + ...input(), + bail: (message: string, code?: number) => { + throw new RebuildBailSentinel(message, code); + }, + }; + + await expect(runRebuildPostRestorePhase(args)).rejects.toThrow( + "Messaging manifest config reapply failed during rebuild.", + ); + + expect(order).toEqual(["maintenance-begin", "messaging", "doctor-abort"]); + expect(restoreWindow.finishUnregisteredOpenClawPostRestoreDoctor).not.toHaveBeenCalled(); + expect(rebuildMcp.restoreMcpAfterRebuild).not.toHaveBeenCalled(); + }); + it("completes offline restoration before one native final start (#7102, #9946, #11764)", async () => { await runRebuildPostRestorePhase(input()); diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts index f890bcea984..dead4c3c2c9 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts @@ -57,6 +57,28 @@ export { runHermesCronRestoreTransaction, } from "./rebuild-hermes-post-restore"; +/** + * The interactive CLI rebuild bail prints and calls process.exit, which skips + * every finally between the callsite and the process edge — stranding held + * OpenClaw maintenance windows mid-rebuild (#12919). While the pipeline holds + * a gateway-down window it therefore bails by throwing this sentinel instead: + * unwinding runs each finally on the way out (the same semantics the + * throwOnError callers already rely on), and the pipeline's boundary catch + * then delegates to the real bail with the original message and exit code. + * Defined here — the phase whose doctor-window finally the sentinel exists to + * protect, and already part of the pipeline's runtime import surface — so the + * fix adds no new dependency edge to the pipeline's guarded fan-out. + */ +export class RebuildBailSentinel extends Error { + constructor( + message: string, + readonly code: number | undefined, + ) { + super(message); + this.name = "RebuildBailSentinel"; + } +} + export function printHermesCronRestoreRecoveryCommand( sandboxName: string, writeLine: (message: string) => void = console.error, @@ -350,6 +372,9 @@ export async function runRebuildPostRestorePhase( effectiveMessagingPlan = finalizedMessagingPlan; } } catch (error) { + // A bail already carries its own message; translating it here would + // replace the operator-facing reason mid-unwind (#12919). + if (error instanceof RebuildBailSentinel) throw error; bail( `Could not finalize pending messaging removals after rebuild: ${ error instanceof Error ? error.message : String(error)