diff --git a/src/lib/inference/bedrock-runtime-adapter.test.ts b/src/lib/inference/bedrock-runtime-adapter.test.ts index 38908c684fc..bc1eb7a5087 100644 --- a/src/lib/inference/bedrock-runtime-adapter.test.ts +++ b/src/lib/inference/bedrock-runtime-adapter.test.ts @@ -5,14 +5,42 @@ import http from "node:http"; import { afterEach, describe, expect, it, vi } from "vitest"; +// Only the process- and disk-touching helpers are replaced; every pure helper this file also +// exercises keeps its real implementation. +vi.mock("./local-adapter-lifecycle", async (importOriginal) => ({ + ...(await importOriginal()), + cleanupFailedLocalAdapterStartup: vi.fn(), + killLocalAdapterPid: vi.fn(), + loadLocalAdapterPid: vi.fn(() => null), + persistLocalAdapterPid: vi.fn(), + readLocalAdapterJsonFile: vi.fn(() => null), + readLocalAdapterTextFile: vi.fn(() => null), + spawnDetachedNodeAdapter: vi.fn(() => ({ pid: 4242 })), + waitForLocalAdapterHealth: vi.fn(async () => false), +})); + import { __test, buildBedrockConverseRequest, createBedrockRuntimeAdapterServer, createOpenAiChatCompletion, + ensureBedrockRuntimeAdapter, streamOpenAiChatCompletion, } from "./bedrock-runtime-adapter"; -import { isLocalAdapterProcess } from "./local-adapter-lifecycle"; +import { + cleanupFailedLocalAdapterStartup, + isLocalAdapterProcess, + killLocalAdapterPid, + persistLocalAdapterPid, +} from "./local-adapter-lifecycle"; + +const US_EAST_1_CLASSIFICATION = { + kind: "bedrock-runtime", + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + hostname: "bedrock-runtime.us-east-1.amazonaws.com", + region: "us-east-1", + fips: false, +} as const; const servers: http.Server[] = []; @@ -383,6 +411,41 @@ describe("Bedrock Runtime OpenAI adapter", () => { expect(body.error.message).toContain("Could not load credentials"); }); + it("kills the spawned child and clears adapter state when startup never becomes healthy", async () => { + vi.mocked(killLocalAdapterPid).mockClear(); + vi.mocked(cleanupFailedLocalAdapterStartup).mockClear(); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("did not become healthy"); + + // The single direct kill is the pre-spawn one that clears any prior adapter; tearing the new + // child down is the shared cleanup's job, and it must target this adapter's own files and the + // pid of the child this call spawned. + expect(vi.mocked(killLocalAdapterPid).mock.calls).toHaveLength(1); + const [cleanup] = vi.mocked(cleanupFailedLocalAdapterStartup).mock.calls; + expect(cleanup?.[0].pidPath.endsWith("bedrock-runtime-adapter.pid")).toBe(true); + expect(cleanup?.[0].statePath.endsWith("bedrock-runtime-adapter.json")).toBe(true); + expect(cleanup?.[1]).toBe(4242); + }); + + it("hands the spawned child to cleanup when its pid file cannot be persisted", async () => { + vi.mocked(cleanupFailedLocalAdapterStartup).mockClear(); + vi.mocked(persistLocalAdapterPid).mockImplementationOnce(() => { + throw new Error("ENOSPC: no space left on device"); + }); + + await expect( + ensureBedrockRuntimeAdapter({ classification: US_EAST_1_CLASSIFICATION }), + ).rejects.toThrow("ENOSPC"); + + // The pid file the cleanup would otherwise reload was never written, so 4242 — the pid the + // mocked spawn returned — is the only remaining handle on the orphaned child. + const [cleanup] = vi.mocked(cleanupFailedLocalAdapterStartup).mock.calls; + expect(cleanup?.[0].pidPath.endsWith("bedrock-runtime-adapter.pid")).toBe(true); + expect(cleanup?.[1]).toBe(4242); + }); + it("spawns the typed .mts launcher entrypoint", () => { expect(__test.getAdapterScriptPath().endsWith("bedrock-runtime-adapter.mts")).toBe(true); }); diff --git a/src/lib/inference/bedrock-runtime-adapter.ts b/src/lib/inference/bedrock-runtime-adapter.ts index 0f751532c7f..98d2c31fedc 100644 --- a/src/lib/inference/bedrock-runtime-adapter.ts +++ b/src/lib/inference/bedrock-runtime-adapter.ts @@ -31,10 +31,12 @@ import { streamOpenAiChatCompletion, } from "./bedrock-runtime-translation"; import { + cleanupFailedLocalAdapterStartup, DEFAULT_LOCAL_ADAPTER_STATE_DIR, isLocalAdapterProcess, type JsonObject, killLocalAdapterPid, + type LocalAdapterProcessOptions, loadLocalAdapterPid, localAdapterTokenHash, persistLocalAdapterPid, @@ -286,10 +288,6 @@ export function startBedrockRuntimeAdapterFromEnv(): http.Server { return server; } -function loadPersistedPid(): number | null { - return loadLocalAdapterPid(PID_PATH); -} - const ADAPTER_LAUNCHER_BASENAMES = ["bedrock-runtime-adapter.mts", "bedrock-runtime-adapter.js"]; const ADAPTER_PROCESS_NEEDLE = new RegExp( `(?:^|[^A-Za-z0-9_.-])(?:${ADAPTER_LAUNCHER_BASENAMES.map((name) => @@ -297,18 +295,13 @@ const ADAPTER_PROCESS_NEEDLE = new RegExp( ).join("|")})(?:$|[^A-Za-z0-9_.-])`, ); -function isAdapterProcess(pid: number | null | undefined): boolean { - return isLocalAdapterProcess(pid, ADAPTER_PROCESS_NEEDLE, runCapture); -} - -function killStaleAdapter(): void { - killLocalAdapterPid({ - pidPath: PID_PATH, - processMatcher: ADAPTER_PROCESS_NEEDLE, - run, - runCapture, - }); -} +const ADAPTER_PROCESS: LocalAdapterProcessOptions & { statePath: string } = { + pidPath: PID_PATH, + statePath: STATE_PATH, + processMatcher: ADAPTER_PROCESS_NEEDLE, + run, + runCapture, +}; function getAdapterScriptPath(): string { const scriptsDir = typeof SCRIPTS === "string" ? SCRIPTS : path.join(process.cwd(), "scripts"); @@ -386,10 +379,10 @@ export async function ensureBedrockRuntimeAdapter(options: { const credentialHash = adapterCredentialHash({ endpointUrl, region, compatibleCredential }); const priorState = readLocalAdapterJsonFile(STATE_PATH); const priorToken = readLocalAdapterTextFile(TOKEN_PATH); - const priorPid = loadPersistedPid(); + const priorPid = loadLocalAdapterPid(PID_PATH); if ( priorToken && - isAdapterProcess(priorPid) && + isLocalAdapterProcess(priorPid, ADAPTER_PROCESS_NEEDLE, runCapture) && priorState?.endpointUrl === endpointUrl && priorState?.region === region && priorState?.credentialHash === credentialHash && @@ -406,7 +399,7 @@ export async function ensureBedrockRuntimeAdapter(options: { }; } - killStaleAdapter(); + killLocalAdapterPid(ADAPTER_PROCESS); const token = crypto.randomBytes(24).toString("hex"); const childEnv: Record = { NEMOCLAW_BEDROCK_RUNTIME_ENDPOINT_URL: endpointUrl, @@ -426,22 +419,27 @@ export async function ensureBedrockRuntimeAdapter(options: { env: childEnv, buildEnv: buildSubprocessEnv, }); - persistLocalAdapterPid(PID_PATH, child.pid); + try { + persistLocalAdapterPid(PID_PATH, child.pid); - if (!(await waitForAdapterHealth(token))) { - throw new Error( - `Bedrock Runtime adapter did not become healthy on ${BEDROCK_RUNTIME_ADAPTER_LOOPBACK_OPENAI_BASE_URL}`, - ); - } + if (!(await waitForAdapterHealth(token))) { + throw new Error( + `Bedrock Runtime adapter did not become healthy on ${BEDROCK_RUNTIME_ADAPTER_LOOPBACK_OPENAI_BASE_URL}`, + ); + } - writeLocalAdapterSecretFile(TOKEN_PATH, token); - writeLocalAdapterJsonFile(STATE_PATH, { - endpointUrl, - region, - credentialHash, - pid: child.pid ?? null, - updatedAt: new Date().toISOString(), - }); + writeLocalAdapterSecretFile(TOKEN_PATH, token); + writeLocalAdapterJsonFile(STATE_PATH, { + endpointUrl, + region, + credentialHash, + pid: child.pid ?? null, + updatedAt: new Date().toISOString(), + }); + } catch (err) { + cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS, child.pid); + throw err; + } process.env[BEDROCK_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV] = token; return { diff --git a/src/lib/inference/local-adapter-lifecycle.test.ts b/src/lib/inference/local-adapter-lifecycle.test.ts index 2bd00b125c1..f52e22a60ab 100644 --- a/src/lib/inference/local-adapter-lifecycle.test.ts +++ b/src/lib/inference/local-adapter-lifecycle.test.ts @@ -9,9 +9,11 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { + cleanupFailedLocalAdapterStartup, ensureLocalAdapterStateDir, isLocalAdapterProcess, killLocalAdapterPid, + type LocalAdapterProcessOptions, LOCAL_ADAPTER_HEALTH_MAX_RESPONSE_BYTES, loadLocalAdapterPid, localAdapterTokenHash, @@ -158,6 +160,34 @@ describe("local adapter lifecycle", () => { expect(loadLocalAdapterPid(pidPath)).toBeNull(); }); + it("signals the spawned child of a failed startup when its pid file was never written", () => { + const dir = tempDir(); + const statePath = path.join(dir, "adapter.json"); + const killed: string[][] = []; + const options: LocalAdapterProcessOptions & { statePath: string } = { + pidPath: path.join(dir, "adapter.pid"), + statePath, + processMatcher: isOllamaAuthProxyCommandLine, + run: (args) => { + killed.push(args); + }, + runCapture: () => "node /opt/nemoclaw/scripts/ollama-auth-proxy.mts", + }; + + // Control: with no pid file and no spawned pid there is nothing the cleanup can identify. + writeLocalAdapterJsonFile(statePath, { pid: 4242 }); + cleanupFailedLocalAdapterStartup(options); + expect(killed).toEqual([]); + expect(fs.existsSync(statePath)).toBe(false); + + // A failed persistLocalAdapterPid leaves the same empty pid path, so the caller's own handle on + // the child it just spawned is the only way the orphan can still be reclaimed. + writeLocalAdapterJsonFile(statePath, { pid: 4242 }); + cleanupFailedLocalAdapterStartup(options, 4242); + expect(killed).toEqual([["kill", "4242"]]); + expect(fs.existsSync(statePath)).toBe(false); + }); + it("probes adapter health with the expected token hash", async () => { const tokenHash = localAdapterTokenHash("secret-token"); const server = http.createServer((req, res) => { diff --git a/src/lib/inference/local-adapter-lifecycle.ts b/src/lib/inference/local-adapter-lifecycle.ts index c739b0b8388..be37413ba43 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -165,19 +165,39 @@ export function isLocalAdapterProcess( : processMatcher(commandLine); } -export function killLocalAdapterPid(options: { +export type LocalAdapterProcessOptions = { pidPath: string; processMatcher: LocalAdapterProcessMatcher; run: RunFn; runCapture: RunCaptureFn; -}): void { - const persistedPid = loadLocalAdapterPid(options.pidPath); - if (isLocalAdapterProcess(persistedPid, options.processMatcher, options.runCapture)) { - options.run(["kill", String(persistedPid)], { ignoreError: true, suppressOutput: true }); +}; + +export function killLocalAdapterPid( + options: LocalAdapterProcessOptions, + pid: number | null | undefined = loadLocalAdapterPid(options.pidPath), +): void { + if (isLocalAdapterProcess(pid, options.processMatcher, options.runCapture)) { + options.run(["kill", String(pid)], { ignoreError: true, suppressOutput: true }); } removeLocalAdapterFile(options.pidPath); } +/** + * Undoes a partial adapter startup so a failed `ensure` leaves no adapter holding the port and no + * state file describing an adapter that is not running. It removes the pid and state files only, + * so any other file an adapter deliberately reuses across a respawn survives. + * + * Callers pass `spawnedPid` so the child of the failed startup is still signalled when the pid file + * was never written — persisting it can itself fail, and the pid file is then the wrong source. + */ +export function cleanupFailedLocalAdapterStartup( + options: LocalAdapterProcessOptions & { statePath: string }, + spawnedPid?: number, +): void { + killLocalAdapterPid(options, spawnedPid); + removeLocalAdapterFile(options.statePath); +} + export function spawnDetachedNodeAdapter(options: { scriptPath: string; env: Record; diff --git a/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts b/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts index 6d7b43c0cae..0b32bc15ae6 100644 --- a/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts +++ b/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts @@ -16,13 +16,14 @@ import { OPENROUTER_RUNTIME_ADAPTER_OPENAI_BASE_URL, } from "./openrouter"; import { + cleanupFailedLocalAdapterStartup, ensureLocalAdapterStateDir, isLocalAdapterProcess, killLocalAdapterPid, + type LocalAdapterProcessOptions, loadLocalAdapterPid, persistLocalAdapterPid, readLocalAdapterJsonFile, - removeLocalAdapterFile, spawnDetachedNodeAdapter, waitForLocalAdapterHealth, writeLocalAdapterJsonFile, @@ -105,27 +106,13 @@ async function withAdapterLock(operation: () => Promise): Promise { throw new Error("OpenRouter Runtime adapter startup is already in progress"); } -function loadPersistedPid(): number | null { - return loadLocalAdapterPid(PID_PATH); -} - -function isAdapterProcess(pid: number | null | undefined): boolean { - return isLocalAdapterProcess(pid, PROCESS_NEEDLE, runCapture); -} - -function killStaleAdapter(): void { - killLocalAdapterPid({ - pidPath: PID_PATH, - processMatcher: PROCESS_NEEDLE, - run, - runCapture, - }); -} - -function cleanupFailedAdapterStartup(): void { - killStaleAdapter(); - removeLocalAdapterFile(STATE_PATH); -} +const ADAPTER_PROCESS: LocalAdapterProcessOptions & { statePath: string } = { + pidPath: PID_PATH, + statePath: STATE_PATH, + processMatcher: PROCESS_NEEDLE, + run, + runCapture, +}; function getAdapterScriptPath(): string { return path.join(__dirname, "openrouter-runtime-adapter-entry.js"); @@ -224,9 +211,9 @@ async function ensureOpenRouterRuntimeAdapterLocked( const configHash = adapterConfigHash(upstreamBaseUrl); const priorState = readLocalAdapterJsonFile(STATE_PATH); const authorizationHash = resolveAuthorizationHash(options.authorizationToken, priorState); - const priorPid = loadPersistedPid(); + const priorPid = loadLocalAdapterPid(PID_PATH); if ( - isAdapterProcess(priorPid) && + isLocalAdapterProcess(priorPid, PROCESS_NEEDLE, runCapture) && priorState?.upstreamBaseUrl === upstreamBaseUrl && priorState?.configHash === configHash && normalizeAuthorizationHash(priorState?.authorizationHash) === authorizationHash && @@ -235,7 +222,7 @@ async function ensureOpenRouterRuntimeAdapterLocked( return adapterRoute(); } - killStaleAdapter(); + killLocalAdapterPid(ADAPTER_PROCESS); const child = spawnDetachedNodeAdapter({ scriptPath: getAdapterScriptPath(), env: { @@ -266,7 +253,7 @@ async function ensureOpenRouterRuntimeAdapterLocked( ); } } catch (err) { - cleanupFailedAdapterStartup(); + cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS, child.pid); throw err; } diff --git a/src/lib/inference/openrouter-runtime-adapter.test.ts b/src/lib/inference/openrouter-runtime-adapter.test.ts index 343479caedb..2cdd5219b01 100644 --- a/src/lib/inference/openrouter-runtime-adapter.test.ts +++ b/src/lib/inference/openrouter-runtime-adapter.test.ts @@ -2,17 +2,47 @@ // SPDX-License-Identifier: Apache-2.0 import { EventEmitter } from "node:events"; +import fs from "node:fs"; import http from "node:http"; import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +// The adapter startup path must not spawn a child, wait on a real port, or signal a real process, +// and its pid, state and lock files are redirected into a temporary state directory. +vi.mock("../runner", async (importOriginal) => ({ + ...(await importOriginal()), + run: vi.fn(), + runCapture: vi.fn(() => "node /opt/nemoclaw/scripts/openrouter-runtime-adapter-entry.js"), +})); +vi.mock("./local-adapter-lifecycle", async (importOriginal) => ({ + ...(await importOriginal()), + spawnDetachedNodeAdapter: vi.fn(() => ({ pid: 5150 })), + waitForLocalAdapterHealth: vi.fn(async () => false), +})); +vi.mock("./openrouter-runtime-adapter-common", async (importOriginal) => { + const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openrouter-adapter-")); + return { + ...(await importOriginal()), + STATE_DIR: stateDir, + PID_PATH: path.join(stateDir, "openrouter-runtime-adapter.pid"), + STATE_PATH: path.join(stateDir, "openrouter-runtime-adapter.json"), + LOCK_PATH: path.join(stateDir, "openrouter-runtime-adapter.lock"), + }; +}); + +import { run } from "../runner"; +import { writeLocalAdapterJsonFile } from "./local-adapter-lifecycle"; import { OPENROUTER_DEFAULT_HEADERS } from "./openrouter"; import { adapterAuthorizationHash, createOpenRouterRuntimeAdapterServer, + ensureOpenRouterRuntimeAdapter, } from "./openrouter-runtime-adapter"; import { OPENROUTER_RUNTIME_ADAPTER_MAX_BODY_BYTES } from "./openrouter-runtime-adapter-forward"; +import { PID_PATH, STATE_DIR, STATE_PATH } from "./openrouter-runtime-adapter-common"; const servers: http.Server[] = []; const OPENROUTER_TEST_TOKEN = "sk-or-test"; @@ -28,6 +58,8 @@ afterEach(async () => { ), ); servers.length = 0; + fs.rmSync(STATE_DIR, { recursive: true, force: true }); + vi.mocked(run).mockClear(); }); function listen(server: http.Server): Promise { @@ -427,4 +459,16 @@ describe("OpenRouter Runtime adapter", () => { await expect(fetch(`${adapterBaseUrl}/health`)).resolves.toMatchObject({ status: 200 }); }); + + it("signals the spawned child and clears the pid and state files when startup never becomes healthy", async () => { + writeLocalAdapterJsonFile(STATE_PATH, { upstreamBaseUrl: "https://stale.example" }); + + await expect( + ensureOpenRouterRuntimeAdapter({ authorizationToken: OPENROUTER_TEST_TOKEN }), + ).rejects.toThrow("did not become healthy"); + + expect(vi.mocked(run).mock.calls.map(([args]) => args)).toEqual([["kill", "5150"]]); + expect(fs.existsSync(PID_PATH)).toBe(false); + expect(fs.existsSync(STATE_PATH)).toBe(false); + }); });