diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index d88c1645f8e..cae528b450f 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -149,7 +149,9 @@ Use the dedicated gateway state directory created for that port, not a shared or Onboarding rejects relative overrides, the shared NemoClaw state root or its parents, and existing nonempty directories without valid NemoClaw-managed gateway configuration. Let onboarding create the directory when possible. Every existing ancestor, from its containing directory to the filesystem root, must be a real directory owned by the current user or root and must not be group- or world-writable. If the state directory already exists, it must be an owner-controlled, non-symbolic-link directory with mode `0700`. If onboarding stops immediately after reserving that directory, uninstall removes the marker-only reservation only while the selected gateway port is free. Gateway configuration, a runtime marker, or a PID file moves cleanup to the managed-gateway checks instead. A port-bound marked gateway with valid generated configuration can be retired after the port is free and a complete process scan proves that no live process claims its state; a listener or unproven process preserves the directory. Inspect and stop the listener or matching gateway process, then rerun uninstall after the port is free. -Onboarding holds an exclusive lifecycle lock from reservation through gateway initialization. If uninstall reports that onboarding owns the state directory, wait for onboarding to finish and rerun uninstall; the reservation is preserved. +Onboarding holds an exclusive lifecycle lock from reservation through gateway initialization. +If uninstall reports that onboarding owns the state directory while onboarding is active, wait for onboarding to finish and rerun uninstall; the reservation is preserved. +If the reported `onboard.lock` remains after onboarding ended abruptly, confirm that no NemoClaw onboarding process is active in any environment that shares the state root, remove only the reported lock, and rerun uninstall. After successful managed cleanup, uninstall recursively removes that directory and all contents. Portable cleanup and `--keep-openshell` preserve it. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 228825373bc..77bee9c31fb 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3535,7 +3535,9 @@ Use the dedicated gateway state directory created for that port, not a shared or Onboarding rejects relative overrides, the shared NemoClaw state root or its parents, and existing nonempty directories without valid NemoClaw-managed gateway configuration. Let onboarding create the directory when possible. Every existing ancestor, from its containing directory to the filesystem root, must be a real directory owned by the current user or root and must not be group- or world-writable. If the state directory already exists, it must be an owner-controlled, non-symbolic-link directory with mode `0700`. If onboarding stops immediately after reserving that directory, uninstall removes the marker-only reservation only while the selected gateway port is free. Gateway configuration, a runtime marker, or a PID file moves cleanup to the managed-gateway checks instead. A port-bound marked gateway with valid generated configuration can be retired after the port is free and a complete process scan proves that no live process claims its state; a listener or unproven process preserves the directory. Inspect and stop the listener or matching gateway process, then rerun uninstall after the port is free. -Onboarding holds an exclusive lifecycle lock from reservation through gateway initialization. If uninstall reports that onboarding owns the state directory, wait for onboarding to finish and rerun uninstall; the reservation is preserved. +Onboarding holds an exclusive lifecycle lock from reservation through gateway initialization. +If uninstall reports that onboarding owns the state directory while onboarding is active, wait for onboarding to finish and rerun uninstall; the reservation is preserved. +If the reported `onboard.lock` remains after onboarding ended abruptly, confirm that no NemoClaw onboarding process is active in any environment that shares the state root, remove only the reported lock, and rerun uninstall. Successful managed cleanup recursively removes that directory and all contents; portable cleanup and `--keep-openshell` preserve it. Before cleanup, uninstall validates port-bound state-root ownership and exact live process identity. A marked, stopped gateway can instead use a free port plus a complete process-absence scan; pre-marker gateways can use their owner-private generated configuration as the legacy ownership proof only with live process identity. diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 739d84adf55..2fe87adbc3e 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2674,9 +2674,13 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { collector: null, span: null, }; - let completed = false, - preserveDeferredExitSession = false, - preserveIncompleteSession = false; + let completed = false; + let preserveIncompleteSession = false; + registerIncompleteOnboardExitHandlerForSession( + { ...onboardSession, releaseOnboardLock: portableRetirementEntry.release }, + () => completed || preserveIncompleteSession, + ); + let preserveDeferredExitSession = false; try { await portableRetirementEntry.run(async () => { const entryOptions = resolveEntryOptions(); @@ -2798,10 +2802,6 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { ); process.exit(1); } - registerIncompleteOnboardExitHandlerForSession( - onboardSession, - () => completed || preserveIncompleteSession, - ); const agent = await selectOnboardAgent({ agentFlag: opts.agent, session, diff --git a/src/lib/onboard/exit-step-failure.test.ts b/src/lib/onboard/exit-step-failure.test.ts index 837e96fe8c1..e5811bd2fa0 100644 --- a/src/lib/onboard/exit-step-failure.test.ts +++ b/src/lib/onboard/exit-step-failure.test.ts @@ -348,31 +348,37 @@ describe("incomplete-onboard --resume backstop (#6003)", () => { }); it.skipIf(process.platform === "win32")( - "prints the resume hint before re-raising SIGINT in a real subprocess", + "releases the owned lock before re-raising SIGINT in a real subprocess", async () => { const childDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-resume-signal-")); const childScript = path.join(childDir, "signal-resume-hint.cjs"); const helperPath = path.resolve("src/lib/onboard/exit-step-failure.ts"); + const onboardSessionPath = path.resolve("src/lib/state/onboard-session.ts"); fs.writeFileSync( childScript, ` const { registerIncompleteOnboardExitFailureHandler } = require(${JSON.stringify(helperPath)}); +const onboardSession = require(${JSON.stringify(onboardSessionPath)}); + +if (!onboardSession.acquireOnboardLock("signal cleanup test").acquired) process.exit(2); const resumableSession = { lastStepStarted: "inference" }; registerIncompleteOnboardExitFailureHandler( { loadSession: () => resumableSession, finalizeIncompleteOnboardStep: () => resumableSession, + releaseOnboardLock: onboardSession.releaseOnboardLock, }, () => false, "Onboarding exited before the step completed.", ); -process.stdout.write("ready\\n"); +process.stdout.write(JSON.stringify({ lockFile: onboardSession.LOCK_FILE }) + "\\n"); setInterval(() => {}, 1_000); `, ); const child = spawn(process.execPath, ["--require", "tsx/cjs", childScript], { + env: { ...process.env, HOME: childDir }, stdio: ["ignore", "pipe", "pipe"], }); let stderr = ""; @@ -383,13 +389,15 @@ setInterval(() => {}, 1_000); try { const [ready] = await once(child.stdout, "data"); - expect(String(ready)).toContain("ready"); + const { lockFile } = JSON.parse(String(ready)) as { lockFile: string }; + expect(fs.existsSync(lockFile)).toBe(true); const exited = once(child, "exit"); child.kill("SIGINT"); const [code, signal] = await exited; expect(code).toBeNull(); expect(signal).toBe("SIGINT"); expect(stderr).toContain("onboard --resume"); + expect(fs.existsSync(lockFile)).toBe(false); } finally { child.kill("SIGKILL"); fs.rmSync(childDir, { recursive: true, force: true }); diff --git a/src/lib/onboard/exit-step-failure.ts b/src/lib/onboard/exit-step-failure.ts index 0977dae42fd..c4516c9e3bd 100644 --- a/src/lib/onboard/exit-step-failure.ts +++ b/src/lib/onboard/exit-step-failure.ts @@ -7,6 +7,7 @@ import { printOnboardResumeHint } from "./resume-hint"; export interface ExitStepFailureSessionDeps { loadSession(): Pick | null; + releaseOnboardLock?(): void; finalizeIncompleteOnboardStep( stepName: string, message?: string | null, @@ -81,8 +82,15 @@ export function registerIncompleteOnboardExitFailureHandler( setImmediate(() => { removeListener("SIGINT", onSigint); removeListener("SIGTERM", onSigterm); - failIncompleteStep(true); - kill(pid, signal); + try { + failIncompleteStep(true); + } finally { + try { + deps.releaseOnboardLock?.(); + } finally { + kill(pid, signal); + } + } }); }; const onSigint = (): void => handleSignal("SIGINT"); diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 63733dcef1c..55c72c600be 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -447,14 +447,16 @@ describe("legacy non-default gateway state migration", () => { const shared = path.join(home, ".nemoclaw"); const selected = path.join(shared, "gateways", "9123"); const recoveryFile = path.join(shared, "retained-sandbox-recovery.json"); + const lockFile = path.join(root(shared, selected), "onboard.lock"); recordRecovery(recoveryFile, "port-box", 9123, "d"); const before = fs.readFileSync(recoveryFile, "utf8"); fs.mkdirSync(root(shared, selected), { recursive: true }); - fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); + fs.writeFileSync(lockFile, "active writer"); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - /onboarding lock .* is present/u, + `onboarding lock ${lockFile} is present; confirm that no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${lockFile} and retry; migration will not remove it automatically`, ); + expect(fs.readFileSync(lockFile, "utf8")).toBe("active writer"); expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); expect(fs.existsSync(path.join(selected, "retained-sandbox-recovery.json"))).toBe(false); }); diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index 1611edc04b5..335ef5fdfe2 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -768,7 +768,7 @@ function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]) const activeLock = path.join(stateRoot, "onboard.lock"); if (lstatNoFollow(home, activeLock)) { throw migrationError( - `onboarding lock ${activeLock} is present; finish or stop that run before migrating state`, + `onboarding lock ${activeLock} is present; confirm that no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${activeLock} and retry; migration will not remove it automatically`, ); } } diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index a6704cd4f0a..3c622ec1071 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -1297,12 +1297,20 @@ describe("onboard session", () => { } }); - it("ignores malformed lock files when releasing the onboard lock", () => { + it("preserves a foreign lock that uses the local PID when no descriptor is held", () => { fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - fs.writeFileSync(session.LOCK_FILE, "{not-json", { mode: 0o600 }); + const contents = JSON.stringify({ + pid: process.pid, + startedAt: new Date().toISOString(), + command: "foreign owner", + processGeneration: "foreign-generation", + hostIdentity: "foreign-host", + pidNamespaceIdentity: "foreign-namespace", + }); + fs.writeFileSync(session.LOCK_FILE, contents, { mode: 0o600 }); session.releaseOnboardLock(); - expect(fs.existsSync(session.LOCK_FILE)).toBe(true); + expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(contents); }); it("redacts sensitive values from persisted failure messages", () => { diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 44ad0556d6b..0d17065d3db 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -1696,24 +1696,8 @@ export function releaseOnboardLock(): void { return; } - // Fallback (no fd held — e.g., a test wrote the lock file directly, - // or a previous release already ran): preserve the legacy pid-based - // behavior so we never unlink a malformed lock and never unlink a - // lock owned by another pid. - try { - let snapshot: LockFileSnapshot; - try { - snapshot = readLockFileSnapshot(); - } catch (error) { - if (isErrnoException(error) && error.code === "ENOENT") return; - throw error; - } - if (!snapshot.info) return; - if (snapshot.info.pid !== process.pid) return; - unlinkIfInodeMatches(LOCK_FILE, snapshot.inode); - } catch { - return; - } + // A PID match does not prove ownership across hosts or PID namespaces. + // Without the retained descriptor, this process has no cleanup authority. } // ── Step management ────────────────────────────────────────────── diff --git a/test/onboarding/onboard-exit-handler.test.ts b/test/onboarding/onboard-exit-handler.test.ts index 0f6a1d522ed..6ba1ee5ae66 100644 --- a/test/onboarding/onboard-exit-handler.test.ts +++ b/test/onboarding/onboard-exit-handler.test.ts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; +import { once } from "node:events"; import fs from "node:fs"; import { createRequire } from "node:module"; import os from "node:os"; @@ -9,6 +10,8 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { testTimeout } from "../helpers/timeouts"; + type OnboardModule = typeof import("../../src/lib/onboard") & { onboardSession: typeof import("../../src/lib/state/onboard-session"); registerIncompleteOnboardExitHandlerForSession: ( @@ -101,6 +104,183 @@ describe("onboard exit handler registration", () => { expect(loaded.machine.state).toBe("init"); }); + it.skipIf(process.platform === "win32")( + "onboard releases its owned lock during entry setup and preserves replacement and outer-owned locks (#10779)", + async () => { + const repoRoot = path.join(import.meta.dirname, "../.."); + const scriptPath = path.join(tmpDir, "onboard-entry-signal.cjs"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const sessionPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), + ); + const lockedRuntimePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "resume", "locked-runtime.ts"), + ); + const replacement = "replacement lock"; + + fs.writeFileSync( + scriptPath, + ` +const fs = require("node:fs"); +const lockedRuntimePath = ${lockedRuntimePath}; +const lockedRuntime = require(lockedRuntimePath); +const onboardSession = require(${sessionPath}); +const replaceLock = process.argv.includes("--replace-lock"); +const outerOwnsLock = process.argv.includes("--outer-lock"); + +if (outerOwnsLock) { + const lock = onboardSession.acquireOnboardLock("outer rebuild lifecycle"); + if (!lock.acquired) throw new Error("outer rebuild lifecycle did not acquire onboard lock"); + let signalDeliveries = 0; + const releaseFromOuterLifecycle = () => { + signalDeliveries += 1; + if (signalDeliveries === 1) return; + const lockContents = fs.readFileSync(onboardSession.LOCK_FILE, "utf8"); + onboardSession.releaseOnboardLock(); + process.removeListener("SIGINT", releaseFromOuterLifecycle); + process.stdout.write( + "NEMOCLAW_OUTER_RELEASE " + JSON.stringify({ lockContents }) + "\\n", + () => process.kill(process.pid, "SIGINT"), + ); + }; + process.on("SIGINT", releaseFromOuterLifecycle); +} + +const pauseDuringLockedRuntimePreparation = async () => { + if (replaceLock) { + fs.unlinkSync(onboardSession.LOCK_FILE); + fs.writeFileSync(onboardSession.LOCK_FILE, ${JSON.stringify(replacement)}); + } + process.stdout.write( + "NEMOCLAW_SIGNAL_READY " + + JSON.stringify({ + lockFile: onboardSession.LOCK_FILE, + lockContents: fs.readFileSync(onboardSession.LOCK_FILE, "utf8"), + }) + + "\\n", + ); + await new Promise(() => {}); + throw new Error("unreachable"); +}; +require.cache[require.resolve(lockedRuntimePath)].exports = { + ...lockedRuntime, + prepare: pauseDuringLockedRuntimePreparation, +}; + +const { onboard } = require(${onboardPath}); +setInterval(() => {}, 1_000); +onboard({ + nonInteractive: true, + autoYes: true, + acceptThirdPartySoftware: true, + noGpu: true, + sandboxName: "entry-signal", + ...(outerOwnsLock + ? { + resume: true, + recreateSandbox: true, + authoritativeResumeConfig: true, + onboardLockAlreadyHeld: true, + targetGatewayName: "nemoclaw-9090", + targetGatewayPort: 9090, + } + : {}), +}).catch((error) => { + console.error(error && error.stack ? error.stack : String(error)); + process.exitCode = 1; +}); +`, + ); + + const run = async (mode: "owned" | "replacement" | "outer") => { + const replaceLock = mode === "replacement"; + const outerOwnsLock = mode === "outer"; + const home = path.join(tmpDir, `${mode}-home`); + fs.mkdirSync(home); + const child = spawn( + process.execPath, + [ + "--require", + "tsx/cjs", + scriptPath, + ...(replaceLock ? ["--replace-lock"] : []), + ...(outerOwnsLock ? ["--outer-lock"] : []), + ], + { + cwd: repoRoot, + env: { + ...process.env, + HOME: home, + PATH: ONBOARD_FIXTURE_PATH, + TMPDIR: tmpDir, + NEMOCLAW_TEST_NO_SLEEP: "1", + }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + let stderr = ""; + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderr += chunk; + }); + let stdout = ""; + + try { + const ready = await new Promise((resolve, reject) => { + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdout += chunk; + stdout + .split("\n") + .filter((candidate) => candidate.startsWith("NEMOCLAW_SIGNAL_READY ")) + .forEach((line) => resolve(line.slice("NEMOCLAW_SIGNAL_READY ".length))); + }); + child.once("exit", (code, signal) => { + reject( + new Error( + `onboard child exited before readiness: code=${String(code)} signal=${String(signal)} stderr=${stderr}`, + ), + ); + }); + }); + const { lockFile, lockContents } = JSON.parse(ready) as { + lockFile: string; + lockContents: string; + }; + expect(fs.existsSync(lockFile)).toBe(true); + const exited = once(child, "exit"); + child.kill("SIGINT"); + const [code, signal] = await exited; + expect(code, stderr).toBeNull(); + expect(signal, stderr).toBe("SIGINT"); + const assertResult = { + owned: () => expect(fs.existsSync(lockFile)).toBe(false), + replacement: () => expect(fs.readFileSync(lockFile, "utf8")).toBe(replacement), + outer: () => { + const outerRelease = stdout + .split("\n") + .find((line) => line.startsWith("NEMOCLAW_OUTER_RELEASE ")); + expect(outerRelease, stderr).toBeDefined(); + const outerPayload = JSON.parse( + outerRelease?.slice("NEMOCLAW_OUTER_RELEASE ".length) ?? "{}", + ) as { lockContents?: string }; + expect(outerPayload.lockContents).toBe(lockContents); + expect(fs.existsSync(lockFile)).toBe(false); + }, + } satisfies Record void>; + assertResult[mode](); + } finally { + child.kill("SIGKILL"); + } + }; + + await run("owned"); + await run("replacement"); + await run("outer"); + }, + testTimeout(30_000), + ); + it("resumes clean validation exits while cleanup failures and unexpected exits stay terminal (#9732)", () => { const repoRoot = path.join(import.meta.dirname, "../.."); const scriptPath = path.join(tmpDir, "onboard-exit-registration.cjs"); @@ -210,9 +390,8 @@ const { onboard } = require(${onboardPath}); ) { throw error; } - const exitHandler = exitListeners.at(-1); - if (!exitHandler) throw new Error("missing exit handler"); - exitHandler(1); + if (exitListeners.length === 0) throw new Error("missing exit handler"); + for (const exitHandler of exitListeners) exitHandler(1); const loaded = onboardSession.loadSession(); console.log(JSON.stringify({ loaded, exitListeners: exitListeners.length })); } finally { @@ -315,7 +494,7 @@ const { onboard } = require(${onboardPath}); expect(resumePayload.loaded.status).toBe("in_progress"); expect(resumePayload.loaded.failure).toBeNull(); expect(resumePayload.loaded.machine.state).toBe("preflight"); - }); + }, testTimeout(30_000)); it("onboard() preserves a resumable session after a normal incomplete result (#9048)", () => { const repoRoot = path.join(import.meta.dirname, "../..");