From aa865b5c73cef7c4b285a55c6ac694c0123c99cd Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 09:32:47 -0400 Subject: [PATCH 01/12] fix(state): observe stale onboarding locks Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 103 ++++++-- src/lib/state/legacy-port-migration.ts | 12 +- src/lib/state/onboard-session.ts | 5 +- src/lib/state/onboard-session/index.ts | 17 ++ .../onboard-session/lock-observation.test.ts | 223 ++++++++++++++++++ .../state/onboard-session/lock-observation.ts | 211 +++++++++++++++++ 6 files changed, 548 insertions(+), 23 deletions(-) create mode 100644 src/lib/state/onboard-session/index.ts create mode 100644 src/lib/state/onboard-session/lock-observation.test.ts create mode 100644 src/lib/state/onboard-session/lock-observation.ts diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 63733dcef1c..d9afe334689 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -7,11 +7,16 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { - type OnboardEntryOptionsDeps, - resolveOnboardEntryOptions, -} from "../onboard/entry-options"; +const { observeOnboardLock } = vi.hoisted(() => ({ + observeOnboardLock: vi.fn<(lockPath: string) => OnboardLockObservation>(() => ({ + kind: "absent", + })), +})); +vi.mock("./onboard-session/lock-observation", () => ({ observeOnboardLock })); + +import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions } from "../onboard/entry-options"; import { hasMigratableLegacySandbox, migrateLegacyPortState } from "./legacy-port-migration"; +import type { OnboardLockObservation } from "./onboard-session/lock-observation"; import { listRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery, @@ -87,6 +92,8 @@ function expectRetainedNameBlocked( } afterEach(() => { + observeOnboardLock.mockReset(); + observeOnboardLock.mockReturnValue({ kind: "absent" }); vi.restoreAllMocks(); for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); }); @@ -452,41 +459,99 @@ describe("legacy non-default gateway state migration", () => { fs.mkdirSync(root(shared, selected), { recursive: true }); fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); + observeOnboardLock.mockImplementation((lockPath: string): OnboardLockObservation => + fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, + ); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - /onboarding lock .* is present/u, + new RegExp( + `onboarding lock .* is unverified; confirm no NemoClaw onboarding process .* then remove only ${path.join(root(shared, selected), "onboard.lock")} and retry; migration will not remove it automatically`, + "u", + ), ); expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); expect(fs.existsSync(path.join(selected, "retained-sandbox-recovery.json"))).toBe(false); }); - it.each( - ["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"], - )("keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { + it("migrates past a proven-stale onboarding lock without removing it", () => { const home = makeHome(); const shared = path.join(home, ".nemoclaw"); const selected = path.join(shared, "gateways", "9123"); + const lock = path.join(shared, "onboard.lock"); writeJson(path.join(shared, "sandboxes.json"), { defaultSandbox: "port-box", sandboxes: { "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, }, }); - writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); - fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); - fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); - fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); - - const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); + writeJson(path.join(shared, "onboard-session.json"), { + sandboxName: "port-box", + metadata: { gatewayName: "nemoclaw-9123" }, + }); + fs.writeFileSync(lock, "retained stale lock"); + observeOnboardLock.mockReturnValue({ + kind: "stale", + reason: "departed", + owner: { + pid: 123, + startedAt: null, + command: null, + processGeneration: "boot:10", + hostIdentity: "host-a", + pidNamespaceIdentity: "pid:[1]", + }, + }); - expect(result.warnings).toEqual([]); + expect(migrateLegacyPortState({ home, gatewayPort: 9123 }).migratedSession).toBe(true); + expect(fs.readFileSync(lock, "utf8")).toBe("retained stale lock"); + expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); + }); - expect(fs.existsSync(path.join(shared, entry))).toBe(true); - expect(fs.existsSync(path.join(selected, entry))).toBe(false); + it("refuses an onboarding lock below a symbolic-link state root", () => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + const outside = path.join(home, "outside"); + recordRecovery(path.join(shared, "retained-sandbox-recovery.json"), "port-box", 9123, "d"); + fs.mkdirSync(path.dirname(selected), { recursive: true }); + fs.mkdirSync(outside); + fs.writeFileSync(path.join(outside, "onboard.lock"), "outside lock"); + fs.symlinkSync(outside, selected, "dir"); - expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); - expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); + expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow(/symbolic link/); + expect(observeOnboardLock).toHaveBeenCalledOnce(); + expect(observeOnboardLock).toHaveBeenCalledWith(path.join(shared, "onboard.lock")); + expect(fs.readFileSync(path.join(outside, "onboard.lock"), "utf8")).toBe("outside lock"); }); + it.each(["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"])( + "keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", + (entry) => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + writeJson(path.join(shared, "sandboxes.json"), { + defaultSandbox: "port-box", + sandboxes: { + "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, + }, + }); + writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); + fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); + fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); + fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); + + const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); + + expect(result.warnings).toEqual([]); + + expect(fs.existsSync(path.join(shared, entry))).toBe(true); + expect(fs.existsSync(path.join(selected, entry))).toBe(false); + + expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); + expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); + }, + ); + it.each([8080, 9123])( "removes only generated stale migration-intent directories for gateway port %i", (gatewayPort) => { diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index 1611edc04b5..22ebdc6ec31 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -15,6 +15,7 @@ import { readGatewayRegistryFile, registryEntryGatewayPort, } from "./gateway-registry"; +import { observeOnboardLock } from "./onboard-session/lock-observation"; import { listRetainedSandboxRecoveryRecords, retainedSandboxRecoveryFile, @@ -766,9 +767,16 @@ function acquireDirectoryLock(home: string, lock: string): string { function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]): void { for (const stateRoot of stateRoots) { const activeLock = path.join(stateRoot, "onboard.lock"); - if (lstatNoFollow(home, activeLock)) { + assertGatewayStatePathSafe(home, activeLock); + const lock = observeOnboardLock(activeLock); + if (lock.kind === "busy") { + const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; + const recovery = + lock.reason === "unverified" + ? `confirm 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` + : "finish that run or verify the lock owner before retrying"; throw migrationError( - `onboarding lock ${activeLock} is present; finish or stop that run before migrating state`, + `onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`, ); } } diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 44ad0556d6b..b4962fa7ae1 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -61,6 +61,7 @@ import { } from "./onboard-session-tool-disclosure"; import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; import { + createOnboardLockOwner, listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, retainedSandboxRecoveryAuthorityIsCurrent, @@ -70,7 +71,7 @@ import { type RetainedSandboxRecoveryRecord, type RetainedSandboxRecoveryReason, validSafeEvidence, -} from "./onboard-session/retained-sandbox-recovery"; +} from "./onboard-session/index"; import type { SandboxEntry, SandboxHostMount } from "./registry/types"; import { hasUnsafeHostMountTerminalText } from "./registry/host-mount"; import { nemoclawStateRoot } from "./state-root"; @@ -1490,7 +1491,7 @@ export function isOnboardLockHeldByCurrentProcess(): boolean { export function acquireOnboardLock(command: string | null = null): LockResult { ensureSessionDir(); const payload = JSON.stringify( - { + createOnboardLockOwner(typeof command === "string" ? command : null) ?? { pid: process.pid, startedAt: new Date().toISOString(), command: typeof command === "string" ? command : null, diff --git a/src/lib/state/onboard-session/index.ts b/src/lib/state/onboard-session/index.ts new file mode 100644 index 00000000000..fe7ccdf32cf --- /dev/null +++ b/src/lib/state/onboard-session/index.ts @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { createOnboardLockOwner } from "./lock-observation"; +export { + listRetainedSandboxRecoveryRecords, + recordRetainedSandboxRecovery, + retainedSandboxRecoveryAuthorityIsCurrent, + retainedSandboxRecoveryFile, + resolveRetainedSandboxRecovery, + validSafeEvidence, +} from "./retained-sandbox-recovery"; +export type { + RecordRetainedSandboxRecoveryInput, + RetainedSandboxRecoveryRecord, + RetainedSandboxRecoveryReason, +} from "./retained-sandbox-recovery"; diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts new file mode 100644 index 00000000000..5b7ae8243c8 --- /dev/null +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { spawnSync } from "node:child_process"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + observeOnboardLock, + systemOnboardLockEvidence, + type OnboardLockEvidence, + type OnboardLockOwner, +} from "./lock-observation"; + +const roots: string[] = []; + +function fixture(): { + evidence: OnboardLockEvidence; + lock: string; + owner: OnboardLockOwner; +} { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-observation-")); + roots.push(root); + const lock = path.join(root, "onboard.lock"); + const owner: OnboardLockOwner = { + pid: 123, + startedAt: "2026-09-02T00:00:00.000Z", + command: "nemoclaw onboard", + processGeneration: "boot:10", + hostIdentity: "host-a", + pidNamespaceIdentity: "pid:[1]", + }; + const evidence: OnboardLockEvidence = { + hostIdentity: () => "host-a", + pidNamespaceIdentity: () => "pid:[1]", + processGeneration: () => "boot:10", + processAlive: () => true, + }; + return { evidence, lock, owner }; +} + +function writeOwner(lock: string, owner: OnboardLockOwner): void { + fs.writeFileSync(lock, JSON.stringify(owner), { mode: 0o600 }); +} + +afterEach(() => { + vi.restoreAllMocks(); + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +describe("onboarding lock observation", () => { + it("reports a missing lock as absent", () => { + const { evidence, lock } = fixture(); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "absent" }); + }); + + it("reports only proven-local departed and reused owners as stale", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + expect(observeOnboardLock(lock, { ...evidence, processAlive: () => false })).toMatchObject({ + kind: "stale", + reason: "departed", + }); + expect( + observeOnboardLock(lock, { + ...evidence, + processGeneration: () => "boot:11", + }), + ).toMatchObject({ kind: "stale", reason: "pid-reused" }); + }); + + it.each([ + ["active", {}], + ["unverified", { processGeneration: () => null }], + ["foreign", { hostIdentity: () => "host-b" }], + ["foreign", { pidNamespaceIdentity: () => "pid:[2]" }], + ] as const)("keeps %s owners busy", (reason, overrides) => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + expect(observeOnboardLock(lock, { ...evidence, ...overrides })).toMatchObject({ + kind: "busy", + reason, + }); + }); + + it("keeps legacy, oversized, linked, and non-regular state busy", () => { + const { evidence, lock } = fixture(); + fs.writeFileSync(lock, JSON.stringify({ pid: 123 })); + expect(observeOnboardLock(lock, evidence)).toMatchObject({ kind: "busy" }); + fs.writeFileSync(lock, "x".repeat(64 * 1024 + 1)); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unsafe", + }); + fs.rmSync(lock); + fs.mkdirSync(lock); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unsafe", + }); + }); + + it("keeps symlink and hard-linked lock paths unsafe", () => { + const { evidence, lock, owner } = fixture(); + const target = `${lock}.target`; + writeOwner(target, owner); + fs.symlinkSync(target, lock); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + + fs.rmSync(lock); + fs.linkSync(target, lock); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + + it.runIf(process.platform !== "win32")("keeps a FIFO lock path unsafe", () => { + const { evidence, lock } = fixture(); + expect(spawnSync("mkfifo", [lock]).status).toBe(0); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + + it("keeps a lock changed during its stable read busy", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + const original = fs.fstatSync.bind(fs); + vi.spyOn(fs, "fstatSync") + .mockImplementationOnce((fd) => original(fd)) + .mockImplementationOnce((fd) => { + fs.appendFileSync(lock, " "); + return original(fd); + }); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); + }); + + it("keeps a short lock read busy", () => { + const { evidence, lock, owner } = fixture(); + const ownerBytes = Buffer.from(JSON.stringify(owner)); + fs.writeFileSync(lock, Buffer.concat([ownerBytes, Buffer.from(" invalid")]), { mode: 0o600 }); + vi.spyOn(fs, "readSync").mockImplementation((( + _fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + ) => { + ownerBytes.copy(buffer as Buffer, offset); + return ownerBytes.length; + }) as typeof fs.readSync); + + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); + }); + + it("keeps a lock replaced between descriptor and path checks unsafe", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + const original = fs.lstatSync.bind(fs); + vi.spyOn(fs, "lstatSync").mockImplementation((path) => { + fs.renameSync(lock, `${lock}.old`); + writeOwner(lock, owner); + return original(path); + }); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + + it.each([0, -1])("keeps a malformed PID %s unverified", (pid) => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, { ...owner, pid }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); + }); + + it("keeps an out-of-range PID unverified", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, { ...owner, pid: Number.MAX_SAFE_INTEGER }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); + }); + + it("does not report departure when the process probe fails without ESRCH", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + vi.spyOn(process, "kill").mockImplementation(() => { + throw Object.assign(new Error("probe failed"), { code: "EIO" }); + }); + + expect( + observeOnboardLock(lock, { + ...evidence, + processAlive: systemOnboardLockEvidence.processAlive, + }), + ).toEqual({ kind: "busy", reason: "active", owner }); + }); + + it("keeps an empty process generation unverified", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, { ...owner, processGeneration: "" }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); + }); + + it("does not consult the local PID table for a foreign owner", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + let probed = false; + const result = observeOnboardLock(lock, { + ...evidence, + hostIdentity: () => "host-b", + processAlive: () => { + probed = true; + return false; + }, + }); + expect(result).toMatchObject({ kind: "busy", reason: "foreign" }); + expect(probed).toBe(false); + }); +}); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts new file mode 100644 index 00000000000..bea81db4684 --- /dev/null +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -0,0 +1,211 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +const MAX_LOCK_BYTES = 64 * 1024; +const MAX_PROCESS_ID = 0x7fffffff; + +export interface OnboardLockOwner { + pid: number; + startedAt: string | null; + command: string | null; + processGeneration: string; + hostIdentity: string; + pidNamespaceIdentity: string; +} + +export interface OnboardLockEvidence { + hostIdentity(): string | null; + pidNamespaceIdentity(): string | null; + processGeneration(pid: number): string | null; + processAlive(pid: number): boolean; +} + +export type OnboardLockObservation = + | { kind: "absent" } + | { + kind: "stale"; + reason: "departed" | "pid-reused"; + owner: OnboardLockOwner; + } + | { + kind: "busy"; + reason: "active" | "foreign" | "unverified" | "publishing" | "unsafe"; + owner?: OnboardLockOwner; + }; + +function readTrimmed(path: string): string | null { + try { + const value = fs.readFileSync(path, "utf8").trim(); + return value || null; + } catch { + return null; + } +} + +function errnoCode(error: unknown): string | undefined { + if (!error || typeof error !== "object" || !("code" in error)) return undefined; + return typeof error.code === "string" ? error.code : undefined; +} + +function defaultProcessAlive(pid: number): boolean { + if (!Number.isSafeInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return errnoCode(error) !== "ESRCH"; + } +} + +function linuxProcessGeneration(pid: number): string | null { + try { + const stat = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf8"); + const closeParen = stat.lastIndexOf(")"); + if (closeParen < 0) return null; + const fields = stat + .slice(closeParen + 2) + .trim() + .split(/\s+/); + const startTicks = fields[19]; + if (!startTicks || !/^[0-9]+$/.test(startTicks)) return null; + const bootIdentity = + readTrimmed("/proc/sys/kernel/random/boot_id") ?? + fs + .readFileSync("/proc/stat", "utf8") + .split("\n") + .find((line) => line.startsWith("btime ")) + ?.slice("btime ".length) + .trim(); + return bootIdentity ? `linux:${bootIdentity}:${startTicks}` : null; + } catch { + return null; + } +} + +export const systemOnboardLockEvidence: OnboardLockEvidence = { + hostIdentity: () => readTrimmed("/etc/machine-id"), + pidNamespaceIdentity: () => { + try { + return fs.readlinkSync("/proc/self/ns/pid"); + } catch { + return null; + } + }, + processGeneration: (pid) => (process.platform === "linux" ? linuxProcessGeneration(pid) : null), + processAlive: defaultProcessAlive, +}; + +export function createOnboardLockOwner( + command: string | null, + evidence: OnboardLockEvidence = systemOnboardLockEvidence, +): OnboardLockOwner | null { + const hostIdentity = evidence.hostIdentity(); + const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); + const processGeneration = evidence.processGeneration(process.pid); + if (!hostIdentity || !pidNamespaceIdentity || !processGeneration) return null; + return { + pid: process.pid, + startedAt: new Date().toISOString(), + command, + processGeneration, + hostIdentity, + pidNamespaceIdentity, + }; +} + +function parseOwner(value: unknown): OnboardLockOwner | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const record = value as Record; + if ( + typeof record.pid !== "number" || + !Number.isSafeInteger(record.pid) || + record.pid <= 0 || + record.pid > MAX_PROCESS_ID || + typeof record.processGeneration !== "string" || + record.processGeneration.length === 0 || + typeof record.hostIdentity !== "string" || + typeof record.pidNamespaceIdentity !== "string" + ) { + return null; + } + return { + pid: record.pid as number, + startedAt: typeof record.startedAt === "string" ? record.startedAt : null, + command: typeof record.command === "string" ? record.command : null, + processGeneration: record.processGeneration, + hostIdentity: record.hostIdentity, + pidNamespaceIdentity: record.pidNamespaceIdentity, + }; +} + +export function observeOnboardLock( + lockPath: string, + evidence: OnboardLockEvidence = systemOnboardLockEvidence, +): OnboardLockObservation { + let fd: number; + try { + fd = fs.openSync( + lockPath, + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), + ); + } catch (error) { + if (errnoCode(error) === "ENOENT") return { kind: "absent" }; + return { kind: "busy", reason: "unsafe" }; + } + + try { + const before = fs.fstatSync(fd); + const pathStat = fs.lstatSync(lockPath); + if ( + !before.isFile() || + before.nlink !== 1 || + before.size > MAX_LOCK_BYTES || + pathStat.isSymbolicLink() || + !pathStat.isFile() || + pathStat.nlink !== 1 || + pathStat.dev !== before.dev || + pathStat.ino !== before.ino + ) { + return { kind: "busy", reason: "unsafe" }; + } + const bytes = Buffer.alloc(Math.min(MAX_LOCK_BYTES + 1, before.size + 1)); + const length = fs.readSync(fd, bytes, 0, bytes.length, 0); + const after = fs.fstatSync(fd); + if ( + length > MAX_LOCK_BYTES || + length !== before.size || + before.dev !== after.dev || + before.ino !== after.ino || + before.size !== after.size || + before.mtimeMs !== after.mtimeMs || + before.ctimeMs !== after.ctimeMs + ) { + return { kind: "busy", reason: "publishing" }; + } + const owner = parseOwner(JSON.parse(bytes.subarray(0, length).toString("utf8"))); + if (!owner) return { kind: "busy", reason: "unverified" }; + + const hostIdentity = evidence.hostIdentity(); + const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); + if (!hostIdentity || !pidNamespaceIdentity) + return { kind: "busy", reason: "unverified", owner }; + if ( + owner.hostIdentity !== hostIdentity || + owner.pidNamespaceIdentity !== pidNamespaceIdentity + ) { + return { kind: "busy", reason: "foreign", owner }; + } + if (!evidence.processAlive(owner.pid)) return { kind: "stale", reason: "departed", owner }; + const generation = evidence.processGeneration(owner.pid); + if (!generation) return { kind: "busy", reason: "unverified", owner }; + if (generation !== owner.processGeneration) + return { kind: "stale", reason: "pid-reused", owner }; + return { kind: "busy", reason: "active", owner }; + } catch { + return { kind: "busy", reason: "unverified" }; + } finally { + fs.closeSync(fd); + } +} From 7f1d93618827004fd2935dadef2f6a7075519b0b Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 10:14:38 -0400 Subject: [PATCH 02/12] fix(state): unify onboarding lock recovery Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 32 ++++++- src/lib/state/legacy-port-migration.ts | 28 ++++-- src/lib/state/onboard-session.test.ts | 90 ++++++++++--------- src/lib/state/onboard-session.ts | 71 +++------------ src/lib/state/onboard-session/index.ts | 11 ++- .../onboard-session/lock-observation.test.ts | 34 +++++++ .../state/onboard-session/lock-observation.ts | 54 +++-------- 7 files changed, 168 insertions(+), 152 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index d9afe334689..eec516b7f62 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -463,15 +463,39 @@ describe("legacy non-default gateway state migration", () => { fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, ); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - new RegExp( - `onboarding lock .* is unverified; confirm no NemoClaw onboarding process .* then remove only ${path.join(root(shared, selected), "onboard.lock")} and retry; migration will not remove it automatically`, - "u", - ), + `is unverified; confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${path.join(root(shared, selected), "onboard.lock")} and retry; migration will not remove it automatically`, ); expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); expect(fs.existsSync(path.join(selected, "retained-sandbox-recovery.json"))).toBe(false); }); + it.each([ + ["active", () => "finish the active onboarding run before retrying"], + ["publishing", () => "wait for the lock write to finish, then retry"], + [ + "foreign", + () => "finish or stop the onboarding run in the other host or PID namespace before retrying", + ], + [ + "unsafe", + (lockPath: string) => + `inspect ${lockPath} and replace or remove that unsafe path after confirming it is not in use, then retry; migration will not remove it automatically`, + ], + ] as const)("explains how to recover from a %s onboarding lock", (reason, recoveryFor) => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const activeLock = path.join(shared, "onboard.lock"); + const recoveryFile = path.join(shared, "retained-sandbox-recovery.json"); + recordRecovery(recoveryFile, "port-box", 9123, "d"); + const before = fs.readFileSync(recoveryFile, "utf8"); + observeOnboardLock.mockReturnValue({ kind: "busy", reason }); + + expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( + `is ${reason}; ${recoveryFor(activeLock)}`, + ); + expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); + }); + it("migrates past a proven-stale onboarding lock without removing it", () => { const home = makeHome(); const shared = path.join(home, ".nemoclaw"); diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index 22ebdc6ec31..cc30f91c86f 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -15,7 +15,10 @@ import { readGatewayRegistryFile, registryEntryGatewayPort, } from "./gateway-registry"; -import { observeOnboardLock } from "./onboard-session/lock-observation"; +import { + observeOnboardLock, + type OnboardLockObservation, +} from "./onboard-session/index"; import { listRetainedSandboxRecoveryRecords, retainedSandboxRecoveryFile, @@ -118,6 +121,24 @@ function migrationError(message: string): Error { return new Error(`Cannot safely migrate legacy NemoClaw state for this gateway port: ${message}`); } +function onboardLockRecoveryAdvice( + reason: Extract["reason"], + lockPath: string, +): string { + switch (reason) { + case "active": + return "finish the active onboarding run before retrying"; + case "publishing": + return "wait for the lock write to finish, then retry"; + case "foreign": + return "finish or stop the onboarding run in the other host or PID namespace before retrying"; + case "unsafe": + return `inspect ${lockPath} and replace or remove that unsafe path after confirming it is not in use, then retry; migration will not remove it automatically`; + case "unverified": + return `confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${lockPath} and retry; migration will not remove it automatically`; + } +} + function ensureRealDirectory(home: string, dir: string): void { assertGatewayStatePathSafe(home, dir); fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); @@ -771,10 +792,7 @@ function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]) const lock = observeOnboardLock(activeLock); if (lock.kind === "busy") { const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; - const recovery = - lock.reason === "unverified" - ? `confirm 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` - : "finish that run or verify the lock owner before retrying"; + const recovery = onboardLockRecoveryAdvice(lock.reason, activeLock); throw migrationError( `onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`, ); diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index a6704cd4f0a..eec1ecc5a89 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { makeMessagingPlan } from "../../../test/helpers/messaging-plan-fixtures"; import { decisionSelected } from "./onboard-checkpoint-decision"; +import { createOnboardLockOwner, observeOnboardLock } from "./onboard-session/lock-observation"; const require = createRequire(import.meta.url); const distPath = require.resolve("./onboard-session"); @@ -25,6 +26,12 @@ let session: OnboardSessionModule; let machineEvents: OnboardMachineEventsModule; let tmpDir: string; +function localOnboardLockOwner(command: string) { + const owner = createOnboardLockOwner(command); + if (!owner) throw new Error("Expected complete local onboarding lock evidence"); + return owner; +} + const _nullableSessionUpdateKeyAcceptsNullableFields: Record< Extract<"model" | "credentialEnv" | "webSearchConfig", NullableSessionUpdateKey>, true @@ -1080,6 +1087,16 @@ describe("onboard session", () => { const acquired = session.acquireOnboardLock("nemoclaw onboard"); expect(acquired.acquired).toBe(true); expect(fs.existsSync(session.LOCK_FILE)).toBe(true); + expect(observeOnboardLock(session.LOCK_FILE)).toMatchObject({ + kind: "busy", + reason: "active", + owner: { + pid: process.pid, + processGeneration: expect.any(String), + hostIdentity: expect.any(String), + pidNamespaceIdentity: expect.any(String), + }, + }); const secondAttempt = session.acquireOnboardLock("nemoclaw onboard --resume"); expect(secondAttempt.acquired).toBe(false); @@ -1091,13 +1108,14 @@ describe("onboard session", () => { it("replaces a stale onboard lock", () => { fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); + const departedOwner = { + ...localOnboardLockOwner("nemoclaw onboard"), + pid: 999999, + processGeneration: "departed-process-generation", + }; fs.writeFileSync( session.LOCK_FILE, - JSON.stringify({ - pid: 999999, - startedAt: "2026-03-25T00:00:00.000Z", - command: "nemoclaw onboard", - }), + JSON.stringify(departedOwner), { mode: 0o600 }, ); @@ -1110,46 +1128,38 @@ describe("onboard session", () => { it("replaces a stale onboard lock when the recorded PID was reused by another process", () => { fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const reusedPid = 424242; + const reusedOwner = localOnboardLockOwner("nemoclaw onboard"); fs.writeFileSync( session.LOCK_FILE, JSON.stringify({ - pid: reusedPid, - startedAt: "1970-01-01T00:20:00.000Z", - command: "nemoclaw onboard", + ...reusedOwner, + processGeneration: `${reusedOwner.processGeneration}:reused`, }), { mode: 0o600 }, ); - const killSpy = vi.spyOn(process, "kill").mockReturnValue(true); - const originalReadFileSync = fs.readFileSync; - const readSpy = vi.spyOn(fs, "readFileSync").mockImplementation(((file, options) => { - const fileName = String(file); - if (fileName === `/proc/${reusedPid}/stat`) { - const fieldsAfterComm = Array.from({ length: 50 }, (_, index) => { - if (index === 0) return "S"; - if (index === 19) return "23000"; - return "0"; - }).join(" "); - return `${reusedPid} (node) ${fieldsAfterComm}`; - } - if (fileName === "/proc/stat") { - return "cpu 1 2 3 4\nbtime 1000\n"; - } - return originalReadFileSync(file, options); - }) as typeof fs.readFileSync); + const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); + expect(acquired.acquired).toBe(true); - try { - const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); - expect(acquired.acquired).toBe(true); + const written = JSON.parse(fs.readFileSync(session.LOCK_FILE, "utf8")); + expect(written.pid).toBe(process.pid); + session.releaseOnboardLock(); + }); - const written = JSON.parse(fs.readFileSync(session.LOCK_FILE, "utf8")); - expect(written.pid).toBe(process.pid); - } finally { - readSpy.mockRestore(); - killSpy.mockRestore(); - session.releaseOnboardLock(); - } + it("preserves a foreign onboard lock whose PID is absent locally", () => { + fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); + const foreignOwner = { + ...localOnboardLockOwner("nemoclaw onboard"), + pid: 999999, + hostIdentity: "foreign-host", + }; + const before = JSON.stringify(foreignOwner); + fs.writeFileSync(session.LOCK_FILE, before, { mode: 0o600 }); + + const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); + + expect(acquired).toMatchObject({ acquired: false, stale: false, holderPid: 999999 }); + expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(before); }); it("does not unlink a fresh lock claimed by another process during a stale-cleanup race (#1281)", () => { @@ -1161,17 +1171,17 @@ describe("onboard session", () => { // 1. Lay down a stale lock from a dead PID (PID 999999 on the test box). const staleLock = JSON.stringify({ + ...localOnboardLockOwner("nemoclaw onboard"), pid: 999999, - startedAt: "2026-03-25T00:00:00.000Z", - command: "nemoclaw onboard", + processGeneration: "departed-process-generation", }); fs.writeFileSync(session.LOCK_FILE, staleLock, { mode: 0o600 }); // 2. Wrap fs.statSync so the swap happens just before stat #2: // - stat #1 (inside acquireOnboardLock): reads the stale inode // and returns it unmodified. readFileSync then reads the - // ORIGINAL stale lock (dead PID 999999), isProcessAlive - // returns false, and acquireOnboardLock enters the stale- + // ORIGINAL stale lock (dead PID 999999), the shared observer + // returns stale, and acquireOnboardLock enters the stale- // cleanup path calling unlinkIfInodeMatches. // - stat #1 (inside unlinkIfInodeMatches): BEFORE the actual // stat, swap the file for a fresh claim. stat #1 then sees diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index b4962fa7ae1..3b3e976d3b7 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -63,6 +63,7 @@ import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; import { createOnboardLockOwner, listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, + observeOnboardLock, recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, retainedSandboxRecoveryAuthorityIsCurrent, retainedSandboxRecoveryFile, @@ -1373,59 +1374,6 @@ function readLockFileSnapshot(): LockFileSnapshot { const MALFORMED_STALE_SECONDS = 30; -function isProcessAlive(pid: number): boolean { - if (!Number.isInteger(pid) || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch (error) { - return isErrnoException(error) && error.code === "EPERM"; - } -} - -function readProcProcessStartMs(pid: number): number | null { - try { - const statText = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); - const btimeLine = fs - .readFileSync("/proc/stat", "utf8") - .split("\n") - .find((line) => line.startsWith("btime ")); - const bootSeconds = btimeLine ? Number(btimeLine.trim().split(/\s+/)[1]) : NaN; - const closeParen = statText.lastIndexOf(")"); - if (!Number.isFinite(bootSeconds) || closeParen < 0) return null; - - const fieldsAfterComm = statText - .slice(closeParen + 2) - .trim() - .split(/\s+/); - const startTicks = Number(fieldsAfterComm[19]); - if (!Number.isFinite(startTicks)) return null; - - // Linux exposes /proc//stat starttime in USER_HZ ticks. 100 is the - // stable value on supported NemoClaw Linux hosts. - const clockTicksPerSecond = 100; - return (bootSeconds + startTicks / clockTicksPerSecond) * 1000; - } catch { - return null; - } -} - -function lockHolderStillMatches(lock: LockInfo): boolean { - if (!isProcessAlive(lock.pid)) return false; - if (lock.pid === process.pid) return true; - - const lockStartedMs = lock.startedAt ? Date.parse(lock.startedAt) : NaN; - if (!Number.isFinite(lockStartedMs)) return true; - - const processStartMs = readProcProcessStartMs(lock.pid); - if (processStartMs === null) return true; - - // The original lock holder must have started before it wrote the lock. If - // the currently-live PID started after the lock timestamp, the PID was reused - // and the lock is stale even though kill(pid, 0) succeeds. - return processStartMs <= lockStartedMs + 1000; -} - // File descriptor we hold across the lifetime of an acquired lock. On // release, fstat(fd).ino vs stat(path).ino confirms the on-disk path // still resolves to the file we created — closing the residual TOCTOU @@ -1549,19 +1497,24 @@ export function acquireOnboardLock(command: string | null = null): LockResult { } continue; } - if (lockHolderStillMatches(existing)) { + const observation = observeOnboardLock(LOCK_FILE); + if (observation.kind === "absent") { + continue; + } + if (observation.kind === "busy") { + const holder = observation.owner ?? existing; return { acquired: false, lockFile: LOCK_FILE, stale: false, - holderPid: existing.pid, - holderStartedAt: existing.startedAt, - holderCommand: existing.command, + holderPid: holder.pid, + holderStartedAt: holder.startedAt, + holderCommand: holder.command, }; } - // Stale: unlink ONLY if the file on disk is still the same inode - // we just read. If a concurrent process already cleaned up and + // The shared observer proved this owner stale. Unlink ONLY if the file + // on disk is still the same inode we first read. If a concurrent process already cleaned up and // claimed the lock, the inode will have changed and we'll fall // through to the next iteration where openSync(wx) will either // succeed (we win) or fail EEXIST against the new holder (and we diff --git a/src/lib/state/onboard-session/index.ts b/src/lib/state/onboard-session/index.ts index fe7ccdf32cf..8ef97387c6a 100644 --- a/src/lib/state/onboard-session/index.ts +++ b/src/lib/state/onboard-session/index.ts @@ -1,7 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -export { createOnboardLockOwner } from "./lock-observation"; +export { + createOnboardLockOwner, + observeOnboardLock, + systemOnboardLockEvidence, +} from "./lock-observation"; +export type { + OnboardLockEvidence, + OnboardLockObservation, + OnboardLockOwner, +} from "./lock-observation"; export { listRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery, diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 5b7ae8243c8..752e70bb18f 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -10,6 +10,7 @@ import { spawnSync } from "node:child_process"; import { afterEach, describe, expect, it, vi } from "vitest"; import { + createOnboardLockOwner, observeOnboardLock, systemOnboardLockEvidence, type OnboardLockEvidence, @@ -58,6 +59,39 @@ describe("onboarding lock observation", () => { expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "absent" }); }); + it("creates an owner from complete local process evidence", () => { + const { evidence } = fixture(); + expect(createOnboardLockOwner("nemoclaw onboard", evidence)).toEqual({ + pid: process.pid, + startedAt: expect.any(String), + command: "nemoclaw onboard", + processGeneration: "boot:10", + hostIdentity: "host-a", + pidNamespaceIdentity: "pid:[1]", + }); + }); + + it.each(["hostIdentity", "pidNamespaceIdentity", "processGeneration"] as const)( + "rejects missing %s evidence when creating an owner", + (missing) => { + const { evidence } = fixture(); + expect( + createOnboardLockOwner("nemoclaw onboard", { ...evidence, [missing]: () => null }), + ).toBeNull(); + }, + ); + + it("creates complete owner evidence on a host without Linux PID namespaces", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); + + expect(createOnboardLockOwner("nemoclaw onboard", systemOnboardLockEvidence)).toMatchObject({ + pid: process.pid, + processGeneration: expect.stringMatching(/^darwin:/u), + hostIdentity: expect.stringMatching(/^darwin:/u), + pidNamespaceIdentity: "darwin:host-pid-namespace", + }); + }); + it("reports only proven-local departed and reused owners as stale", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index bea81db4684..5d7f079ccca 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -3,6 +3,12 @@ import fs from "node:fs"; +import { + readMcpLockHostIdentity, + readMcpLockPidNamespaceIdentity, + readMcpLockProcessIdentity, +} from "../mcp-lifecycle-lock-identity"; + const MAX_LOCK_BYTES = 64 * 1024; const MAX_PROCESS_ID = 0x7fffffff; @@ -35,15 +41,6 @@ export type OnboardLockObservation = owner?: OnboardLockOwner; }; -function readTrimmed(path: string): string | null { - try { - const value = fs.readFileSync(path, "utf8").trim(); - return value || null; - } catch { - return null; - } -} - function errnoCode(error: unknown): string | undefined { if (!error || typeof error !== "object" || !("code" in error)) return undefined; return typeof error.code === "string" ? error.code : undefined; @@ -59,41 +56,12 @@ function defaultProcessAlive(pid: number): boolean { } } -function linuxProcessGeneration(pid: number): string | null { - try { - const stat = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf8"); - const closeParen = stat.lastIndexOf(")"); - if (closeParen < 0) return null; - const fields = stat - .slice(closeParen + 2) - .trim() - .split(/\s+/); - const startTicks = fields[19]; - if (!startTicks || !/^[0-9]+$/.test(startTicks)) return null; - const bootIdentity = - readTrimmed("/proc/sys/kernel/random/boot_id") ?? - fs - .readFileSync("/proc/stat", "utf8") - .split("\n") - .find((line) => line.startsWith("btime ")) - ?.slice("btime ".length) - .trim(); - return bootIdentity ? `linux:${bootIdentity}:${startTicks}` : null; - } catch { - return null; - } -} - export const systemOnboardLockEvidence: OnboardLockEvidence = { - hostIdentity: () => readTrimmed("/etc/machine-id"), - pidNamespaceIdentity: () => { - try { - return fs.readlinkSync("/proc/self/ns/pid"); - } catch { - return null; - } - }, - processGeneration: (pid) => (process.platform === "linux" ? linuxProcessGeneration(pid) : null), + hostIdentity: readMcpLockHostIdentity, + pidNamespaceIdentity: () => + readMcpLockPidNamespaceIdentity() ?? + (process.platform === "linux" ? null : `${process.platform}:host-pid-namespace`), + processGeneration: (pid) => readMcpLockProcessIdentity(pid, true), processAlive: defaultProcessAlive, }; From f518a362d1d6f8b3b4f713473f3544bc53f07606 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 11:00:29 -0400 Subject: [PATCH 03/12] fix(state): require complete onboarding lock identity Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 3 +++ .../onboard-session-lock-ownership.test.ts | 18 +++++++++++++++ src/lib/state/onboard-session.test.ts | 6 +---- src/lib/state/onboard-session.ts | 23 ++++++++++--------- 4 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index eec516b7f62..0caff1c9363 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -488,12 +488,15 @@ describe("legacy non-default gateway state migration", () => { const recoveryFile = path.join(shared, "retained-sandbox-recovery.json"); recordRecovery(recoveryFile, "port-box", 9123, "d"); const before = fs.readFileSync(recoveryFile, "utf8"); + const lockBefore = `retained ${reason} lock`; + fs.writeFileSync(activeLock, lockBefore); observeOnboardLock.mockReturnValue({ kind: "busy", reason }); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( `is ${reason}; ${recoveryFor(activeLock)}`, ); expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); + expect(fs.readFileSync(activeLock, "utf8")).toBe(lockBefore); }); it("migrates past a proven-stale onboarding lock without removing it", () => { diff --git a/src/lib/state/onboard-session-lock-ownership.test.ts b/src/lib/state/onboard-session-lock-ownership.test.ts index 588b9cc4e1b..86fc79e25be 100644 --- a/src/lib/state/onboard-session-lock-ownership.test.ts +++ b/src/lib/state/onboard-session-lock-ownership.test.ts @@ -7,6 +7,8 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { OnboardLockEvidence } from "./onboard-session/lock-observation"; + type OnboardSessionModule = typeof import("./onboard-session"); let session: OnboardSessionModule; let tmpDir: string; @@ -27,6 +29,22 @@ afterEach(() => { }); describe("onboard lock ownership", () => { + it("does not create an onboard lock without complete owner evidence", () => { + const incompleteEvidence: OnboardLockEvidence = { + hostIdentity: () => "host-a", + pidNamespaceIdentity: () => "pid:[1]", + processGeneration: () => null, + processAlive: () => true, + }; + + expect(session.acquireOnboardLock("nemoclaw onboard", incompleteEvidence)).toEqual({ + acquired: false, + lockFile: session.LOCK_FILE, + stale: false, + }); + expect(fs.existsSync(session.LOCK_FILE)).toBe(false); + }); + it("reports ownership only while this process holds the acquired lock (#9833)", () => { expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); expect(session.acquireOnboardLock("nemoclaw onboard").acquired).toBe(true); diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index eec1ecc5a89..a392e3f6a79 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -1113,11 +1113,7 @@ describe("onboard session", () => { pid: 999999, processGeneration: "departed-process-generation", }; - fs.writeFileSync( - session.LOCK_FILE, - JSON.stringify(departedOwner), - { mode: 0o600 }, - ); + fs.writeFileSync(session.LOCK_FILE, JSON.stringify(departedOwner), { mode: 0o600 }); const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); expect(acquired.acquired).toBe(true); diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 3b3e976d3b7..3fe0101595b 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -68,6 +68,8 @@ import { retainedSandboxRecoveryAuthorityIsCurrent, retainedSandboxRecoveryFile, resolveRetainedSandboxRecovery as retireRetainedSandboxRecovery, + systemOnboardLockEvidence, + type OnboardLockEvidence, type RecordRetainedSandboxRecoveryInput, type RetainedSandboxRecoveryRecord, type RetainedSandboxRecoveryReason, @@ -1436,17 +1438,16 @@ export function isOnboardLockHeldByCurrentProcess(): boolean { } } -export function acquireOnboardLock(command: string | null = null): LockResult { +export function acquireOnboardLock( + command: string | null = null, + evidence: OnboardLockEvidence = systemOnboardLockEvidence, +): LockResult { ensureSessionDir(); - const payload = JSON.stringify( - createOnboardLockOwner(typeof command === "string" ? command : null) ?? { - pid: process.pid, - startedAt: new Date().toISOString(), - command: typeof command === "string" ? command : null, - }, - null, - 2, - ); + const owner = createOnboardLockOwner(typeof command === "string" ? command : null, evidence); + if (!owner) { + return { acquired: false, lockFile: LOCK_FILE, stale: false }; + } + const payload = JSON.stringify(owner, null, 2); // The retry budget here used to be 2, which is the bare minimum needed // for "see-stale → cleanup → reclaim". With the inode-verified cleanup @@ -1497,7 +1498,7 @@ export function acquireOnboardLock(command: string | null = null): LockResult { } continue; } - const observation = observeOnboardLock(LOCK_FILE); + const observation = observeOnboardLock(LOCK_FILE, evidence); if (observation.kind === "absent") { continue; } From 3e6de7d0a669e5b022d80ad63bd6de340307386f Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 11:29:40 -0400 Subject: [PATCH 04/12] fix(state): bound onboarding lock inspection --- .../onboard-session-lock-ownership.test.ts | 35 ++++++++++ src/lib/state/onboard-session.ts | 67 ++++-------------- src/lib/state/onboard-session/index.ts | 3 + .../state/onboard-session/lock-observation.ts | 68 ++++++++++++++----- 4 files changed, 105 insertions(+), 68 deletions(-) diff --git a/src/lib/state/onboard-session-lock-ownership.test.ts b/src/lib/state/onboard-session-lock-ownership.test.ts index 86fc79e25be..bf54d5fa270 100644 --- a/src/lib/state/onboard-session-lock-ownership.test.ts +++ b/src/lib/state/onboard-session-lock-ownership.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -45,6 +46,40 @@ describe("onboard lock ownership", () => { expect(fs.existsSync(session.LOCK_FILE)).toBe(false); }); + it.runIf(process.platform !== "win32")( + "refuses a FIFO lock path without blocking or replacing it", + () => { + fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); + expect(spawnSync("mkfifo", [session.LOCK_FILE]).status).toBe(0); + + expect(session.acquireOnboardLock("nemoclaw onboard")).toEqual({ + acquired: false, + lockFile: session.LOCK_FILE, + stale: false, + }); + expect(fs.lstatSync(session.LOCK_FILE).isFIFO()).toBe(true); + }, + ); + + it("refuses an oversized lock file without reading or replacing it", () => { + fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); + const contents = Buffer.alloc(64 * 1024 + 1, "x"); + fs.writeFileSync(session.LOCK_FILE, contents, { mode: 0o600 }); + + const readSpy = vi.spyOn(fs, "readSync"); + try { + expect(session.acquireOnboardLock("nemoclaw onboard")).toEqual({ + acquired: false, + lockFile: session.LOCK_FILE, + stale: false, + }); + expect(readSpy).not.toHaveBeenCalled(); + } finally { + readSpy.mockRestore(); + } + expect(fs.readFileSync(session.LOCK_FILE)).toEqual(contents); + }); + it("reports ownership only while this process holds the acquired lock (#9833)", () => { expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); expect(session.acquireOnboardLock("nemoclaw onboard").acquired).toBe(true); diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 3fe0101595b..cb9dd7abddc 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -62,8 +62,8 @@ import { import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; import { createOnboardLockOwner, + inspectOnboardLock, listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, - observeOnboardLock, recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, retainedSandboxRecoveryAuthorityIsCurrent, retainedSandboxRecoveryFile, @@ -1351,29 +1351,6 @@ function parseLockFile(contents: string): LockInfo | null { } } -interface LockFileSnapshot { - info: LockInfo | null; - inode: bigint; - mtimeMs: number; -} - -function readLockFileSnapshot(): LockFileSnapshot { - const fd = fs.openSync(LOCK_FILE, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); - try { - const stat = fs.fstatSync(fd, { bigint: true }); - if (!stat.isFile()) { - return { info: null, inode: stat.ino, mtimeMs: Number(stat.mtimeMs) }; - } - return { - info: parseLockFile(String(fs.readFileSync(fd, "utf8"))), - inode: stat.ino, - mtimeMs: Number(stat.mtimeMs), - }; - } finally { - fs.closeSync(fd); - } -} - const MALFORMED_STALE_SECONDS = 30; // File descriptor we hold across the lifetime of an acquired lock. On @@ -1470,22 +1447,17 @@ export function acquireOnboardLock( throw error; } - // Capture both the parsed lock and the inode so we can verify the - // file we're about to unlink is STILL the same stale file we read. - // Without the inode check, two concurrent processes can both read - // the same stale lock, and the slower one will unlink the fresh - // lock the faster one just claimed, breaking mutual exclusion. - // See issue #1281. - let snapshot: LockFileSnapshot; - try { - snapshot = readLockFileSnapshot(); - } catch (readError) { - if (isErrnoException(readError) && readError.code === "ENOENT") { - continue; - } - throw readError; + // Inspect through the shared bounded, nonblocking reader. The returned + // snapshot and observation describe the same verified inode, so cleanup + // never needs an independent read of an attacker-controlled path. + const inspection = inspectOnboardLock(LOCK_FILE, evidence); + const { observation, snapshot } = inspection; + if (observation.kind === "absent") continue; + if (!snapshot) { + return { acquired: false, lockFile: LOCK_FILE, stale: false }; } - const { info: existing, inode: staleInode } = snapshot; + const existing = parseLockFile(snapshot.contents); + const staleInode = snapshot.inode; if (!existing) { // Malformed lock file. If the file is very recent (<30 s), a // concurrent process may be mid-write — leave it and retry. @@ -1498,10 +1470,6 @@ export function acquireOnboardLock( } continue; } - const observation = observeOnboardLock(LOCK_FILE, evidence); - if (observation.kind === "absent") { - continue; - } if (observation.kind === "busy") { const holder = observation.owner ?? existing; return { @@ -1656,15 +1624,10 @@ export function releaseOnboardLock(): void { // 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; + const snapshot = inspectOnboardLock(LOCK_FILE).snapshot; + if (!snapshot) return; + const info = parseLockFile(snapshot.contents); + if (!info || info.pid !== process.pid) return; unlinkIfInodeMatches(LOCK_FILE, snapshot.inode); } catch { return; diff --git a/src/lib/state/onboard-session/index.ts b/src/lib/state/onboard-session/index.ts index 8ef97387c6a..067e55482d9 100644 --- a/src/lib/state/onboard-session/index.ts +++ b/src/lib/state/onboard-session/index.ts @@ -3,11 +3,14 @@ export { createOnboardLockOwner, + inspectOnboardLock, observeOnboardLock, systemOnboardLockEvidence, } from "./lock-observation"; export type { OnboardLockEvidence, + OnboardLockFileSnapshot, + OnboardLockInspection, OnboardLockObservation, OnboardLockOwner, } from "./lock-observation"; diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index 5d7f079ccca..2f0e8913fbd 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -41,6 +41,17 @@ export type OnboardLockObservation = owner?: OnboardLockOwner; }; +export interface OnboardLockFileSnapshot { + contents: string; + inode: bigint; + mtimeMs: number; +} + +export interface OnboardLockInspection { + observation: OnboardLockObservation; + snapshot?: OnboardLockFileSnapshot; +} + function errnoCode(error: unknown): string | undefined { if (!error || typeof error !== "object" || !("code" in error)) return undefined; return typeof error.code === "string" ? error.code : undefined; @@ -108,10 +119,10 @@ function parseOwner(value: unknown): OnboardLockOwner | null { }; } -export function observeOnboardLock( +export function inspectOnboardLock( lockPath: string, evidence: OnboardLockEvidence = systemOnboardLockEvidence, -): OnboardLockObservation { +): OnboardLockInspection { let fd: number; try { fd = fs.openSync( @@ -119,8 +130,8 @@ export function observeOnboardLock( fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), ); } catch (error) { - if (errnoCode(error) === "ENOENT") return { kind: "absent" }; - return { kind: "busy", reason: "unsafe" }; + if (errnoCode(error) === "ENOENT") return { observation: { kind: "absent" } }; + return { observation: { kind: "busy", reason: "unsafe" } }; } try { @@ -136,7 +147,7 @@ export function observeOnboardLock( pathStat.dev !== before.dev || pathStat.ino !== before.ino ) { - return { kind: "busy", reason: "unsafe" }; + return { observation: { kind: "busy", reason: "unsafe" } }; } const bytes = Buffer.alloc(Math.min(MAX_LOCK_BYTES + 1, before.size + 1)); const length = fs.readSync(fd, bytes, 0, bytes.length, 0); @@ -150,30 +161,55 @@ export function observeOnboardLock( before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs ) { - return { kind: "busy", reason: "publishing" }; + return { observation: { kind: "busy", reason: "publishing" } }; + } + const snapshot: OnboardLockFileSnapshot = { + contents: bytes.subarray(0, length).toString("utf8"), + inode: fs.fstatSync(fd, { bigint: true }).ino, + mtimeMs: before.mtimeMs, + }; + let value: unknown; + try { + value = JSON.parse(snapshot.contents); + } catch { + return { observation: { kind: "busy", reason: "unverified" }, snapshot }; + } + const owner = parseOwner(value); + if (!owner) { + return { observation: { kind: "busy", reason: "unverified" }, snapshot }; } - const owner = parseOwner(JSON.parse(bytes.subarray(0, length).toString("utf8"))); - if (!owner) return { kind: "busy", reason: "unverified" }; const hostIdentity = evidence.hostIdentity(); const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); if (!hostIdentity || !pidNamespaceIdentity) - return { kind: "busy", reason: "unverified", owner }; + return { observation: { kind: "busy", reason: "unverified", owner }, snapshot }; if ( owner.hostIdentity !== hostIdentity || owner.pidNamespaceIdentity !== pidNamespaceIdentity ) { - return { kind: "busy", reason: "foreign", owner }; + return { observation: { kind: "busy", reason: "foreign", owner }, snapshot }; + } + if (!evidence.processAlive(owner.pid)) { + return { observation: { kind: "stale", reason: "departed", owner }, snapshot }; } - if (!evidence.processAlive(owner.pid)) return { kind: "stale", reason: "departed", owner }; const generation = evidence.processGeneration(owner.pid); - if (!generation) return { kind: "busy", reason: "unverified", owner }; - if (generation !== owner.processGeneration) - return { kind: "stale", reason: "pid-reused", owner }; - return { kind: "busy", reason: "active", owner }; + if (!generation) { + return { observation: { kind: "busy", reason: "unverified", owner }, snapshot }; + } + if (generation !== owner.processGeneration) { + return { observation: { kind: "stale", reason: "pid-reused", owner }, snapshot }; + } + return { observation: { kind: "busy", reason: "active", owner }, snapshot }; } catch { - return { kind: "busy", reason: "unverified" }; + return { observation: { kind: "busy", reason: "unverified" } }; } finally { fs.closeSync(fd); } } + +export function observeOnboardLock( + lockPath: string, + evidence: OnboardLockEvidence = systemOnboardLockEvidence, +): OnboardLockObservation { + return inspectOnboardLock(lockPath, evidence).observation; +} From 1139fab07e05c0dfd42f8f5df14cad097e03b743 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 12:19:26 -0400 Subject: [PATCH 05/12] refactor(state): route migration through lock inspection --- src/lib/state/legacy-port-migration.test.ts | 48 +++++++++++---------- src/lib/state/legacy-port-migration.ts | 40 +++++------------ 2 files changed, 36 insertions(+), 52 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 0caff1c9363..4a3ee2ddb6e 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -7,12 +7,12 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -const { observeOnboardLock } = vi.hoisted(() => ({ - observeOnboardLock: vi.fn<(lockPath: string) => OnboardLockObservation>(() => ({ - kind: "absent", +const { inspectOnboardLock } = vi.hoisted(() => ({ + inspectOnboardLock: vi.fn<(lockPath: string) => { observation: OnboardLockObservation }>(() => ({ + observation: { kind: "absent" }, })), })); -vi.mock("./onboard-session/lock-observation", () => ({ observeOnboardLock })); +vi.mock("./onboard-session/lock-observation", () => ({ inspectOnboardLock })); import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions } from "../onboard/entry-options"; import { hasMigratableLegacySandbox, migrateLegacyPortState } from "./legacy-port-migration"; @@ -92,8 +92,8 @@ function expectRetainedNameBlocked( } afterEach(() => { - observeOnboardLock.mockReset(); - observeOnboardLock.mockReturnValue({ kind: "absent" }); + inspectOnboardLock.mockReset(); + inspectOnboardLock.mockReturnValue({ observation: { kind: "absent" } }); vi.restoreAllMocks(); for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); }); @@ -459,9 +459,11 @@ describe("legacy non-default gateway state migration", () => { fs.mkdirSync(root(shared, selected), { recursive: true }); fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); - observeOnboardLock.mockImplementation((lockPath: string): OnboardLockObservation => - fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, - ); + inspectOnboardLock.mockImplementation((lockPath: string) => ({ + observation: fs.existsSync(lockPath) + ? { kind: "busy", reason: "unverified" } + : { kind: "absent" }, + })); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( `is unverified; confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${path.join(root(shared, selected), "onboard.lock")} and retry; migration will not remove it automatically`, ); @@ -490,7 +492,7 @@ describe("legacy non-default gateway state migration", () => { const before = fs.readFileSync(recoveryFile, "utf8"); const lockBefore = `retained ${reason} lock`; fs.writeFileSync(activeLock, lockBefore); - observeOnboardLock.mockReturnValue({ kind: "busy", reason }); + inspectOnboardLock.mockReturnValue({ observation: { kind: "busy", reason } }); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( `is ${reason}; ${recoveryFor(activeLock)}`, @@ -515,16 +517,18 @@ describe("legacy non-default gateway state migration", () => { metadata: { gatewayName: "nemoclaw-9123" }, }); fs.writeFileSync(lock, "retained stale lock"); - observeOnboardLock.mockReturnValue({ - kind: "stale", - reason: "departed", - owner: { - pid: 123, - startedAt: null, - command: null, - processGeneration: "boot:10", - hostIdentity: "host-a", - pidNamespaceIdentity: "pid:[1]", + inspectOnboardLock.mockReturnValue({ + observation: { + kind: "stale", + reason: "departed", + owner: { + pid: 123, + startedAt: null, + command: null, + processGeneration: "boot:10", + hostIdentity: "host-a", + pidNamespaceIdentity: "pid:[1]", + }, }, }); @@ -545,8 +549,8 @@ describe("legacy non-default gateway state migration", () => { fs.symlinkSync(outside, selected, "dir"); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow(/symbolic link/); - expect(observeOnboardLock).toHaveBeenCalledOnce(); - expect(observeOnboardLock).toHaveBeenCalledWith(path.join(shared, "onboard.lock")); + expect(inspectOnboardLock).toHaveBeenCalledOnce(); + expect(inspectOnboardLock).toHaveBeenCalledWith(path.join(shared, "onboard.lock")); expect(fs.readFileSync(path.join(outside, "onboard.lock"), "utf8")).toBe("outside lock"); }); diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index cc30f91c86f..c4cb0927ab0 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -15,10 +15,7 @@ import { readGatewayRegistryFile, registryEntryGatewayPort, } from "./gateway-registry"; -import { - observeOnboardLock, - type OnboardLockObservation, -} from "./onboard-session/index"; +import { inspectOnboardLock, type OnboardLockObservation } from "./onboard-session/index"; import { listRetainedSandboxRecoveryRecords, retainedSandboxRecoveryFile, @@ -534,10 +531,9 @@ function readMigrationIntent(home: string, sharedRoot: string): LegacyPortMigrat } if ( selectedRecovery === null && - readRetainedRecoveryDocument( - home, - retainedSandboxRecoveryFile(sharedRoot), - )?.unresolved.some((record) => record.gatewayPort === gatewayPort) + readRetainedRecoveryDocument(home, retainedSandboxRecoveryFile(sharedRoot))?.unresolved.some( + (record) => record.gatewayPort === gatewayPort, + ) ) { throw migrationError( "published migration intent predates retained recovery partitioning; retained recovery remains safely in the shared root", @@ -681,17 +677,9 @@ function applyMigrationIntent( } if (intent.selectedRecovery && intent.remainingRecovery) { - writeJsonAtomic( - home, - retainedSandboxRecoveryFile(selectedRoot), - intent.selectedRecovery, - ); + writeJsonAtomic(home, retainedSandboxRecoveryFile(selectedRoot), intent.selectedRecovery); if (intent.remainingRecovery.unresolved.length > 0) { - writeJsonAtomic( - home, - retainedSandboxRecoveryFile(sharedRoot), - intent.remainingRecovery, - ); + writeJsonAtomic(home, retainedSandboxRecoveryFile(sharedRoot), intent.remainingRecovery); } else { removeRetainedRecoveryFile(home, retainedSandboxRecoveryFile(sharedRoot)); } @@ -789,13 +777,11 @@ function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]) for (const stateRoot of stateRoots) { const activeLock = path.join(stateRoot, "onboard.lock"); assertGatewayStatePathSafe(home, activeLock); - const lock = observeOnboardLock(activeLock); + const lock = inspectOnboardLock(activeLock).observation; if (lock.kind === "busy") { const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; const recovery = onboardLockRecoveryAdvice(lock.reason, activeLock); - throw migrationError( - `onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`, - ); + throw migrationError(`onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`); } } } @@ -913,9 +899,7 @@ export function migrateLegacyPortState( const remainingRecoveryRecords = recovery?.unresolved.filter((record) => record.gatewayPort !== gatewayPort) ?? []; const selectedRecovery = - selectedRecoveryRecords.length > 0 - ? retainedRecoveryDocument(selectedRecoveryRecords) - : null; + selectedRecoveryRecords.length > 0 ? retainedRecoveryDocument(selectedRecoveryRecords) : null; const remainingRecovery = selectedRecovery ? retainedRecoveryDocument(remainingRecoveryRecords) : null; @@ -956,11 +940,7 @@ export function migrateLegacyPortState( } } if (selectedRecovery) { - preflightMovePath( - home, - legacyRecoveryFile, - retainedSandboxRecoveryFile(selectedRoot), - ); + preflightMovePath(home, legacyRecoveryFile, retainedSandboxRecoveryFile(selectedRoot)); } registryLocks.push(acquireDirectoryLock(home, `${selectedRegistryFile}.lock`)); From 8d3ab797bd341b20c6a3976404542e34308b7d89 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 13:01:12 -0400 Subject: [PATCH 06/12] fix(state): harden onboarding lock ownership --- src/lib/state/legacy-port-migration.test.ts | 42 +++++++ .../state/mcp-lifecycle-lock-identity.test.ts | 26 +++++ src/lib/state/mcp-lifecycle-lock-identity.ts | 45 ++++++-- .../onboard-session-lock-ownership.test.ts | 106 ++++++++++++++++++ src/lib/state/onboard-session.ts | 36 +++--- .../onboard-session/lock-observation.test.ts | 23 +++- .../state/onboard-session/lock-observation.ts | 4 +- 7 files changed, 249 insertions(+), 33 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 4a3ee2ddb6e..d73c2999d85 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -537,6 +537,48 @@ describe("legacy non-default gateway state migration", () => { expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); }); + it("migrates past a persisted departed owner through the real lock observer", async () => { + const actualLockObservation = await vi.importActual< + typeof import("./onboard-session/lock-observation") + >("./onboard-session/lock-observation"); + inspectOnboardLock.mockImplementation((lockPath: string) => + actualLockObservation.inspectOnboardLock(lockPath), + ); + const hostIdentity = actualLockObservation.systemOnboardLockEvidence.hostIdentity(); + const pidNamespaceIdentity = + actualLockObservation.systemOnboardLockEvidence.pidNamespaceIdentity(); + expect(hostIdentity).not.toBeNull(); + expect(pidNamespaceIdentity).not.toBeNull(); + + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + const lock = path.join(shared, "onboard.lock"); + writeJson(path.join(shared, "sandboxes.json"), { + defaultSandbox: "port-box", + sandboxes: { + "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, + }, + }); + writeJson(path.join(shared, "onboard-session.json"), { + sandboxName: "port-box", + metadata: { gatewayName: "nemoclaw-9123" }, + }); + const lockBefore = JSON.stringify({ + pid: 2_147_483_647, + startedAt: "2026-09-09T00:00:00.000Z", + command: "departed nemoclaw onboard", + processGeneration: "departed-process-generation", + hostIdentity: hostIdentity as string, + pidNamespaceIdentity: pidNamespaceIdentity as string, + }); + fs.writeFileSync(lock, lockBefore, { mode: 0o600 }); + + expect(migrateLegacyPortState({ home, gatewayPort: 9123 }).migratedSession).toBe(true); + expect(fs.readFileSync(lock, "utf8")).toBe(lockBefore); + expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); + }); + it("refuses an onboarding lock below a symbolic-link state root", () => { const home = makeHome(); const shared = path.join(home, ".nemoclaw"); diff --git a/src/lib/state/mcp-lifecycle-lock-identity.test.ts b/src/lib/state/mcp-lifecycle-lock-identity.test.ts index d0d9de88578..b3cf9507b8c 100644 --- a/src/lib/state/mcp-lifecycle-lock-identity.test.ts +++ b/src/lib/state/mcp-lifecycle-lock-identity.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import childProcess from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -13,6 +14,7 @@ import { isMcpLifecycleLockOwner, readMcpLockHostIdentity, readMcpLockPidNamespaceIdentity, + readMcpLockStableHostIdentity, type LockObservation, type McpLifecycleLockIdentityProbes, type McpLifecycleLockOwner, @@ -95,6 +97,30 @@ function probes( } describe("MCP lifecycle lock identity properties", () => { + it("does not substitute a hostname when stable Linux host identity is unavailable", () => { + const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const readFileSync = vi.spyOn(fs, "readFileSync").mockImplementation(() => { + throw Object.assign(new Error("machine identity unavailable"), { code: "ENOENT" }); + }); + + try { + expect(readMcpLockStableHostIdentity()).toBeNull(); + } finally { + readFileSync.mockRestore(); + platform.mockRestore(); + } + }); + + it("uses the macOS platform UUID as the stable host identity", () => { + vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: '\"IOPlatformUUID\" = \"stable-platform-uuid\"\n', + } as ReturnType); + + expect(readMcpLockStableHostIdentity()).toBe("darwin:stable-platform-uuid"); + }); + it("reclaims a zombie local owner without treating its PID as live", () => { const localHostIdentity = readMcpLockHostIdentity(); const localPidNamespaceIdentity = readMcpLockPidNamespaceIdentity(); diff --git a/src/lib/state/mcp-lifecycle-lock-identity.ts b/src/lib/state/mcp-lifecycle-lock-identity.ts index 7d0d7fda9ea..547d458a4b5 100644 --- a/src/lib/state/mcp-lifecycle-lock-identity.ts +++ b/src/lib/state/mcp-lifecycle-lock-identity.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import childProcess from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import { performance } from "node:perf_hooks"; @@ -145,7 +145,7 @@ export function readMcpLockProcessIdentity(pid: number, fresh = false): string | identity = null; } } else { - const result = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { + const result = childProcess.spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", env: buildSubprocessEnv(), stdio: ["ignore", "pipe", "ignore"], @@ -159,17 +159,40 @@ export function readMcpLockProcessIdentity(pid: number, fresh = false): string | return identity; } -/** Stable enough to distinguish independent hosts sharing a state directory. */ +function readLinuxMachineIdentity(): string | null { + for (const candidate of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) { + try { + const machineId = fs.readFileSync(candidate, "utf8").trim(); + if (machineId) return `linux:${machineId}`; + } catch { + // Try the next stable machine identity source. + } + } + return null; +} + +/** Stable machine identity suitable for deciding whether local PID evidence applies. */ +export function readMcpLockStableHostIdentity(): string | null { + if (process.platform === "linux") return readLinuxMachineIdentity(); + if (process.platform === "darwin") { + const result = childProcess.spawnSync("ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], { + encoding: "utf8", + env: buildSubprocessEnv(), + stdio: ["ignore", "pipe", "ignore"], + timeout: 1_000, + }); + const platformUuid = + result.status === 0 ? /"IOPlatformUUID"\s*=\s*"([^"]+)"/u.exec(result.stdout)?.[1] : null; + return platformUuid ? `darwin:${platformUuid}` : null; + } + return null; +} + +/** Compatibility identity for the existing MCP lifecycle-lock protocol. */ export function readMcpLockHostIdentity(): string { if (process.platform === "linux") { - for (const candidate of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) { - try { - const machineId = fs.readFileSync(candidate, "utf8").trim(); - if (machineId) return `linux:${machineId}`; - } catch { - // Fall through to the hostname identity. - } - } + const machineIdentity = readLinuxMachineIdentity(); + if (machineIdentity) return machineIdentity; } return `${process.platform}:${os.hostname() || "unknown-host"}`; } diff --git a/src/lib/state/onboard-session-lock-ownership.test.ts b/src/lib/state/onboard-session-lock-ownership.test.ts index bf54d5fa270..b76d1d92c61 100644 --- a/src/lib/state/onboard-session-lock-ownership.test.ts +++ b/src/lib/state/onboard-session-lock-ownership.test.ts @@ -14,6 +14,15 @@ type OnboardSessionModule = typeof import("./onboard-session"); let session: OnboardSessionModule; let tmpDir: string; +function completeEvidence(): OnboardLockEvidence { + return { + hostIdentity: () => "host-a", + pidNamespaceIdentity: () => "pid:[1]", + processGeneration: () => "process-generation-a", + processAlive: () => true, + }; +} + beforeEach(async () => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-lock-ownership-")); vi.stubEnv("HOME", tmpDir); @@ -24,6 +33,7 @@ beforeEach(async () => { afterEach(() => { session.releaseOnboardLock(); + vi.restoreAllMocks(); vi.resetModules(); fs.rmSync(tmpDir, { recursive: true, force: true }); vi.unstubAllEnvs(); @@ -80,6 +90,85 @@ describe("onboard lock ownership", () => { expect(fs.readFileSync(session.LOCK_FILE)).toEqual(contents); }); + it("publishes the complete lock payload across short writes", () => { + const originalWriteSync = fs.writeSync.bind(fs) as typeof fs.writeSync; + const writeSync = vi + .spyOn(fs, "writeSync") + .mockImplementation((( + fd: number, + buffer: Uint8Array, + offset: number, + length: number, + position: number | null, + ) => + originalWriteSync( + fd, + buffer, + offset, + Math.min(length, 7), + position, + )) as typeof fs.writeSync); + + let writeCount = 0; + try { + expect(session.acquireOnboardLock("nemoclaw onboard", completeEvidence()).acquired).toBe( + true, + ); + writeCount = writeSync.mock.calls.length; + } finally { + writeSync.mockRestore(); + } + + expect(writeCount).toBeGreaterThan(1); + expect(JSON.parse(fs.readFileSync(session.LOCK_FILE, "utf8"))).toMatchObject({ + pid: process.pid, + command: "nemoclaw onboard", + hostIdentity: "host-a", + }); + }); + + it("rejects a zero-progress lock write and removes only that attempt", () => { + const writeSync = vi + .spyOn(fs, "writeSync") + .mockImplementation((() => 0) as typeof fs.writeSync); + + try { + expect(() => session.acquireOnboardLock("nemoclaw onboard", completeEvidence())).toThrow( + "write made no progress", + ); + } finally { + writeSync.mockRestore(); + } + + expect(fs.existsSync(session.LOCK_FILE)).toBe(false); + expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); + }); + + it.runIf(process.platform !== "win32")( + "preserves a replacement raced into place after a failed lock write", + () => { + fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); + const replacement = `${session.LOCK_FILE}.replacement`; + const replacementContents = "replacement lock"; + fs.writeFileSync(replacement, replacementContents, { mode: 0o600 }); + const writeSync = vi.spyOn(fs, "writeSync").mockImplementation((() => { + fs.renameSync(replacement, session.LOCK_FILE); + return 0; + }) as typeof fs.writeSync); + + try { + expect(() => session.acquireOnboardLock("nemoclaw onboard", completeEvidence())).toThrow( + "write made no progress", + ); + } finally { + writeSync.mockRestore(); + } + + expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(replacementContents); + expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); + }, + ); + it("reports ownership only while this process holds the acquired lock (#9833)", () => { expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); expect(session.acquireOnboardLock("nemoclaw onboard").acquired).toBe(true); @@ -113,4 +202,21 @@ describe("onboard lock ownership", () => { command: "replacement owner", }); }); + + it("does not release a foreign lock with the local PID without an acquired descriptor", () => { + fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); + const contents = JSON.stringify({ + pid: process.pid, + startedAt: new Date().toISOString(), + command: "foreign owner", + processGeneration: "foreign-process-generation", + hostIdentity: "foreign-host", + pidNamespaceIdentity: "foreign-pid-namespace", + }); + fs.writeFileSync(session.LOCK_FILE, contents, { mode: 0o600 }); + + session.releaseOnboardLock(); + + expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(contents); + }); }); diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index cb9dd7abddc..84cd0ad7270 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -1495,19 +1495,27 @@ export function acquireOnboardLock( // Atomic create succeeded — write the payload and keep the fd open // for the lifetime of the lock so releaseOnboardLock() can verify // ownership via the live descriptor. + let createdInode: bigint | null = null; try { - fs.writeSync(fd, payload); + createdInode = fs.fstatSync(fd, { bigint: true }).ino; + const bytes = Buffer.from(payload); + let offset = 0; + while (offset < bytes.length) { + const written = fs.writeSync(fd, bytes, offset, bytes.length - offset, offset); + if (written <= 0) { + throw new Error( + "Could not publish the onboarding lock because the write made no progress.", + ); + } + offset += written; + } } catch (writeError) { try { fs.closeSync(fd); } catch { /* ignore */ } - try { - fs.unlinkSync(LOCK_FILE); - } catch { - /* ignore */ - } + unlinkIfInodeMatches(LOCK_FILE, createdInode); throw writeError; } heldLockFd = fd; @@ -1619,19 +1627,9 @@ 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 { - const snapshot = inspectOnboardLock(LOCK_FILE).snapshot; - if (!snapshot) return; - const info = parseLockFile(snapshot.contents); - if (!info || info.pid !== process.pid) return; - unlinkIfInodeMatches(LOCK_FILE, snapshot.inode); - } catch { - return; - } + // Without the live descriptor retained by a successful acquisition there + // is no release authority. A PID match alone is not sufficient across hosts + // or PID namespaces that share a state root. } // ── Step management ────────────────────────────────────────────── diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 752e70bb18f..8409574be9c 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -82,9 +82,15 @@ describe("onboarding lock observation", () => { ); it("creates complete owner evidence on a host without Linux PID namespaces", () => { + const evidence: OnboardLockEvidence = { + hostIdentity: () => "darwin:stable-platform-uuid", + pidNamespaceIdentity: systemOnboardLockEvidence.pidNamespaceIdentity, + processGeneration: () => "darwin:process-start", + processAlive: systemOnboardLockEvidence.processAlive, + }; vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - expect(createOnboardLockOwner("nemoclaw onboard", systemOnboardLockEvidence)).toMatchObject({ + expect(createOnboardLockOwner("nemoclaw onboard", evidence)).toMatchObject({ pid: process.pid, processGeneration: expect.stringMatching(/^darwin:/u), hostIdentity: expect.stringMatching(/^darwin:/u), @@ -254,4 +260,19 @@ describe("onboarding lock observation", () => { expect(result).toMatchObject({ kind: "busy", reason: "foreign" }); expect(probed).toBe(false); }); + + it("does not consult the local PID table without stable local host identity", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + const processAlive = vi.fn(() => false); + + expect( + observeOnboardLock(lock, { + ...evidence, + hostIdentity: () => null, + processAlive, + }), + ).toEqual({ kind: "busy", reason: "unverified", owner }); + expect(processAlive).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index 2f0e8913fbd..aac36d57e50 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -4,9 +4,9 @@ import fs from "node:fs"; import { - readMcpLockHostIdentity, readMcpLockPidNamespaceIdentity, readMcpLockProcessIdentity, + readMcpLockStableHostIdentity, } from "../mcp-lifecycle-lock-identity"; const MAX_LOCK_BYTES = 64 * 1024; @@ -68,7 +68,7 @@ function defaultProcessAlive(pid: number): boolean { } export const systemOnboardLockEvidence: OnboardLockEvidence = { - hostIdentity: readMcpLockHostIdentity, + hostIdentity: readMcpLockStableHostIdentity, pidNamespaceIdentity: () => readMcpLockPidNamespaceIdentity() ?? (process.platform === "linux" ? null : `${process.platform}:host-pid-namespace`), From 27a5077ee23a420a8784ff171d22597e16385b8e Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 13:25:05 -0400 Subject: [PATCH 07/12] test(state): provide stable macOS lock identity --- test/security/shellquote-sandbox.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/security/shellquote-sandbox.test.ts b/test/security/shellquote-sandbox.test.ts index a9daf75af30..ea67915a451 100644 --- a/test/security/shellquote-sandbox.test.ts +++ b/test/security/shellquote-sandbox.test.ts @@ -93,6 +93,10 @@ const createdSandbox = fixtureMocks.createCreatedSandboxFixture(); const forwardService = fixtureMocks.installForwardServiceReachabilityFixture(); const childProcess = require("node:child_process"); const { EventEmitter } = require("node:events"); +const originalSpawnSync = childProcess.spawnSync; +childProcess.spawnSync = (command, ...args) => command === "ioreg" + ? { status: 0, stdout: '"IOPlatformUUID" = "fixture-platform-uuid"\n' } + : originalSpawnSync(command, ...args); childProcess.spawn = (...args) => { if (!forwardService.recordSpawn(args)) throw new Error("unexpected spawned process"); const child = new EventEmitter(); From 045b3e1ded75753e5e7d03849b1b7c2558e57924 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 15:06:31 -0400 Subject: [PATCH 08/12] fix(onboard): release lock on handled signals --- src/lib/onboard/exit-step-failure.test.ts | 14 +- src/lib/onboard/exit-step-failure.ts | 12 +- src/lib/state/legacy-port-migration.test.ts | 178 ++--------- src/lib/state/legacy-port-migration.ts | 58 ++-- .../state/mcp-lifecycle-lock-identity.test.ts | 26 -- src/lib/state/mcp-lifecycle-lock-identity.ts | 45 +-- .../onboard-session-lock-ownership.test.ts | 159 ---------- src/lib/state/onboard-session.test.ts | 108 +++---- src/lib/state/onboard-session.ts | 164 ++++++++--- src/lib/state/onboard-session/index.ts | 29 -- .../onboard-session/lock-observation.test.ts | 278 ------------------ .../state/onboard-session/lock-observation.ts | 215 -------------- test/security/shellquote-sandbox.test.ts | 4 - 13 files changed, 250 insertions(+), 1040 deletions(-) delete mode 100644 src/lib/state/onboard-session/index.ts delete mode 100644 src/lib/state/onboard-session/lock-observation.test.ts delete mode 100644 src/lib/state/onboard-session/lock-observation.ts 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 d73c2999d85..55c72c600be 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -7,16 +7,11 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -const { inspectOnboardLock } = vi.hoisted(() => ({ - inspectOnboardLock: vi.fn<(lockPath: string) => { observation: OnboardLockObservation }>(() => ({ - observation: { kind: "absent" }, - })), -})); -vi.mock("./onboard-session/lock-observation", () => ({ inspectOnboardLock })); - -import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions } from "../onboard/entry-options"; +import { + type OnboardEntryOptionsDeps, + resolveOnboardEntryOptions, +} from "../onboard/entry-options"; import { hasMigratableLegacySandbox, migrateLegacyPortState } from "./legacy-port-migration"; -import type { OnboardLockObservation } from "./onboard-session/lock-observation"; import { listRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery, @@ -92,8 +87,6 @@ function expectRetainedNameBlocked( } afterEach(() => { - inspectOnboardLock.mockReset(); - inspectOnboardLock.mockReturnValue({ observation: { kind: "absent" } }); vi.restoreAllMocks(); for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); }); @@ -454,177 +447,48 @@ 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"); - inspectOnboardLock.mockImplementation((lockPath: string) => ({ - observation: fs.existsSync(lockPath) - ? { kind: "busy", reason: "unverified" } - : { kind: "absent" }, - })); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - `is unverified; confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${path.join(root(shared, selected), "onboard.lock")} and retry; migration will not remove it automatically`, + `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); }); - it.each([ - ["active", () => "finish the active onboarding run before retrying"], - ["publishing", () => "wait for the lock write to finish, then retry"], - [ - "foreign", - () => "finish or stop the onboarding run in the other host or PID namespace before retrying", - ], - [ - "unsafe", - (lockPath: string) => - `inspect ${lockPath} and replace or remove that unsafe path after confirming it is not in use, then retry; migration will not remove it automatically`, - ], - ] as const)("explains how to recover from a %s onboarding lock", (reason, recoveryFor) => { - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const activeLock = path.join(shared, "onboard.lock"); - const recoveryFile = path.join(shared, "retained-sandbox-recovery.json"); - recordRecovery(recoveryFile, "port-box", 9123, "d"); - const before = fs.readFileSync(recoveryFile, "utf8"); - const lockBefore = `retained ${reason} lock`; - fs.writeFileSync(activeLock, lockBefore); - inspectOnboardLock.mockReturnValue({ observation: { kind: "busy", reason } }); - - expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - `is ${reason}; ${recoveryFor(activeLock)}`, - ); - expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); - expect(fs.readFileSync(activeLock, "utf8")).toBe(lockBefore); - }); - - it("migrates past a proven-stale onboarding lock without removing it", () => { + it.each( + ["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"], + )("keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { const home = makeHome(); const shared = path.join(home, ".nemoclaw"); const selected = path.join(shared, "gateways", "9123"); - const lock = path.join(shared, "onboard.lock"); writeJson(path.join(shared, "sandboxes.json"), { defaultSandbox: "port-box", sandboxes: { "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, }, }); - writeJson(path.join(shared, "onboard-session.json"), { - sandboxName: "port-box", - metadata: { gatewayName: "nemoclaw-9123" }, - }); - fs.writeFileSync(lock, "retained stale lock"); - inspectOnboardLock.mockReturnValue({ - observation: { - kind: "stale", - reason: "departed", - owner: { - pid: 123, - startedAt: null, - command: null, - processGeneration: "boot:10", - hostIdentity: "host-a", - pidNamespaceIdentity: "pid:[1]", - }, - }, - }); - - expect(migrateLegacyPortState({ home, gatewayPort: 9123 }).migratedSession).toBe(true); - expect(fs.readFileSync(lock, "utf8")).toBe("retained stale lock"); - expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); - }); - - it("migrates past a persisted departed owner through the real lock observer", async () => { - const actualLockObservation = await vi.importActual< - typeof import("./onboard-session/lock-observation") - >("./onboard-session/lock-observation"); - inspectOnboardLock.mockImplementation((lockPath: string) => - actualLockObservation.inspectOnboardLock(lockPath), - ); - const hostIdentity = actualLockObservation.systemOnboardLockEvidence.hostIdentity(); - const pidNamespaceIdentity = - actualLockObservation.systemOnboardLockEvidence.pidNamespaceIdentity(); - expect(hostIdentity).not.toBeNull(); - expect(pidNamespaceIdentity).not.toBeNull(); + writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); + fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); + fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); + fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const selected = path.join(shared, "gateways", "9123"); - const lock = path.join(shared, "onboard.lock"); - writeJson(path.join(shared, "sandboxes.json"), { - defaultSandbox: "port-box", - sandboxes: { - "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, - }, - }); - writeJson(path.join(shared, "onboard-session.json"), { - sandboxName: "port-box", - metadata: { gatewayName: "nemoclaw-9123" }, - }); - const lockBefore = JSON.stringify({ - pid: 2_147_483_647, - startedAt: "2026-09-09T00:00:00.000Z", - command: "departed nemoclaw onboard", - processGeneration: "departed-process-generation", - hostIdentity: hostIdentity as string, - pidNamespaceIdentity: pidNamespaceIdentity as string, - }); - fs.writeFileSync(lock, lockBefore, { mode: 0o600 }); + const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); - expect(migrateLegacyPortState({ home, gatewayPort: 9123 }).migratedSession).toBe(true); - expect(fs.readFileSync(lock, "utf8")).toBe(lockBefore); - expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); - }); + expect(result.warnings).toEqual([]); - it("refuses an onboarding lock below a symbolic-link state root", () => { - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const selected = path.join(shared, "gateways", "9123"); - const outside = path.join(home, "outside"); - recordRecovery(path.join(shared, "retained-sandbox-recovery.json"), "port-box", 9123, "d"); - fs.mkdirSync(path.dirname(selected), { recursive: true }); - fs.mkdirSync(outside); - fs.writeFileSync(path.join(outside, "onboard.lock"), "outside lock"); - fs.symlinkSync(outside, selected, "dir"); + expect(fs.existsSync(path.join(shared, entry))).toBe(true); + expect(fs.existsSync(path.join(selected, entry))).toBe(false); - expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow(/symbolic link/); - expect(inspectOnboardLock).toHaveBeenCalledOnce(); - expect(inspectOnboardLock).toHaveBeenCalledWith(path.join(shared, "onboard.lock")); - expect(fs.readFileSync(path.join(outside, "onboard.lock"), "utf8")).toBe("outside lock"); + expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); + expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); }); - it.each(["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"])( - "keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", - (entry) => { - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const selected = path.join(shared, "gateways", "9123"); - writeJson(path.join(shared, "sandboxes.json"), { - defaultSandbox: "port-box", - sandboxes: { - "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, - }, - }); - writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); - fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); - fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); - fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); - - const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); - - expect(result.warnings).toEqual([]); - - expect(fs.existsSync(path.join(shared, entry))).toBe(true); - expect(fs.existsSync(path.join(selected, entry))).toBe(false); - - expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); - expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); - }, - ); - it.each([8080, 9123])( "removes only generated stale migration-intent directories for gateway port %i", (gatewayPort) => { diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index c4cb0927ab0..335ef5fdfe2 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -15,7 +15,6 @@ import { readGatewayRegistryFile, registryEntryGatewayPort, } from "./gateway-registry"; -import { inspectOnboardLock, type OnboardLockObservation } from "./onboard-session/index"; import { listRetainedSandboxRecoveryRecords, retainedSandboxRecoveryFile, @@ -118,24 +117,6 @@ function migrationError(message: string): Error { return new Error(`Cannot safely migrate legacy NemoClaw state for this gateway port: ${message}`); } -function onboardLockRecoveryAdvice( - reason: Extract["reason"], - lockPath: string, -): string { - switch (reason) { - case "active": - return "finish the active onboarding run before retrying"; - case "publishing": - return "wait for the lock write to finish, then retry"; - case "foreign": - return "finish or stop the onboarding run in the other host or PID namespace before retrying"; - case "unsafe": - return `inspect ${lockPath} and replace or remove that unsafe path after confirming it is not in use, then retry; migration will not remove it automatically`; - case "unverified": - return `confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${lockPath} and retry; migration will not remove it automatically`; - } -} - function ensureRealDirectory(home: string, dir: string): void { assertGatewayStatePathSafe(home, dir); fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); @@ -531,9 +512,10 @@ function readMigrationIntent(home: string, sharedRoot: string): LegacyPortMigrat } if ( selectedRecovery === null && - readRetainedRecoveryDocument(home, retainedSandboxRecoveryFile(sharedRoot))?.unresolved.some( - (record) => record.gatewayPort === gatewayPort, - ) + readRetainedRecoveryDocument( + home, + retainedSandboxRecoveryFile(sharedRoot), + )?.unresolved.some((record) => record.gatewayPort === gatewayPort) ) { throw migrationError( "published migration intent predates retained recovery partitioning; retained recovery remains safely in the shared root", @@ -677,9 +659,17 @@ function applyMigrationIntent( } if (intent.selectedRecovery && intent.remainingRecovery) { - writeJsonAtomic(home, retainedSandboxRecoveryFile(selectedRoot), intent.selectedRecovery); + writeJsonAtomic( + home, + retainedSandboxRecoveryFile(selectedRoot), + intent.selectedRecovery, + ); if (intent.remainingRecovery.unresolved.length > 0) { - writeJsonAtomic(home, retainedSandboxRecoveryFile(sharedRoot), intent.remainingRecovery); + writeJsonAtomic( + home, + retainedSandboxRecoveryFile(sharedRoot), + intent.remainingRecovery, + ); } else { removeRetainedRecoveryFile(home, retainedSandboxRecoveryFile(sharedRoot)); } @@ -776,12 +766,10 @@ function acquireDirectoryLock(home: string, lock: string): string { function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]): void { for (const stateRoot of stateRoots) { const activeLock = path.join(stateRoot, "onboard.lock"); - assertGatewayStatePathSafe(home, activeLock); - const lock = inspectOnboardLock(activeLock).observation; - if (lock.kind === "busy") { - const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; - const recovery = onboardLockRecoveryAdvice(lock.reason, activeLock); - throw migrationError(`onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`); + if (lstatNoFollow(home, activeLock)) { + throw migrationError( + `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`, + ); } } } @@ -899,7 +887,9 @@ export function migrateLegacyPortState( const remainingRecoveryRecords = recovery?.unresolved.filter((record) => record.gatewayPort !== gatewayPort) ?? []; const selectedRecovery = - selectedRecoveryRecords.length > 0 ? retainedRecoveryDocument(selectedRecoveryRecords) : null; + selectedRecoveryRecords.length > 0 + ? retainedRecoveryDocument(selectedRecoveryRecords) + : null; const remainingRecovery = selectedRecovery ? retainedRecoveryDocument(remainingRecoveryRecords) : null; @@ -940,7 +930,11 @@ export function migrateLegacyPortState( } } if (selectedRecovery) { - preflightMovePath(home, legacyRecoveryFile, retainedSandboxRecoveryFile(selectedRoot)); + preflightMovePath( + home, + legacyRecoveryFile, + retainedSandboxRecoveryFile(selectedRoot), + ); } registryLocks.push(acquireDirectoryLock(home, `${selectedRegistryFile}.lock`)); diff --git a/src/lib/state/mcp-lifecycle-lock-identity.test.ts b/src/lib/state/mcp-lifecycle-lock-identity.test.ts index b3cf9507b8c..d0d9de88578 100644 --- a/src/lib/state/mcp-lifecycle-lock-identity.test.ts +++ b/src/lib/state/mcp-lifecycle-lock-identity.test.ts @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import childProcess from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -14,7 +13,6 @@ import { isMcpLifecycleLockOwner, readMcpLockHostIdentity, readMcpLockPidNamespaceIdentity, - readMcpLockStableHostIdentity, type LockObservation, type McpLifecycleLockIdentityProbes, type McpLifecycleLockOwner, @@ -97,30 +95,6 @@ function probes( } describe("MCP lifecycle lock identity properties", () => { - it("does not substitute a hostname when stable Linux host identity is unavailable", () => { - const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); - const readFileSync = vi.spyOn(fs, "readFileSync").mockImplementation(() => { - throw Object.assign(new Error("machine identity unavailable"), { code: "ENOENT" }); - }); - - try { - expect(readMcpLockStableHostIdentity()).toBeNull(); - } finally { - readFileSync.mockRestore(); - platform.mockRestore(); - } - }); - - it("uses the macOS platform UUID as the stable host identity", () => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - vi.spyOn(childProcess, "spawnSync").mockReturnValue({ - status: 0, - stdout: '\"IOPlatformUUID\" = \"stable-platform-uuid\"\n', - } as ReturnType); - - expect(readMcpLockStableHostIdentity()).toBe("darwin:stable-platform-uuid"); - }); - it("reclaims a zombie local owner without treating its PID as live", () => { const localHostIdentity = readMcpLockHostIdentity(); const localPidNamespaceIdentity = readMcpLockPidNamespaceIdentity(); diff --git a/src/lib/state/mcp-lifecycle-lock-identity.ts b/src/lib/state/mcp-lifecycle-lock-identity.ts index 547d458a4b5..7d0d7fda9ea 100644 --- a/src/lib/state/mcp-lifecycle-lock-identity.ts +++ b/src/lib/state/mcp-lifecycle-lock-identity.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import childProcess from "node:child_process"; +import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import { performance } from "node:perf_hooks"; @@ -145,7 +145,7 @@ export function readMcpLockProcessIdentity(pid: number, fresh = false): string | identity = null; } } else { - const result = childProcess.spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { + const result = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", env: buildSubprocessEnv(), stdio: ["ignore", "pipe", "ignore"], @@ -159,40 +159,17 @@ export function readMcpLockProcessIdentity(pid: number, fresh = false): string | return identity; } -function readLinuxMachineIdentity(): string | null { - for (const candidate of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) { - try { - const machineId = fs.readFileSync(candidate, "utf8").trim(); - if (machineId) return `linux:${machineId}`; - } catch { - // Try the next stable machine identity source. - } - } - return null; -} - -/** Stable machine identity suitable for deciding whether local PID evidence applies. */ -export function readMcpLockStableHostIdentity(): string | null { - if (process.platform === "linux") return readLinuxMachineIdentity(); - if (process.platform === "darwin") { - const result = childProcess.spawnSync("ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], { - encoding: "utf8", - env: buildSubprocessEnv(), - stdio: ["ignore", "pipe", "ignore"], - timeout: 1_000, - }); - const platformUuid = - result.status === 0 ? /"IOPlatformUUID"\s*=\s*"([^"]+)"/u.exec(result.stdout)?.[1] : null; - return platformUuid ? `darwin:${platformUuid}` : null; - } - return null; -} - -/** Compatibility identity for the existing MCP lifecycle-lock protocol. */ +/** Stable enough to distinguish independent hosts sharing a state directory. */ export function readMcpLockHostIdentity(): string { if (process.platform === "linux") { - const machineIdentity = readLinuxMachineIdentity(); - if (machineIdentity) return machineIdentity; + for (const candidate of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) { + try { + const machineId = fs.readFileSync(candidate, "utf8").trim(); + if (machineId) return `linux:${machineId}`; + } catch { + // Fall through to the hostname identity. + } + } } return `${process.platform}:${os.hostname() || "unknown-host"}`; } diff --git a/src/lib/state/onboard-session-lock-ownership.test.ts b/src/lib/state/onboard-session-lock-ownership.test.ts index b76d1d92c61..588b9cc4e1b 100644 --- a/src/lib/state/onboard-session-lock-ownership.test.ts +++ b/src/lib/state/onboard-session-lock-ownership.test.ts @@ -1,28 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { OnboardLockEvidence } from "./onboard-session/lock-observation"; - type OnboardSessionModule = typeof import("./onboard-session"); let session: OnboardSessionModule; let tmpDir: string; -function completeEvidence(): OnboardLockEvidence { - return { - hostIdentity: () => "host-a", - pidNamespaceIdentity: () => "pid:[1]", - processGeneration: () => "process-generation-a", - processAlive: () => true, - }; -} - beforeEach(async () => { tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-lock-ownership-")); vi.stubEnv("HOME", tmpDir); @@ -33,142 +21,12 @@ beforeEach(async () => { afterEach(() => { session.releaseOnboardLock(); - vi.restoreAllMocks(); vi.resetModules(); fs.rmSync(tmpDir, { recursive: true, force: true }); vi.unstubAllEnvs(); }); describe("onboard lock ownership", () => { - it("does not create an onboard lock without complete owner evidence", () => { - const incompleteEvidence: OnboardLockEvidence = { - hostIdentity: () => "host-a", - pidNamespaceIdentity: () => "pid:[1]", - processGeneration: () => null, - processAlive: () => true, - }; - - expect(session.acquireOnboardLock("nemoclaw onboard", incompleteEvidence)).toEqual({ - acquired: false, - lockFile: session.LOCK_FILE, - stale: false, - }); - expect(fs.existsSync(session.LOCK_FILE)).toBe(false); - }); - - it.runIf(process.platform !== "win32")( - "refuses a FIFO lock path without blocking or replacing it", - () => { - fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - expect(spawnSync("mkfifo", [session.LOCK_FILE]).status).toBe(0); - - expect(session.acquireOnboardLock("nemoclaw onboard")).toEqual({ - acquired: false, - lockFile: session.LOCK_FILE, - stale: false, - }); - expect(fs.lstatSync(session.LOCK_FILE).isFIFO()).toBe(true); - }, - ); - - it("refuses an oversized lock file without reading or replacing it", () => { - fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const contents = Buffer.alloc(64 * 1024 + 1, "x"); - fs.writeFileSync(session.LOCK_FILE, contents, { mode: 0o600 }); - - const readSpy = vi.spyOn(fs, "readSync"); - try { - expect(session.acquireOnboardLock("nemoclaw onboard")).toEqual({ - acquired: false, - lockFile: session.LOCK_FILE, - stale: false, - }); - expect(readSpy).not.toHaveBeenCalled(); - } finally { - readSpy.mockRestore(); - } - expect(fs.readFileSync(session.LOCK_FILE)).toEqual(contents); - }); - - it("publishes the complete lock payload across short writes", () => { - const originalWriteSync = fs.writeSync.bind(fs) as typeof fs.writeSync; - const writeSync = vi - .spyOn(fs, "writeSync") - .mockImplementation((( - fd: number, - buffer: Uint8Array, - offset: number, - length: number, - position: number | null, - ) => - originalWriteSync( - fd, - buffer, - offset, - Math.min(length, 7), - position, - )) as typeof fs.writeSync); - - let writeCount = 0; - try { - expect(session.acquireOnboardLock("nemoclaw onboard", completeEvidence()).acquired).toBe( - true, - ); - writeCount = writeSync.mock.calls.length; - } finally { - writeSync.mockRestore(); - } - - expect(writeCount).toBeGreaterThan(1); - expect(JSON.parse(fs.readFileSync(session.LOCK_FILE, "utf8"))).toMatchObject({ - pid: process.pid, - command: "nemoclaw onboard", - hostIdentity: "host-a", - }); - }); - - it("rejects a zero-progress lock write and removes only that attempt", () => { - const writeSync = vi - .spyOn(fs, "writeSync") - .mockImplementation((() => 0) as typeof fs.writeSync); - - try { - expect(() => session.acquireOnboardLock("nemoclaw onboard", completeEvidence())).toThrow( - "write made no progress", - ); - } finally { - writeSync.mockRestore(); - } - - expect(fs.existsSync(session.LOCK_FILE)).toBe(false); - expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); - }); - - it.runIf(process.platform !== "win32")( - "preserves a replacement raced into place after a failed lock write", - () => { - fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const replacement = `${session.LOCK_FILE}.replacement`; - const replacementContents = "replacement lock"; - fs.writeFileSync(replacement, replacementContents, { mode: 0o600 }); - const writeSync = vi.spyOn(fs, "writeSync").mockImplementation((() => { - fs.renameSync(replacement, session.LOCK_FILE); - return 0; - }) as typeof fs.writeSync); - - try { - expect(() => session.acquireOnboardLock("nemoclaw onboard", completeEvidence())).toThrow( - "write made no progress", - ); - } finally { - writeSync.mockRestore(); - } - - expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(replacementContents); - expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); - }, - ); - it("reports ownership only while this process holds the acquired lock (#9833)", () => { expect(session.isOnboardLockHeldByCurrentProcess()).toBe(false); expect(session.acquireOnboardLock("nemoclaw onboard").acquired).toBe(true); @@ -202,21 +60,4 @@ describe("onboard lock ownership", () => { command: "replacement owner", }); }); - - it("does not release a foreign lock with the local PID without an acquired descriptor", () => { - fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const contents = JSON.stringify({ - pid: process.pid, - startedAt: new Date().toISOString(), - command: "foreign owner", - processGeneration: "foreign-process-generation", - hostIdentity: "foreign-host", - pidNamespaceIdentity: "foreign-pid-namespace", - }); - fs.writeFileSync(session.LOCK_FILE, contents, { mode: 0o600 }); - - session.releaseOnboardLock(); - - expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(contents); - }); }); diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index a392e3f6a79..3c622ec1071 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -10,7 +10,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { makeMessagingPlan } from "../../../test/helpers/messaging-plan-fixtures"; import { decisionSelected } from "./onboard-checkpoint-decision"; -import { createOnboardLockOwner, observeOnboardLock } from "./onboard-session/lock-observation"; const require = createRequire(import.meta.url); const distPath = require.resolve("./onboard-session"); @@ -26,12 +25,6 @@ let session: OnboardSessionModule; let machineEvents: OnboardMachineEventsModule; let tmpDir: string; -function localOnboardLockOwner(command: string) { - const owner = createOnboardLockOwner(command); - if (!owner) throw new Error("Expected complete local onboarding lock evidence"); - return owner; -} - const _nullableSessionUpdateKeyAcceptsNullableFields: Record< Extract<"model" | "credentialEnv" | "webSearchConfig", NullableSessionUpdateKey>, true @@ -1087,16 +1080,6 @@ describe("onboard session", () => { const acquired = session.acquireOnboardLock("nemoclaw onboard"); expect(acquired.acquired).toBe(true); expect(fs.existsSync(session.LOCK_FILE)).toBe(true); - expect(observeOnboardLock(session.LOCK_FILE)).toMatchObject({ - kind: "busy", - reason: "active", - owner: { - pid: process.pid, - processGeneration: expect.any(String), - hostIdentity: expect.any(String), - pidNamespaceIdentity: expect.any(String), - }, - }); const secondAttempt = session.acquireOnboardLock("nemoclaw onboard --resume"); expect(secondAttempt.acquired).toBe(false); @@ -1108,12 +1091,15 @@ describe("onboard session", () => { it("replaces a stale onboard lock", () => { fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const departedOwner = { - ...localOnboardLockOwner("nemoclaw onboard"), - pid: 999999, - processGeneration: "departed-process-generation", - }; - fs.writeFileSync(session.LOCK_FILE, JSON.stringify(departedOwner), { mode: 0o600 }); + fs.writeFileSync( + session.LOCK_FILE, + JSON.stringify({ + pid: 999999, + startedAt: "2026-03-25T00:00:00.000Z", + command: "nemoclaw onboard", + }), + { mode: 0o600 }, + ); const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); expect(acquired.acquired).toBe(true); @@ -1124,38 +1110,46 @@ describe("onboard session", () => { it("replaces a stale onboard lock when the recorded PID was reused by another process", () => { fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const reusedOwner = localOnboardLockOwner("nemoclaw onboard"); + const reusedPid = 424242; fs.writeFileSync( session.LOCK_FILE, JSON.stringify({ - ...reusedOwner, - processGeneration: `${reusedOwner.processGeneration}:reused`, + pid: reusedPid, + startedAt: "1970-01-01T00:20:00.000Z", + command: "nemoclaw onboard", }), { mode: 0o600 }, ); - const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); - expect(acquired.acquired).toBe(true); - - const written = JSON.parse(fs.readFileSync(session.LOCK_FILE, "utf8")); - expect(written.pid).toBe(process.pid); - session.releaseOnboardLock(); - }); - - it("preserves a foreign onboard lock whose PID is absent locally", () => { - fs.mkdirSync(path.dirname(session.LOCK_FILE), { recursive: true }); - const foreignOwner = { - ...localOnboardLockOwner("nemoclaw onboard"), - pid: 999999, - hostIdentity: "foreign-host", - }; - const before = JSON.stringify(foreignOwner); - fs.writeFileSync(session.LOCK_FILE, before, { mode: 0o600 }); + const killSpy = vi.spyOn(process, "kill").mockReturnValue(true); + const originalReadFileSync = fs.readFileSync; + const readSpy = vi.spyOn(fs, "readFileSync").mockImplementation(((file, options) => { + const fileName = String(file); + if (fileName === `/proc/${reusedPid}/stat`) { + const fieldsAfterComm = Array.from({ length: 50 }, (_, index) => { + if (index === 0) return "S"; + if (index === 19) return "23000"; + return "0"; + }).join(" "); + return `${reusedPid} (node) ${fieldsAfterComm}`; + } + if (fileName === "/proc/stat") { + return "cpu 1 2 3 4\nbtime 1000\n"; + } + return originalReadFileSync(file, options); + }) as typeof fs.readFileSync); - const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); + try { + const acquired = session.acquireOnboardLock("nemoclaw onboard --resume"); + expect(acquired.acquired).toBe(true); - expect(acquired).toMatchObject({ acquired: false, stale: false, holderPid: 999999 }); - expect(fs.readFileSync(session.LOCK_FILE, "utf8")).toBe(before); + const written = JSON.parse(fs.readFileSync(session.LOCK_FILE, "utf8")); + expect(written.pid).toBe(process.pid); + } finally { + readSpy.mockRestore(); + killSpy.mockRestore(); + session.releaseOnboardLock(); + } }); it("does not unlink a fresh lock claimed by another process during a stale-cleanup race (#1281)", () => { @@ -1167,17 +1161,17 @@ describe("onboard session", () => { // 1. Lay down a stale lock from a dead PID (PID 999999 on the test box). const staleLock = JSON.stringify({ - ...localOnboardLockOwner("nemoclaw onboard"), pid: 999999, - processGeneration: "departed-process-generation", + startedAt: "2026-03-25T00:00:00.000Z", + command: "nemoclaw onboard", }); fs.writeFileSync(session.LOCK_FILE, staleLock, { mode: 0o600 }); // 2. Wrap fs.statSync so the swap happens just before stat #2: // - stat #1 (inside acquireOnboardLock): reads the stale inode // and returns it unmodified. readFileSync then reads the - // ORIGINAL stale lock (dead PID 999999), the shared observer - // returns stale, and acquireOnboardLock enters the stale- + // ORIGINAL stale lock (dead PID 999999), isProcessAlive + // returns false, and acquireOnboardLock enters the stale- // cleanup path calling unlinkIfInodeMatches. // - stat #1 (inside unlinkIfInodeMatches): BEFORE the actual // stat, swap the file for a fresh claim. stat #1 then sees @@ -1303,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 84cd0ad7270..0d17065d3db 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -61,20 +61,16 @@ import { } from "./onboard-session-tool-disclosure"; import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; import { - createOnboardLockOwner, - inspectOnboardLock, listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, retainedSandboxRecoveryAuthorityIsCurrent, retainedSandboxRecoveryFile, resolveRetainedSandboxRecovery as retireRetainedSandboxRecovery, - systemOnboardLockEvidence, - type OnboardLockEvidence, type RecordRetainedSandboxRecoveryInput, type RetainedSandboxRecoveryRecord, type RetainedSandboxRecoveryReason, validSafeEvidence, -} from "./onboard-session/index"; +} from "./onboard-session/retained-sandbox-recovery"; import type { SandboxEntry, SandboxHostMount } from "./registry/types"; import { hasUnsafeHostMountTerminalText } from "./registry/host-mount"; import { nemoclawStateRoot } from "./state-root"; @@ -1351,8 +1347,84 @@ function parseLockFile(contents: string): LockInfo | null { } } +interface LockFileSnapshot { + info: LockInfo | null; + inode: bigint; + mtimeMs: number; +} + +function readLockFileSnapshot(): LockFileSnapshot { + const fd = fs.openSync(LOCK_FILE, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); + try { + const stat = fs.fstatSync(fd, { bigint: true }); + if (!stat.isFile()) { + return { info: null, inode: stat.ino, mtimeMs: Number(stat.mtimeMs) }; + } + return { + info: parseLockFile(String(fs.readFileSync(fd, "utf8"))), + inode: stat.ino, + mtimeMs: Number(stat.mtimeMs), + }; + } finally { + fs.closeSync(fd); + } +} + const MALFORMED_STALE_SECONDS = 30; +function isProcessAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return isErrnoException(error) && error.code === "EPERM"; + } +} + +function readProcProcessStartMs(pid: number): number | null { + try { + const statText = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); + const btimeLine = fs + .readFileSync("/proc/stat", "utf8") + .split("\n") + .find((line) => line.startsWith("btime ")); + const bootSeconds = btimeLine ? Number(btimeLine.trim().split(/\s+/)[1]) : NaN; + const closeParen = statText.lastIndexOf(")"); + if (!Number.isFinite(bootSeconds) || closeParen < 0) return null; + + const fieldsAfterComm = statText + .slice(closeParen + 2) + .trim() + .split(/\s+/); + const startTicks = Number(fieldsAfterComm[19]); + if (!Number.isFinite(startTicks)) return null; + + // Linux exposes /proc//stat starttime in USER_HZ ticks. 100 is the + // stable value on supported NemoClaw Linux hosts. + const clockTicksPerSecond = 100; + return (bootSeconds + startTicks / clockTicksPerSecond) * 1000; + } catch { + return null; + } +} + +function lockHolderStillMatches(lock: LockInfo): boolean { + if (!isProcessAlive(lock.pid)) return false; + if (lock.pid === process.pid) return true; + + const lockStartedMs = lock.startedAt ? Date.parse(lock.startedAt) : NaN; + if (!Number.isFinite(lockStartedMs)) return true; + + const processStartMs = readProcProcessStartMs(lock.pid); + if (processStartMs === null) return true; + + // The original lock holder must have started before it wrote the lock. If + // the currently-live PID started after the lock timestamp, the PID was reused + // and the lock is stale even though kill(pid, 0) succeeds. + return processStartMs <= lockStartedMs + 1000; +} + // File descriptor we hold across the lifetime of an acquired lock. On // release, fstat(fd).ino vs stat(path).ino confirms the on-disk path // still resolves to the file we created — closing the residual TOCTOU @@ -1415,16 +1487,17 @@ export function isOnboardLockHeldByCurrentProcess(): boolean { } } -export function acquireOnboardLock( - command: string | null = null, - evidence: OnboardLockEvidence = systemOnboardLockEvidence, -): LockResult { +export function acquireOnboardLock(command: string | null = null): LockResult { ensureSessionDir(); - const owner = createOnboardLockOwner(typeof command === "string" ? command : null, evidence); - if (!owner) { - return { acquired: false, lockFile: LOCK_FILE, stale: false }; - } - const payload = JSON.stringify(owner, null, 2); + const payload = JSON.stringify( + { + pid: process.pid, + startedAt: new Date().toISOString(), + command: typeof command === "string" ? command : null, + }, + null, + 2, + ); // The retry budget here used to be 2, which is the bare minimum needed // for "see-stale → cleanup → reclaim". With the inode-verified cleanup @@ -1447,17 +1520,22 @@ export function acquireOnboardLock( throw error; } - // Inspect through the shared bounded, nonblocking reader. The returned - // snapshot and observation describe the same verified inode, so cleanup - // never needs an independent read of an attacker-controlled path. - const inspection = inspectOnboardLock(LOCK_FILE, evidence); - const { observation, snapshot } = inspection; - if (observation.kind === "absent") continue; - if (!snapshot) { - return { acquired: false, lockFile: LOCK_FILE, stale: false }; + // Capture both the parsed lock and the inode so we can verify the + // file we're about to unlink is STILL the same stale file we read. + // Without the inode check, two concurrent processes can both read + // the same stale lock, and the slower one will unlink the fresh + // lock the faster one just claimed, breaking mutual exclusion. + // See issue #1281. + let snapshot: LockFileSnapshot; + try { + snapshot = readLockFileSnapshot(); + } catch (readError) { + if (isErrnoException(readError) && readError.code === "ENOENT") { + continue; + } + throw readError; } - const existing = parseLockFile(snapshot.contents); - const staleInode = snapshot.inode; + const { info: existing, inode: staleInode } = snapshot; if (!existing) { // Malformed lock file. If the file is very recent (<30 s), a // concurrent process may be mid-write — leave it and retry. @@ -1470,20 +1548,19 @@ export function acquireOnboardLock( } continue; } - if (observation.kind === "busy") { - const holder = observation.owner ?? existing; + if (lockHolderStillMatches(existing)) { return { acquired: false, lockFile: LOCK_FILE, stale: false, - holderPid: holder.pid, - holderStartedAt: holder.startedAt, - holderCommand: holder.command, + holderPid: existing.pid, + holderStartedAt: existing.startedAt, + holderCommand: existing.command, }; } - // The shared observer proved this owner stale. Unlink ONLY if the file - // on disk is still the same inode we first read. If a concurrent process already cleaned up and + // Stale: unlink ONLY if the file on disk is still the same inode + // we just read. If a concurrent process already cleaned up and // claimed the lock, the inode will have changed and we'll fall // through to the next iteration where openSync(wx) will either // succeed (we win) or fail EEXIST against the new holder (and we @@ -1495,27 +1572,19 @@ export function acquireOnboardLock( // Atomic create succeeded — write the payload and keep the fd open // for the lifetime of the lock so releaseOnboardLock() can verify // ownership via the live descriptor. - let createdInode: bigint | null = null; try { - createdInode = fs.fstatSync(fd, { bigint: true }).ino; - const bytes = Buffer.from(payload); - let offset = 0; - while (offset < bytes.length) { - const written = fs.writeSync(fd, bytes, offset, bytes.length - offset, offset); - if (written <= 0) { - throw new Error( - "Could not publish the onboarding lock because the write made no progress.", - ); - } - offset += written; - } + fs.writeSync(fd, payload); } catch (writeError) { try { fs.closeSync(fd); } catch { /* ignore */ } - unlinkIfInodeMatches(LOCK_FILE, createdInode); + try { + fs.unlinkSync(LOCK_FILE); + } catch { + /* ignore */ + } throw writeError; } heldLockFd = fd; @@ -1627,9 +1696,8 @@ export function releaseOnboardLock(): void { return; } - // Without the live descriptor retained by a successful acquisition there - // is no release authority. A PID match alone is not sufficient across hosts - // or PID namespaces that share a state root. + // 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/src/lib/state/onboard-session/index.ts b/src/lib/state/onboard-session/index.ts deleted file mode 100644 index 067e55482d9..00000000000 --- a/src/lib/state/onboard-session/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -export { - createOnboardLockOwner, - inspectOnboardLock, - observeOnboardLock, - systemOnboardLockEvidence, -} from "./lock-observation"; -export type { - OnboardLockEvidence, - OnboardLockFileSnapshot, - OnboardLockInspection, - OnboardLockObservation, - OnboardLockOwner, -} from "./lock-observation"; -export { - listRetainedSandboxRecoveryRecords, - recordRetainedSandboxRecovery, - retainedSandboxRecoveryAuthorityIsCurrent, - retainedSandboxRecoveryFile, - resolveRetainedSandboxRecovery, - validSafeEvidence, -} from "./retained-sandbox-recovery"; -export type { - RecordRetainedSandboxRecoveryInput, - RetainedSandboxRecoveryRecord, - RetainedSandboxRecoveryReason, -} from "./retained-sandbox-recovery"; diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts deleted file mode 100644 index 8409574be9c..00000000000 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ /dev/null @@ -1,278 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { spawnSync } from "node:child_process"; - -import { afterEach, describe, expect, it, vi } from "vitest"; - -import { - createOnboardLockOwner, - observeOnboardLock, - systemOnboardLockEvidence, - type OnboardLockEvidence, - type OnboardLockOwner, -} from "./lock-observation"; - -const roots: string[] = []; - -function fixture(): { - evidence: OnboardLockEvidence; - lock: string; - owner: OnboardLockOwner; -} { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-observation-")); - roots.push(root); - const lock = path.join(root, "onboard.lock"); - const owner: OnboardLockOwner = { - pid: 123, - startedAt: "2026-09-02T00:00:00.000Z", - command: "nemoclaw onboard", - processGeneration: "boot:10", - hostIdentity: "host-a", - pidNamespaceIdentity: "pid:[1]", - }; - const evidence: OnboardLockEvidence = { - hostIdentity: () => "host-a", - pidNamespaceIdentity: () => "pid:[1]", - processGeneration: () => "boot:10", - processAlive: () => true, - }; - return { evidence, lock, owner }; -} - -function writeOwner(lock: string, owner: OnboardLockOwner): void { - fs.writeFileSync(lock, JSON.stringify(owner), { mode: 0o600 }); -} - -afterEach(() => { - vi.restoreAllMocks(); - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -describe("onboarding lock observation", () => { - it("reports a missing lock as absent", () => { - const { evidence, lock } = fixture(); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "absent" }); - }); - - it("creates an owner from complete local process evidence", () => { - const { evidence } = fixture(); - expect(createOnboardLockOwner("nemoclaw onboard", evidence)).toEqual({ - pid: process.pid, - startedAt: expect.any(String), - command: "nemoclaw onboard", - processGeneration: "boot:10", - hostIdentity: "host-a", - pidNamespaceIdentity: "pid:[1]", - }); - }); - - it.each(["hostIdentity", "pidNamespaceIdentity", "processGeneration"] as const)( - "rejects missing %s evidence when creating an owner", - (missing) => { - const { evidence } = fixture(); - expect( - createOnboardLockOwner("nemoclaw onboard", { ...evidence, [missing]: () => null }), - ).toBeNull(); - }, - ); - - it("creates complete owner evidence on a host without Linux PID namespaces", () => { - const evidence: OnboardLockEvidence = { - hostIdentity: () => "darwin:stable-platform-uuid", - pidNamespaceIdentity: systemOnboardLockEvidence.pidNamespaceIdentity, - processGeneration: () => "darwin:process-start", - processAlive: systemOnboardLockEvidence.processAlive, - }; - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - - expect(createOnboardLockOwner("nemoclaw onboard", evidence)).toMatchObject({ - pid: process.pid, - processGeneration: expect.stringMatching(/^darwin:/u), - hostIdentity: expect.stringMatching(/^darwin:/u), - pidNamespaceIdentity: "darwin:host-pid-namespace", - }); - }); - - it("reports only proven-local departed and reused owners as stale", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - expect(observeOnboardLock(lock, { ...evidence, processAlive: () => false })).toMatchObject({ - kind: "stale", - reason: "departed", - }); - expect( - observeOnboardLock(lock, { - ...evidence, - processGeneration: () => "boot:11", - }), - ).toMatchObject({ kind: "stale", reason: "pid-reused" }); - }); - - it.each([ - ["active", {}], - ["unverified", { processGeneration: () => null }], - ["foreign", { hostIdentity: () => "host-b" }], - ["foreign", { pidNamespaceIdentity: () => "pid:[2]" }], - ] as const)("keeps %s owners busy", (reason, overrides) => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - expect(observeOnboardLock(lock, { ...evidence, ...overrides })).toMatchObject({ - kind: "busy", - reason, - }); - }); - - it("keeps legacy, oversized, linked, and non-regular state busy", () => { - const { evidence, lock } = fixture(); - fs.writeFileSync(lock, JSON.stringify({ pid: 123 })); - expect(observeOnboardLock(lock, evidence)).toMatchObject({ kind: "busy" }); - fs.writeFileSync(lock, "x".repeat(64 * 1024 + 1)); - expect(observeOnboardLock(lock, evidence)).toEqual({ - kind: "busy", - reason: "unsafe", - }); - fs.rmSync(lock); - fs.mkdirSync(lock); - expect(observeOnboardLock(lock, evidence)).toEqual({ - kind: "busy", - reason: "unsafe", - }); - }); - - it("keeps symlink and hard-linked lock paths unsafe", () => { - const { evidence, lock, owner } = fixture(); - const target = `${lock}.target`; - writeOwner(target, owner); - fs.symlinkSync(target, lock); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); - - fs.rmSync(lock); - fs.linkSync(target, lock); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); - }); - - it.runIf(process.platform !== "win32")("keeps a FIFO lock path unsafe", () => { - const { evidence, lock } = fixture(); - expect(spawnSync("mkfifo", [lock]).status).toBe(0); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); - }); - - it("keeps a lock changed during its stable read busy", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - const original = fs.fstatSync.bind(fs); - vi.spyOn(fs, "fstatSync") - .mockImplementationOnce((fd) => original(fd)) - .mockImplementationOnce((fd) => { - fs.appendFileSync(lock, " "); - return original(fd); - }); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); - }); - - it("keeps a short lock read busy", () => { - const { evidence, lock, owner } = fixture(); - const ownerBytes = Buffer.from(JSON.stringify(owner)); - fs.writeFileSync(lock, Buffer.concat([ownerBytes, Buffer.from(" invalid")]), { mode: 0o600 }); - vi.spyOn(fs, "readSync").mockImplementation((( - _fd: number, - buffer: NodeJS.ArrayBufferView, - offset: number, - ) => { - ownerBytes.copy(buffer as Buffer, offset); - return ownerBytes.length; - }) as typeof fs.readSync); - - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); - }); - - it("keeps a lock replaced between descriptor and path checks unsafe", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - const original = fs.lstatSync.bind(fs); - vi.spyOn(fs, "lstatSync").mockImplementation((path) => { - fs.renameSync(lock, `${lock}.old`); - writeOwner(lock, owner); - return original(path); - }); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); - }); - - it.each([0, -1])("keeps a malformed PID %s unverified", (pid) => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, { ...owner, pid }); - expect(observeOnboardLock(lock, evidence)).toEqual({ - kind: "busy", - reason: "unverified", - }); - }); - - it("keeps an out-of-range PID unverified", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, { ...owner, pid: Number.MAX_SAFE_INTEGER }); - expect(observeOnboardLock(lock, evidence)).toEqual({ - kind: "busy", - reason: "unverified", - }); - }); - - it("does not report departure when the process probe fails without ESRCH", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - vi.spyOn(process, "kill").mockImplementation(() => { - throw Object.assign(new Error("probe failed"), { code: "EIO" }); - }); - - expect( - observeOnboardLock(lock, { - ...evidence, - processAlive: systemOnboardLockEvidence.processAlive, - }), - ).toEqual({ kind: "busy", reason: "active", owner }); - }); - - it("keeps an empty process generation unverified", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, { ...owner, processGeneration: "" }); - expect(observeOnboardLock(lock, evidence)).toEqual({ - kind: "busy", - reason: "unverified", - }); - }); - - it("does not consult the local PID table for a foreign owner", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - let probed = false; - const result = observeOnboardLock(lock, { - ...evidence, - hostIdentity: () => "host-b", - processAlive: () => { - probed = true; - return false; - }, - }); - expect(result).toMatchObject({ kind: "busy", reason: "foreign" }); - expect(probed).toBe(false); - }); - - it("does not consult the local PID table without stable local host identity", () => { - const { evidence, lock, owner } = fixture(); - writeOwner(lock, owner); - const processAlive = vi.fn(() => false); - - expect( - observeOnboardLock(lock, { - ...evidence, - hostIdentity: () => null, - processAlive, - }), - ).toEqual({ kind: "busy", reason: "unverified", owner }); - expect(processAlive).not.toHaveBeenCalled(); - }); -}); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts deleted file mode 100644 index aac36d57e50..00000000000 --- a/src/lib/state/onboard-session/lock-observation.ts +++ /dev/null @@ -1,215 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import fs from "node:fs"; - -import { - readMcpLockPidNamespaceIdentity, - readMcpLockProcessIdentity, - readMcpLockStableHostIdentity, -} from "../mcp-lifecycle-lock-identity"; - -const MAX_LOCK_BYTES = 64 * 1024; -const MAX_PROCESS_ID = 0x7fffffff; - -export interface OnboardLockOwner { - pid: number; - startedAt: string | null; - command: string | null; - processGeneration: string; - hostIdentity: string; - pidNamespaceIdentity: string; -} - -export interface OnboardLockEvidence { - hostIdentity(): string | null; - pidNamespaceIdentity(): string | null; - processGeneration(pid: number): string | null; - processAlive(pid: number): boolean; -} - -export type OnboardLockObservation = - | { kind: "absent" } - | { - kind: "stale"; - reason: "departed" | "pid-reused"; - owner: OnboardLockOwner; - } - | { - kind: "busy"; - reason: "active" | "foreign" | "unverified" | "publishing" | "unsafe"; - owner?: OnboardLockOwner; - }; - -export interface OnboardLockFileSnapshot { - contents: string; - inode: bigint; - mtimeMs: number; -} - -export interface OnboardLockInspection { - observation: OnboardLockObservation; - snapshot?: OnboardLockFileSnapshot; -} - -function errnoCode(error: unknown): string | undefined { - if (!error || typeof error !== "object" || !("code" in error)) return undefined; - return typeof error.code === "string" ? error.code : undefined; -} - -function defaultProcessAlive(pid: number): boolean { - if (!Number.isSafeInteger(pid) || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch (error) { - return errnoCode(error) !== "ESRCH"; - } -} - -export const systemOnboardLockEvidence: OnboardLockEvidence = { - hostIdentity: readMcpLockStableHostIdentity, - pidNamespaceIdentity: () => - readMcpLockPidNamespaceIdentity() ?? - (process.platform === "linux" ? null : `${process.platform}:host-pid-namespace`), - processGeneration: (pid) => readMcpLockProcessIdentity(pid, true), - processAlive: defaultProcessAlive, -}; - -export function createOnboardLockOwner( - command: string | null, - evidence: OnboardLockEvidence = systemOnboardLockEvidence, -): OnboardLockOwner | null { - const hostIdentity = evidence.hostIdentity(); - const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); - const processGeneration = evidence.processGeneration(process.pid); - if (!hostIdentity || !pidNamespaceIdentity || !processGeneration) return null; - return { - pid: process.pid, - startedAt: new Date().toISOString(), - command, - processGeneration, - hostIdentity, - pidNamespaceIdentity, - }; -} - -function parseOwner(value: unknown): OnboardLockOwner | null { - if (!value || typeof value !== "object" || Array.isArray(value)) return null; - const record = value as Record; - if ( - typeof record.pid !== "number" || - !Number.isSafeInteger(record.pid) || - record.pid <= 0 || - record.pid > MAX_PROCESS_ID || - typeof record.processGeneration !== "string" || - record.processGeneration.length === 0 || - typeof record.hostIdentity !== "string" || - typeof record.pidNamespaceIdentity !== "string" - ) { - return null; - } - return { - pid: record.pid as number, - startedAt: typeof record.startedAt === "string" ? record.startedAt : null, - command: typeof record.command === "string" ? record.command : null, - processGeneration: record.processGeneration, - hostIdentity: record.hostIdentity, - pidNamespaceIdentity: record.pidNamespaceIdentity, - }; -} - -export function inspectOnboardLock( - lockPath: string, - evidence: OnboardLockEvidence = systemOnboardLockEvidence, -): OnboardLockInspection { - let fd: number; - try { - fd = fs.openSync( - lockPath, - fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), - ); - } catch (error) { - if (errnoCode(error) === "ENOENT") return { observation: { kind: "absent" } }; - return { observation: { kind: "busy", reason: "unsafe" } }; - } - - try { - const before = fs.fstatSync(fd); - const pathStat = fs.lstatSync(lockPath); - if ( - !before.isFile() || - before.nlink !== 1 || - before.size > MAX_LOCK_BYTES || - pathStat.isSymbolicLink() || - !pathStat.isFile() || - pathStat.nlink !== 1 || - pathStat.dev !== before.dev || - pathStat.ino !== before.ino - ) { - return { observation: { kind: "busy", reason: "unsafe" } }; - } - const bytes = Buffer.alloc(Math.min(MAX_LOCK_BYTES + 1, before.size + 1)); - const length = fs.readSync(fd, bytes, 0, bytes.length, 0); - const after = fs.fstatSync(fd); - if ( - length > MAX_LOCK_BYTES || - length !== before.size || - before.dev !== after.dev || - before.ino !== after.ino || - before.size !== after.size || - before.mtimeMs !== after.mtimeMs || - before.ctimeMs !== after.ctimeMs - ) { - return { observation: { kind: "busy", reason: "publishing" } }; - } - const snapshot: OnboardLockFileSnapshot = { - contents: bytes.subarray(0, length).toString("utf8"), - inode: fs.fstatSync(fd, { bigint: true }).ino, - mtimeMs: before.mtimeMs, - }; - let value: unknown; - try { - value = JSON.parse(snapshot.contents); - } catch { - return { observation: { kind: "busy", reason: "unverified" }, snapshot }; - } - const owner = parseOwner(value); - if (!owner) { - return { observation: { kind: "busy", reason: "unverified" }, snapshot }; - } - - const hostIdentity = evidence.hostIdentity(); - const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); - if (!hostIdentity || !pidNamespaceIdentity) - return { observation: { kind: "busy", reason: "unverified", owner }, snapshot }; - if ( - owner.hostIdentity !== hostIdentity || - owner.pidNamespaceIdentity !== pidNamespaceIdentity - ) { - return { observation: { kind: "busy", reason: "foreign", owner }, snapshot }; - } - if (!evidence.processAlive(owner.pid)) { - return { observation: { kind: "stale", reason: "departed", owner }, snapshot }; - } - const generation = evidence.processGeneration(owner.pid); - if (!generation) { - return { observation: { kind: "busy", reason: "unverified", owner }, snapshot }; - } - if (generation !== owner.processGeneration) { - return { observation: { kind: "stale", reason: "pid-reused", owner }, snapshot }; - } - return { observation: { kind: "busy", reason: "active", owner }, snapshot }; - } catch { - return { observation: { kind: "busy", reason: "unverified" } }; - } finally { - fs.closeSync(fd); - } -} - -export function observeOnboardLock( - lockPath: string, - evidence: OnboardLockEvidence = systemOnboardLockEvidence, -): OnboardLockObservation { - return inspectOnboardLock(lockPath, evidence).observation; -} diff --git a/test/security/shellquote-sandbox.test.ts b/test/security/shellquote-sandbox.test.ts index ea67915a451..a9daf75af30 100644 --- a/test/security/shellquote-sandbox.test.ts +++ b/test/security/shellquote-sandbox.test.ts @@ -93,10 +93,6 @@ const createdSandbox = fixtureMocks.createCreatedSandboxFixture(); const forwardService = fixtureMocks.installForwardServiceReachabilityFixture(); const childProcess = require("node:child_process"); const { EventEmitter } = require("node:events"); -const originalSpawnSync = childProcess.spawnSync; -childProcess.spawnSync = (command, ...args) => command === "ioreg" - ? { status: 0, stdout: '"IOPlatformUUID" = "fixture-platform-uuid"\n' } - : originalSpawnSync(command, ...args); childProcess.spawn = (...args) => { if (!forwardService.recordSpawn(args)) throw new Error("unexpected spawned process"); const child = new EventEmitter(); From 1ef1148d9a54de2d702b5c09986381b831179341 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 18:18:24 -0400 Subject: [PATCH 09/12] fix(onboard): cover lock cleanup during entry setup --- src/lib/onboard.ts | 14 +-- test/onboarding/onboard-exit-handler.test.ts | 125 ++++++++++++++++++- 2 files changed, 128 insertions(+), 11 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index b1affbece07..0792b3e7633 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2675,9 +2675,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, + () => completed || preserveIncompleteSession, + ); + let preserveDeferredExitSession = false; try { await portableRetirementEntry.run(async () => { const entryOptions = resolveEntryOptions(); @@ -2799,10 +2803,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/test/onboarding/onboard-exit-handler.test.ts b/test/onboarding/onboard-exit-handler.test.ts index 0f6a1d522ed..c5b3535b93e 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"; @@ -101,6 +102,123 @@ describe("onboard exit handler registration", () => { expect(loaded.machine.state).toBe("init"); }); + it.skipIf(process.platform === "win32")( + "onboard releases its lock when signaled during entry setup and preserves a replacement lock (#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 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 }) + "\\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", +}).catch((error) => { + console.error(error && error.stack ? error.stack : String(error)); + process.exitCode = 1; +}); +`, + ); + + const run = async (replaceLock: boolean) => { + const home = path.join(tmpDir, replaceLock ? "replacement-home" : "owned-home"); + fs.mkdirSync(home); + const child = spawn( + process.execPath, + ["--require", "tsx/cjs", scriptPath, ...(replaceLock ? ["--replace-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; + }); + + try { + const ready = await new Promise((resolve, reject) => { + let stdout = ""; + 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 } = JSON.parse(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, stderr).toBeNull(); + expect(signal, stderr).toBe("SIGINT"); + expect(replaceLock ? fs.readFileSync(lockFile, "utf8") : fs.existsSync(lockFile)).toBe( + replaceLock ? replacement : false, + ); + } finally { + child.kill("SIGKILL"); + } + }; + + await run(false); + await run(true); + }, + ); + 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 +328,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 { From 8ca55bee2237444b362c115dcff032433bac3446 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 18:53:40 -0400 Subject: [PATCH 10/12] docs: document retained onboarding lock recovery --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 4 +++- docs/reference/commands.mdx | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) 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 c0cf6f18812..bceb87cd584 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3527,7 +3527,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. From 85794a4f0e82607a76b65477c372fea4e62b4bb9 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 20:32:25 -0400 Subject: [PATCH 11/12] test(onboard): budget subprocess exit coverage --- test/onboarding/onboard-exit-handler.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/onboarding/onboard-exit-handler.test.ts b/test/onboarding/onboard-exit-handler.test.ts index c5b3535b93e..9557b534de9 100644 --- a/test/onboarding/onboard-exit-handler.test.ts +++ b/test/onboarding/onboard-exit-handler.test.ts @@ -10,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: ( @@ -432,7 +434,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, "../.."); From 7963815c7e81cb7afd5ae8ef78f06af3966b4a28 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 9 Sep 2026 21:11:36 -0400 Subject: [PATCH 12/12] fix(onboard): preserve outer lifecycle lock --- src/lib/onboard.ts | 2 +- test/onboarding/onboard-exit-handler.test.ts | 84 +++++++++++++++++--- 2 files changed, 73 insertions(+), 13 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 4f9ed6eea2e..2fe87adbc3e 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2677,7 +2677,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { let completed = false; let preserveIncompleteSession = false; registerIncompleteOnboardExitHandlerForSession( - onboardSession, + { ...onboardSession, releaseOnboardLock: portableRetirementEntry.release }, () => completed || preserveIncompleteSession, ); let preserveDeferredExitSession = false; diff --git a/test/onboarding/onboard-exit-handler.test.ts b/test/onboarding/onboard-exit-handler.test.ts index 9557b534de9..6ba1ee5ae66 100644 --- a/test/onboarding/onboard-exit-handler.test.ts +++ b/test/onboarding/onboard-exit-handler.test.ts @@ -105,7 +105,7 @@ describe("onboard exit handler registration", () => { }); it.skipIf(process.platform === "win32")( - "onboard releases its lock when signaled during entry setup and preserves a replacement lock (#10779)", + "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"); @@ -126,6 +126,25 @@ 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) { @@ -133,7 +152,12 @@ const pauseDuringLockedRuntimePreparation = async () => { fs.writeFileSync(onboardSession.LOCK_FILE, ${JSON.stringify(replacement)}); } process.stdout.write( - "NEMOCLAW_SIGNAL_READY " + JSON.stringify({ lockFile: onboardSession.LOCK_FILE }) + "\\n", + "NEMOCLAW_SIGNAL_READY " + + JSON.stringify({ + lockFile: onboardSession.LOCK_FILE, + lockContents: fs.readFileSync(onboardSession.LOCK_FILE, "utf8"), + }) + + "\\n", ); await new Promise(() => {}); throw new Error("unreachable"); @@ -151,6 +175,16 @@ onboard({ 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; @@ -158,12 +192,20 @@ onboard({ `, ); - const run = async (replaceLock: boolean) => { - const home = path.join(tmpDir, replaceLock ? "replacement-home" : "owned-home"); + 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"] : [])], + [ + "--require", + "tsx/cjs", + scriptPath, + ...(replaceLock ? ["--replace-lock"] : []), + ...(outerOwnsLock ? ["--outer-lock"] : []), + ], { cwd: repoRoot, env: { @@ -181,10 +223,10 @@ onboard({ child.stderr.on("data", (chunk: string) => { stderr += chunk; }); + let stdout = ""; try { const ready = await new Promise((resolve, reject) => { - let stdout = ""; child.stdout.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { stdout += chunk; @@ -201,24 +243,42 @@ onboard({ ); }); }); - const { lockFile } = JSON.parse(ready) as { lockFile: string }; + 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"); - expect(replaceLock ? fs.readFileSync(lockFile, "utf8") : fs.existsSync(lockFile)).toBe( - replaceLock ? replacement : false, - ); + 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(false); - await run(true); + 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)", () => {