From da4bc7856ccce8e3bdab421648d63cae94635265 Mon Sep 17 00:00:00 2001 From: Udaya Tejas Date: Tue, 18 Aug 2026 19:35:20 -0700 Subject: [PATCH 1/3] fix(inference): clean up a failed Bedrock Runtime adapter startup A Bedrock Runtime adapter startup that never became healthy threw straight out of the health wait, leaving the child it had just spawned running on the adapter port and leaving a state file that described the previous adapter. Move the teardown both sibling adapters already perform into one shared cleanupFailedLocalAdapterStartup in local-adapter-lifecycle.ts, delete the per-adapter kill and cleanup wrappers in the Bedrock and OpenRouter lifecycles, and guard the Bedrock post-spawn block with the shared cleanup. Production is a net line reduction and no new import edge is created. Signed-off-by: Udaya Tejas --- .../inference/bedrock-runtime-adapter.test.ts | 45 ++++++++++++- src/lib/inference/bedrock-runtime-adapter.ts | 64 +++++++++---------- src/lib/inference/local-adapter-lifecycle.ts | 18 +++++- .../openrouter-runtime-adapter-lifecycle.ts | 39 ++++------- 4 files changed, 104 insertions(+), 62 deletions(-) diff --git a/src/lib/inference/bedrock-runtime-adapter.test.ts b/src/lib/inference/bedrock-runtime-adapter.test.ts index 38908c684fc..8b870335d36 100644 --- a/src/lib/inference/bedrock-runtime-adapter.test.ts +++ b/src/lib/inference/bedrock-runtime-adapter.test.ts @@ -5,14 +5,33 @@ 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, +} from "./local-adapter-lifecycle"; const servers: http.Server[] = []; @@ -383,6 +402,30 @@ 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: { + 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, + }, + }), + ).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. + 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); + }); + 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 9f010bb4bbf..0d901c5bb6e 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"); @@ -385,10 +378,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 && @@ -405,7 +398,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, @@ -425,22 +418,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); + throw err; + } process.env[BEDROCK_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV] = token; return { diff --git a/src/lib/inference/local-adapter-lifecycle.ts b/src/lib/inference/local-adapter-lifecycle.ts index c739b0b8388..ec584b5abbc 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -165,12 +165,14 @@ export function isLocalAdapterProcess( : processMatcher(commandLine); } -export function killLocalAdapterPid(options: { +export type LocalAdapterProcessOptions = { pidPath: string; processMatcher: LocalAdapterProcessMatcher; run: RunFn; runCapture: RunCaptureFn; -}): void { +}; + +export function killLocalAdapterPid(options: LocalAdapterProcessOptions): void { const persistedPid = loadLocalAdapterPid(options.pidPath); if (isLocalAdapterProcess(persistedPid, options.processMatcher, options.runCapture)) { options.run(["kill", String(persistedPid)], { ignoreError: true, suppressOutput: true }); @@ -178,6 +180,18 @@ export function killLocalAdapterPid(options: { 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. + */ +export function cleanupFailedLocalAdapterStartup( + options: LocalAdapterProcessOptions & { statePath: string }, +): void { + killLocalAdapterPid(options); + 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 36894e3990f..c7325ddc16a 100644 --- a/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts +++ b/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts @@ -28,13 +28,14 @@ import { OPENROUTER_RUNTIME_ADAPTER_OPENAI_BASE_URL, } from "./openrouter"; import { + cleanupFailedLocalAdapterStartup, ensureLocalAdapterStateDir, isLocalAdapterProcess, killLocalAdapterPid, + type LocalAdapterProcessOptions, loadLocalAdapterPid, persistLocalAdapterPid, readLocalAdapterJsonFile, - removeLocalAdapterFile, spawnDetachedNodeAdapter, waitForLocalAdapterHealth, writeLocalAdapterJsonFile, @@ -117,27 +118,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"); @@ -252,9 +239,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 && @@ -263,7 +250,7 @@ async function ensureOpenRouterRuntimeAdapterLocked( return adapterRoute(); } - killStaleAdapter(); + killLocalAdapterPid(ADAPTER_PROCESS); const child = spawnDetachedNodeAdapter({ scriptPath: getAdapterScriptPath(), env: { @@ -294,7 +281,7 @@ async function ensureOpenRouterRuntimeAdapterLocked( ); } } catch (err) { - cleanupFailedAdapterStartup(); + cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS); throw err; } From b138da328091ec95188311693f9b46e3d39787df Mon Sep 17 00:00:00 2001 From: Udaya Tejas Date: Wed, 19 Aug 2026 09:48:48 -0700 Subject: [PATCH 2/3] fix(inference): kill the spawned adapter child when its pid file cannot be persisted persistLocalAdapterPid runs after the adapter child is already spawned and can throw on its own: it creates the state directory, refuses symlinked paths, and writes the file. When it throws, the failed-startup cleanup had no pid file left to reload, so it removed the state file and left the child holding the port. The cleanup now takes the pid the caller just spawned and prefers it over reloading the pid file, and both adapters pass their child's pid. HTTPS Pin keeps its own teardown, which awaits process exit and refuses to start a competing listener. Signed-off-by: Udaya Tejas --- .../inference/bedrock-runtime-adapter.test.ts | 40 ++++++++++++++----- src/lib/inference/bedrock-runtime-adapter.ts | 2 +- .../inference/local-adapter-lifecycle.test.ts | 30 ++++++++++++++ src/lib/inference/local-adapter-lifecycle.ts | 16 +++++--- .../openrouter-runtime-adapter-lifecycle.ts | 2 +- 5 files changed, 73 insertions(+), 17 deletions(-) diff --git a/src/lib/inference/bedrock-runtime-adapter.test.ts b/src/lib/inference/bedrock-runtime-adapter.test.ts index 8b870335d36..bc1eb7a5087 100644 --- a/src/lib/inference/bedrock-runtime-adapter.test.ts +++ b/src/lib/inference/bedrock-runtime-adapter.test.ts @@ -31,8 +31,17 @@ 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[] = []; afterEach(async () => { @@ -407,23 +416,34 @@ describe("Bedrock Runtime OpenAI adapter", () => { vi.mocked(cleanupFailedLocalAdapterStartup).mockClear(); await expect( - ensureBedrockRuntimeAdapter({ - 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, - }, - }), + 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. + // 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", () => { diff --git a/src/lib/inference/bedrock-runtime-adapter.ts b/src/lib/inference/bedrock-runtime-adapter.ts index 0d901c5bb6e..be57ed548aa 100644 --- a/src/lib/inference/bedrock-runtime-adapter.ts +++ b/src/lib/inference/bedrock-runtime-adapter.ts @@ -436,7 +436,7 @@ export async function ensureBedrockRuntimeAdapter(options: { updatedAt: new Date().toISOString(), }); } catch (err) { - cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS); + cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS, child.pid); throw err; } process.env[BEDROCK_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV] = token; 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 ec584b5abbc..be37413ba43 100644 --- a/src/lib/inference/local-adapter-lifecycle.ts +++ b/src/lib/inference/local-adapter-lifecycle.ts @@ -172,10 +172,12 @@ export type LocalAdapterProcessOptions = { runCapture: RunCaptureFn; }; -export function killLocalAdapterPid(options: LocalAdapterProcessOptions): 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); } @@ -184,11 +186,15 @@ export function killLocalAdapterPid(options: LocalAdapterProcessOptions): void { * 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); + killLocalAdapterPid(options, spawnedPid); removeLocalAdapterFile(options.statePath); } diff --git a/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts b/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts index c7325ddc16a..524a2fd3db0 100644 --- a/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts +++ b/src/lib/inference/openrouter-runtime-adapter-lifecycle.ts @@ -281,7 +281,7 @@ async function ensureOpenRouterRuntimeAdapterLocked( ); } } catch (err) { - cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS); + cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS, child.pid); throw err; } From a24a33cb8ad2b433f448fbc9c8985d1bf90168bd Mon Sep 17 00:00:00 2001 From: Udaya Tejas Date: Wed, 19 Aug 2026 09:48:49 -0700 Subject: [PATCH 3/3] test(inference): cover the OpenRouter adapter failed-startup cleanup ensureOpenRouterRuntimeAdapter had no test call site, so the shared cleanup it now routes through was unexercised. The new case drives a startup that never becomes healthy and asserts the real cleanup signals the spawned child and removes the adapter's own pid and state files. Signed-off-by: Udaya Tejas --- .../openrouter-runtime-adapter.test.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) 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); + }); });