Skip to content
65 changes: 64 additions & 1 deletion src/lib/inference/bedrock-runtime-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import("./local-adapter-lifecycle")>()),
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[] = [];

Expand Down Expand Up @@ -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);
});
Expand Down
64 changes: 31 additions & 33 deletions src/lib/inference/bedrock-runtime-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -286,29 +288,20 @@ 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) =>
name.replaceAll(".", "\\."),
).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");
Expand Down Expand Up @@ -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 &&
Expand All @@ -406,7 +399,7 @@ export async function ensureBedrockRuntimeAdapter(options: {
};
}

killStaleAdapter();
killLocalAdapterPid(ADAPTER_PROCESS);
const token = crypto.randomBytes(24).toString("hex");
const childEnv: Record<string, string> = {
NEMOCLAW_BEDROCK_RUNTIME_ENDPOINT_URL: endpointUrl,
Expand All @@ -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 {
Expand Down
30 changes: 30 additions & 0 deletions src/lib/inference/local-adapter-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) => {
Expand Down
30 changes: 25 additions & 5 deletions src/lib/inference/local-adapter-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

export function spawnDetachedNodeAdapter(options: {
scriptPath: string;
env: Record<string, string>;
Expand Down
39 changes: 13 additions & 26 deletions src/lib/inference/openrouter-runtime-adapter-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -105,27 +106,13 @@ async function withAdapterLock<T>(operation: () => Promise<T>): Promise<T> {
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,
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function getAdapterScriptPath(): string {
return path.join(__dirname, "openrouter-runtime-adapter-entry.js");
Expand Down Expand Up @@ -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 &&
Expand All @@ -235,7 +222,7 @@ async function ensureOpenRouterRuntimeAdapterLocked(
return adapterRoute();
}

killStaleAdapter();
killLocalAdapterPid(ADAPTER_PROCESS);
const child = spawnDetachedNodeAdapter({
scriptPath: getAdapterScriptPath(),
env: {
Expand Down Expand Up @@ -266,7 +253,7 @@ async function ensureOpenRouterRuntimeAdapterLocked(
);
}
} catch (err) {
cleanupFailedAdapterStartup();
cleanupFailedLocalAdapterStartup(ADAPTER_PROCESS, child.pid);
throw err;
}

Expand Down
Loading
Loading