Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/lib/inference/onboard-probes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1215,6 +1215,17 @@ export async function verifyOnboardInferenceSmoke(options: any) {
console.error(
` Upstream error: ${compactText(redact(probe.message || "unknown inference failure"))}`,
);
// #8952: tear down an unowned managed gateway before fatal exit.
try {
const { teardownOrphanManagedGatewayOnAbort } =
require("../onboard/abort-gateway-teardown") as typeof import("../onboard/abort-gateway-teardown");
teardownOrphanManagedGatewayOnAbort();
} catch (error) {
// Helper never throws; this covers require/load failures only.
console.error(
` Gateway teardown after onboard abort failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
process.exit(1);
}

Expand Down
168 changes: 168 additions & 0 deletions src/lib/onboard/abort-gateway-teardown.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { describe, expect, it, vi } from "vitest";

import {
gatewayHasRegisteredSandbox,
teardownOrphanManagedGatewayOnAbort,
} from "./abort-gateway-teardown";
import { GatewayAuthorityError } from "./gateway-teardown-authority";

describe("gatewayHasRegisteredSandbox", () => {
it("returns true when a sandbox is bound to the gateway name", () => {
const listSandboxes = () => ({
sandboxes: [{ name: "alpha", gatewayName: "nemoclaw-8814", gatewayPort: 8814 }],
defaultSandbox: "alpha" as string | null,
});
expect(gatewayHasRegisteredSandbox("nemoclaw-8814", listSandboxes)).toBe(true);
});

it("returns false when no sandbox owns the gateway", () => {
const listSandboxes = () => ({
sandboxes: [{ name: "alpha", gatewayName: "nemoclaw", gatewayPort: 8080 }],
defaultSandbox: "alpha" as string | null,
});
expect(gatewayHasRegisteredSandbox("nemoclaw-8814", listSandboxes)).toBe(false);
});

it("fails closed when a registry binding cannot be resolved", () => {
const listSandboxes = () => ({
sandboxes: [{ name: "alpha", gatewayName: "not-a-nemoclaw-gateway" }],
defaultSandbox: "alpha" as string | null,
});
expect(gatewayHasRegisteredSandbox("nemoclaw-8814", listSandboxes)).toBe(true);
});
});

describe("teardownOrphanManagedGatewayOnAbort (#8952)", () => {
it("skips teardown when a sandbox still owns the gateway", () => {
const release = vi.fn();
const remove = vi.fn();
const attempted = teardownOrphanManagedGatewayOnAbort({
gatewayPort: 8814,
gatewayName: "nemoclaw-8814",
listSandboxes: () => ({
sandboxes: [{ name: "alpha", gatewayName: "nemoclaw-8814", gatewayPort: 8814 }],
defaultSandbox: "alpha",
}),
releaseManagedGatewayPort: release,
removeGatewayRegistration: remove,
});
expect(attempted).toBe(false);
expect(release).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
});

it("skips teardown for an externally supervised gateway", () => {
const release = vi.fn();
const remove = vi.fn();
const log = vi.fn();
const attempted = teardownOrphanManagedGatewayOnAbort({
gatewayPort: 8814,
gatewayName: "nemoclaw-8814",
listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }),
resolveAuthority: () => ({
gatewayName: "nemoclaw-8814",
gatewayPort: 8814,
mode: "externally-supervised",
source: "declared",
endpoint: "https://gateway.example",
stateDir: null,
supervisor: null,
requiredCapabilities: [],
}),
releaseManagedGatewayPort: release,
removeGatewayRegistration: remove,
log,
});
expect(attempted).toBe(false);
expect(release).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
expect(log.mock.calls.map((call) => String(call[0])).join("\n")).toContain(
"externally supervised",
);
});

it("skips teardown when authority cannot be revalidated", () => {
const release = vi.fn();
const remove = vi.fn();
const warn = vi.fn();
const attempted = teardownOrphanManagedGatewayOnAbort({
gatewayPort: 8814,
gatewayName: "nemoclaw-8814",
listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }),
resolveAuthority: () => {
throw new GatewayAuthorityError("authority mismatch");
},
releaseManagedGatewayPort: release,
removeGatewayRegistration: remove,
warn,
});
expect(attempted).toBe(false);
expect(release).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
expect(warn.mock.calls.map((call) => String(call[0])).join("\n")).toContain(
"authority mismatch",
);
});

it("stops the host listener and removes registration when no sandbox owns the gateway", () => {
const release = vi.fn(() => ({
port: 8814,
released: true,
stopped: [4242],
remaining: [],
scanned: true,
skipped: false,
}));
const remove = vi.fn();
const log = vi.fn();
const attempted = teardownOrphanManagedGatewayOnAbort({
gatewayPort: 8814,
gatewayName: "nemoclaw-8814",
listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }),
resolveAuthority: () => ({
gatewayName: "nemoclaw-8814",
gatewayPort: 8814,
mode: "nemoclaw-managed",
source: "standalone",
endpoint: null,
stateDir: null,
supervisor: null,
requiredCapabilities: [],
}),
releaseManagedGatewayPort: release,
removeGatewayRegistration: remove,
log,
});
expect(attempted).toBe(true);
expect(release).toHaveBeenCalledWith({ port: 8814 });
expect(remove).toHaveBeenCalledWith("nemoclaw-8814");
const output = log.mock.calls.map((call) => String(call[0])).join("\n");
expect(output).toContain("Onboard aborted before a sandbox was created");
expect(output).toContain("Released gateway port 8814");
});

it("warns and returns false when the sandbox registry cannot be read", () => {
const release = vi.fn();
const remove = vi.fn();
const warn = vi.fn();
const attempted = teardownOrphanManagedGatewayOnAbort({
gatewayPort: 8814,
gatewayName: "nemoclaw-8814",
listSandboxes: () => {
throw new Error("registry unreadable");
},
releaseManagedGatewayPort: release,
removeGatewayRegistration: remove,
warn,
});
expect(attempted).toBe(false);
expect(release).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
expect(warn.mock.calls.map((call) => String(call[0])).join("\n")).toContain(
"registry unreadable",
);
});
});
145 changes: 145 additions & 0 deletions src/lib/onboard/abort-gateway-teardown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

/**
* Tear down an unowned NemoClaw-managed host gateway after onboard aborts
* once the gateway is up but before a sandbox is registered (#8952).
* The Docker-driver gateway inherits provider credentials from the onboard
* process environment, so the listener must not survive a failed run.
*/

import { GATEWAY_PORT } from "../core/ports";
import { listSandboxes as listRegisteredSandboxes } from "../state/registry";
import { releaseManagedGatewayPort } from "../tunnel/gateway-port-release";
import { resolveGatewayName, resolveSandboxGatewayName } from "./gateway-binding";
import { isExternallySupervised } from "./gateway-ownership";
import {
GatewayAuthorityError,
resolveGatewayTeardownAuthority,
} from "./gateway-teardown-authority";

export type AbortGatewayTeardownDeps = {
env?: NodeJS.ProcessEnv;
gatewayPort?: number;
gatewayName?: string;
listSandboxes?: typeof listRegisteredSandboxes;
resolveAuthority?: typeof resolveGatewayTeardownAuthority;
releaseManagedGatewayPort?: typeof releaseManagedGatewayPort;
removeGatewayRegistration?: (gatewayName: string) => void;
log?: (message: string) => void;
warn?: (message: string) => void;
};

function defaultRemoveGatewayRegistration(gatewayName: string): void {
// Lazy require keeps unit tests free of openshell binary resolution.
const runtime =
require("../adapters/openshell/runtime") as typeof import("../adapters/openshell/runtime");
runtime.runOpenshell(["gateway", "remove", gatewayName], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
});
}

/**
* True when any registered sandbox is bound to `gatewayName`. An unreadable
* binding fails closed (treat as owned) so abort teardown never guesses.
*/
export function gatewayHasRegisteredSandbox(
gatewayName: string,
listSandboxes: typeof listRegisteredSandboxes = listRegisteredSandboxes,
): boolean {
for (const sandbox of listSandboxes().sandboxes) {
try {
if (resolveSandboxGatewayName(sandbox) === gatewayName) return true;
} catch {
return true;
}
}
return false;
}

/**
* Best-effort: stop the managed host gateway listener and remove its OpenShell
* registration when no sandbox still owns that gateway. Never throws — callers
* on fatal exit paths must still be able to `process.exit(1)` after a warn.
*
* @returns true when a teardown attempt ran (stop and/or remove).
*/
export function teardownOrphanManagedGatewayOnAbort(deps: AbortGatewayTeardownDeps = {}): boolean {
const log = deps.log ?? ((message: string) => console.error(message));
const warn = deps.warn ?? ((message: string) => console.error(message));

try {
const env = deps.env ?? process.env;
const port = deps.gatewayPort ?? GATEWAY_PORT;
const gatewayName = deps.gatewayName ?? resolveGatewayName(port);
const listSandboxes = deps.listSandboxes ?? listRegisteredSandboxes;
const resolveAuthority = deps.resolveAuthority ?? resolveGatewayTeardownAuthority;
const release = deps.releaseManagedGatewayPort ?? releaseManagedGatewayPort;
const removeRegistration = deps.removeGatewayRegistration ?? defaultRemoveGatewayRegistration;

if (gatewayHasRegisteredSandbox(gatewayName, listSandboxes)) {
return false;
}

try {
const owner = resolveAuthority({ gatewayName, gatewayPort: port }, { env });
if (isExternallySupervised(owner)) {
log(
` Keeping externally supervised OpenShell gateway '${gatewayName}' running after onboard abort.`,
);
return false;
}
} catch (error) {
if (error instanceof GatewayAuthorityError) {
warn(` Skipping gateway teardown after onboard abort: ${error.message}`);
return false;
}
warn(
` Skipping gateway teardown after onboard abort: ${error instanceof Error ? error.message : String(error)}`,
);
return false;
}

log(
` Onboard aborted before a sandbox was created; releasing managed gateway '${gatewayName}' so provider credentials do not remain in a live process.`,
);

let attempted = false;
try {
const result = release({ port });
attempted = true;
if (result.released && result.stopped.length > 0) {
log(
` Released gateway port ${String(result.port)} (stopped host process ${result.stopped.join(", ")}).`,
);
} else if (!result.released && !result.skipped) {
warn(
` Gateway port ${String(result.port ?? port)} was not confirmed released after onboard abort. Inspect the listener and stop only the matching openshell-gateway process.`,
);
}
} catch (error) {
attempted = true;
warn(
` Gateway process stop after onboard abort failed: ${error instanceof Error ? error.message : String(error)}`,
);
}

try {
removeRegistration(gatewayName);
attempted = true;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} catch (error) {
warn(
` Gateway registration remove after onboard abort failed: ${error instanceof Error ? error.message : String(error)}`,
);
}

return attempted;
} catch (error) {
// Warn and continue to fatal exit; do not hide a still-live listener.
warn(
` Gateway teardown after onboard abort failed: ${error instanceof Error ? error.message : String(error)}`,
);
return false;
}
}
Loading
Loading