From bbbb0c64a6728d75b295bbf7191153c5444b1b13 Mon Sep 17 00:00:00 2001 From: Ho Lim Date: Mon, 6 Jul 2026 03:39:48 -0700 Subject: [PATCH 1/2] perf(onboard): reuse validated inference probes Signed-off-by: Ho Lim --- .../inference/onboard-probes-curl-harness.ts | 27 +++-- src/lib/inference/onboard-probes.test.ts | 77 ++++++++++++- src/lib/inference/onboard-probes.ts | 101 +++++++++++++++++- 3 files changed, 193 insertions(+), 12 deletions(-) diff --git a/src/lib/inference/onboard-probes-curl-harness.ts b/src/lib/inference/onboard-probes-curl-harness.ts index 66fb194c800..d53ce0edbd8 100644 --- a/src/lib/inference/onboard-probes-curl-harness.ts +++ b/src/lib/inference/onboard-probes-curl-harness.ts @@ -37,11 +37,7 @@ export function makeFakeCurlScript(bodyLogic: string): string { return `${FAKE_CURL_HEADER}${bodyLogic}`; } -// Fake curl for the strict Responses API compatibility check. It records each -// requested URL, returns a successful Responses payload without a tool call, -// then returns a successful Chat Completions payload so callers can assert the -// exact fallback order without duplicating shell parsing in a test body. -export function makeResponsesFallbackUrlRecordingFakeCurlScript(): string { +function makeUrlRecordingFakeCurlScript(responsesPayload: string): string { return `#!/usr/bin/env bash outfile="" url="" @@ -58,7 +54,7 @@ n=$((n + 1)) echo "$n" > "${HARNESS_COUNTER}" printf '%s' "$url" > "${HARNESS_TMPDIR}/request-$n-url.txt" if echo "$url" | grep -q '/responses$'; then - printf '%s' '{"output":[{"type":"message","content":[{"type":"output_text","text":"OK"}]}]}' > "$outfile" + printf '%s' '${responsesPayload}' > "$outfile" else printf '%s' '{"choices":[{"message":{"content":"OK"}}]}' > "$outfile" fi @@ -66,6 +62,25 @@ printf '200' `; } +// Fake curl for the strict Responses API compatibility check. It records each +// requested URL, returns a successful Responses payload without a tool call, +// then returns a successful Chat Completions payload so callers can assert the +// exact fallback order without duplicating shell parsing in a test body. +export function makeResponsesFallbackUrlRecordingFakeCurlScript(): string { + return makeUrlRecordingFakeCurlScript( + '{"output":[{"type":"message","content":[{"type":"output_text","text":"OK"}]}]}', + ); +} + +// Fake curl for cache tests where /responses is a fully valid tool-call +// success. It lets tests prove a later chat-completions-only smoke is not +// satisfied by a Responses-only cache entry. +export function makeResponsesToolCallUrlRecordingFakeCurlScript(): string { + return makeUrlRecordingFakeCurlScript( + '{"output":[{"type":"function_call","name":"emit_ok","arguments":"{\\"value\\":\\"OK\\"}"}]}', + ); +} + // Restore an env var to its pre-test value without branching at the call // site (kept identical to the helper the test file uses so restore semantics // are unchanged). diff --git a/src/lib/inference/onboard-probes.test.ts b/src/lib/inference/onboard-probes.test.ts index 1bef5cc04e0..5e2254ee649 100644 --- a/src/lib/inference/onboard-probes.test.ts +++ b/src/lib/inference/onboard-probes.test.ts @@ -4,17 +4,19 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { captureAuthConfigPath } from "../adapters/http/auth-config-test-helpers"; import { HARNESS_COUNTER, HARNESS_TMPDIR, makeFakeCurlScript, + makeResponsesToolCallUrlRecordingFakeCurlScript, withFakeCurlProbe, } from "./onboard-probes-curl-harness"; const { + clearOpenAiLikeProbeValidationCacheForTests, getChatCompletionsProbeCurlArgs, getChatCompletionsProbePayload, getDeepSeekV4ProValidationProbeCurlArgs, @@ -42,6 +44,10 @@ function restoreEnv(name: string, original: string | undefined): void { const FAKE_CONFIG_PATH = "/tmp/nemoclaw-test-credential.conf"; const FAKE_CREDENTIAL_ARGS = ["--config", FAKE_CONFIG_PATH] as const; +afterEach(() => { + clearOpenAiLikeProbeValidationCacheForTests(); +}); + describe("OpenAI-compatible inference probe response parsing", () => { it("detects tool-calling responses payloads conservatively", () => { expect( @@ -768,6 +774,75 @@ exit 28 ); }); + it("reuses a successful chat-completions validation for a repeated chat-only probe", () => { + const body = `n=$(cat "${HARNESS_COUNTER}") +n=$((n + 1)) +echo "$n" > "${HARNESS_COUNTER}" +cat <<'JSON' > "$outfile" +{"choices":[{"message":{"content":"OK"}}]} +JSON +printf '200' +exit 0 +`; + withFakeCurlProbe( + { + script: makeFakeCurlScript(body), + dirPrefix: "nemoclaw-probe-cache-hit-", + }, + ({ counter }) => { + const first = probeOpenAiLikeEndpoint( + "https://integrate.api.nvidia.com/v1", + "nvidia/nemotron-3-super-120b-a12b", + "nvapi-cache-test", + { skipResponsesProbe: true }, + ); + const second = probeOpenAiLikeEndpoint( + "https://integrate.api.nvidia.com/v1/", + "nvidia/nemotron-3-super-120b-a12b", + "nvapi-cache-test", + { skipResponsesProbe: true }, + ); + + expect(first).toMatchObject({ ok: true, api: "openai-completions" }); + expect(second).toMatchObject({ ok: true, api: "openai-completions" }); + expect(fs.readFileSync(counter, "utf8").trim()).toBe("1"); + }, + ); + }); + + it("keeps Responses-only and chat-only validations in separate cache entries", () => { + withFakeCurlProbe( + { + script: makeResponsesToolCallUrlRecordingFakeCurlScript(), + dirPrefix: "nemoclaw-probe-cache-api-", + }, + ({ counter, tmpDir }) => { + const responses = probeOpenAiLikeEndpoint( + "https://proxy.example.com/v1", + "custom-model", + "proxy-cache-key", + { requireResponsesToolCalling: true }, + ); + const chatOnly = probeOpenAiLikeEndpoint( + "https://proxy.example.com/v1", + "custom-model", + "proxy-cache-key", + { skipResponsesProbe: true }, + ); + + expect(responses).toMatchObject({ ok: true, api: "openai-responses" }); + expect(chatOnly).toMatchObject({ ok: true, api: "openai-completions" }); + expect(fs.readFileSync(counter, "utf8").trim()).toBe("2"); + expect(fs.readFileSync(path.join(tmpDir, "request-1-url.txt"), "utf8")).toBe( + "https://proxy.example.com/v1/responses", + ); + expect(fs.readFileSync(path.join(tmpDir, "request-2-url.txt"), "utf8")).toBe( + "https://proxy.example.com/v1/chat/completions", + ); + }, + ); + }); + // PR #5975 review note PRA-14 (Nemotron). Pins the silent fallback so a // future SGLang fix that removes the workaround stays observable. it("falls back to chat-completions when /responses streaming lacks required events", () => { diff --git a/src/lib/inference/onboard-probes.ts b/src/lib/inference/onboard-probes.ts index f21255472c6..ad28d216600 100644 --- a/src/lib/inference/onboard-probes.ts +++ b/src/lib/inference/onboard-probes.ts @@ -28,6 +28,8 @@ const { const { isWsl } = require("../platform"); const httpProbe = require("../adapters/http/probe"); const authConfigModule = require("../adapters/http/auth-config"); +const { hashCredential } = require("../security/credential-hash"); +const { addTraceEvent } = require("../trace"); const { getHostDockerInternalProbeFailure, isHijackedDockerInternalUrl, @@ -84,6 +86,8 @@ const EXTENDED_NVIDIA_ENDPOINT_VALIDATION_MODELS = new Set([ "qwen/qwen3.5-397b-a17b", "deepseek-ai/deepseek-v4-flash", ]); +const OPENAI_LIKE_PROBE_CACHE_TTL_MS = 10 * 60 * 1000; +const openAiLikeProbeValidationCache = new Map(); // Hostnames that are normally meant for the sandbox/container host boundary. // host.openshell.internal only resolves inside the OpenShell sandbox network, @@ -279,10 +283,85 @@ function getProbeProcessTimeoutMs(args) { return (getCurlMaxTimeSeconds(args) + 5) * 1000; } +function normalizeOpenAiLikeProbeEndpoint(endpointUrl) { + return String(endpointUrl).replace(/\/+$/, ""); +} + +function normalizeProbeAuthMode(options = {}) { + return options.authMode === "query-param" ? "query-param" : "bearer"; +} + +function getOpenAiLikeProbeCacheKey(endpointUrl, model, apiKey, options = {}) { + const credentialHash = hashCredential(apiKey); + if (!credentialHash) return null; + return JSON.stringify({ + endpointUrl: normalizeOpenAiLikeProbeEndpoint(endpointUrl), + model: String(model), + credentialHash, + authMode: normalizeProbeAuthMode(options), + allowHostDockerInternal: options.allowHostDockerInternal === true, + requirements: getOpenAiLikeProbeRequirements(options), + }); +} + +function getOpenAiLikeProbeRequirements(options = {}) { + return { + skipResponsesProbe: options.skipResponsesProbe === true, + requireResponsesToolCalling: options.requireResponsesToolCalling === true, + requireChatCompletionsToolCalling: options.requireChatCompletionsToolCalling === true, + probeStreaming: options.probeStreaming === true, + }; +} + +function isOpenAiLikeProbeCacheEntryFresh(entry) { + return entry.expiresAt > Date.now(); +} + +function getCachedOpenAiLikeProbeResult(cacheKey) { + if (!cacheKey) return null; + const entry = openAiLikeProbeValidationCache.get(cacheKey); + if (!entry) return null; + if (!isOpenAiLikeProbeCacheEntryFresh(entry)) { + openAiLikeProbeValidationCache.delete(cacheKey); + return null; + } + addTraceEvent("openai_like_probe_cache_hit", { + api: entry.api, + skip_responses_probe: entry.skipResponsesProbe, + require_responses_tool_calling: entry.requireResponsesToolCalling, + require_chat_completions_tool_calling: entry.requireChatCompletionsToolCalling, + probe_streaming: entry.probeStreaming, + }); + return { ...entry.result }; +} + +function rememberOpenAiLikeProbeSuccess(cacheKey, options = {}, result = {}) { + if (!cacheKey || !result.ok || result.validated === false || !result.api) return result; + const requirements = getOpenAiLikeProbeRequirements(options); + openAiLikeProbeValidationCache.set(cacheKey, { + ...requirements, + api: result.api, + result: { ...result }, + expiresAt: Date.now() + OPENAI_LIKE_PROBE_CACHE_TTL_MS, + }); + addTraceEvent("openai_like_probe_cache_store", { + api: result.api, + skip_responses_probe: requirements.skipResponsesProbe, + require_responses_tool_calling: requirements.requireResponsesToolCalling, + require_chat_completions_tool_calling: requirements.requireChatCompletionsToolCalling, + probe_streaming: requirements.probeStreaming, + }); + return result; +} + +function clearOpenAiLikeProbeValidationCacheForTests() { + openAiLikeProbeValidationCache.clear(); +} + // ── Responses API probe ────────────────────────────────────────── function probeResponsesToolCalling(endpointUrl, model, apiKey, options = {}) { - const baseUrl = String(endpointUrl).replace(/\/+$/, ""); + const baseUrl = normalizeOpenAiLikeProbeEndpoint(endpointUrl); let authConfig; try { authConfig = buildOpenAiLikeAuthConfig(apiKey, options); @@ -341,7 +420,7 @@ function probeResponsesToolCalling(endpointUrl, model, apiKey, options = {}) { } function probeChatCompletionsToolCalling(endpointUrl, model, apiKey, options = {}) { - const baseUrl = String(endpointUrl).replace(/\/+$/, ""); + const baseUrl = normalizeOpenAiLikeProbeEndpoint(endpointUrl); let authConfig; try { authConfig = buildOpenAiLikeAuthConfig(apiKey, options); @@ -634,7 +713,10 @@ function probeOpenAiLikeEndpoint(endpointUrl, model, apiKey, options = {}) { }; } - const baseUrl = String(endpointUrl).replace(/\/+$/, ""); + const baseUrl = normalizeOpenAiLikeProbeEndpoint(endpointUrl); + const cacheKey = getOpenAiLikeProbeCacheKey(endpointUrl, model, apiKey, options); + const cachedProbe = getCachedOpenAiLikeProbeResult(cacheKey); + if (cachedProbe) return cachedProbe; let authConfig; try { authConfig = buildOpenAiLikeAuthConfig(apiKey, options); @@ -759,7 +841,11 @@ function probeOpenAiLikeEndpoint(endpointUrl, model, apiKey, options = {}) { }; } } - return { ok: true, api: probe.api, label: probe.name }; + return rememberOpenAiLikeProbeSuccess(cacheKey, options, { + ok: true, + api: probe.api, + label: probe.name, + }); } if ( probe.api === "openai-completions" && @@ -810,7 +896,11 @@ function probeOpenAiLikeEndpoint(endpointUrl, model, apiKey, options = {}) { authConfig, }); if (retryResult.ok) { - return { ok: true, api: "openai-completions", label: "Chat Completions API" }; + return rememberOpenAiLikeProbeSuccess(cacheKey, options, { + ok: true, + api: "openai-completions", + label: "Chat Completions API", + }); } if (options.requireChatCompletionsToolCalling === true) { failures.push({ @@ -875,6 +965,7 @@ module.exports = { getKimiK26ValidationProbeCurlArgs, getChatCompletionsProbePayload, getChatCompletionsProbeCurlArgs, + clearOpenAiLikeProbeValidationCacheForTests, probeResponsesToolCalling, probeChatCompletionsToolCalling, probeOpenAiLikeEndpoint, From d33258c9767353fce98d2ac87776d1f08eabe3f9 Mon Sep 17 00:00:00 2001 From: Charan Jagwani Date: Wed, 8 Jul 2026 22:01:22 -0700 Subject: [PATCH 2/2] fix(inference): bind probe cache to pinned addresses Signed-off-by: Charan Jagwani --- src/lib/inference/onboard-probes.test.ts | 36 ++++++++++++++ src/lib/inference/onboard-probes.ts | 63 ++---------------------- 2 files changed, 40 insertions(+), 59 deletions(-) diff --git a/src/lib/inference/onboard-probes.test.ts b/src/lib/inference/onboard-probes.test.ts index 1aa5b403dbb..40e8f4e0603 100644 --- a/src/lib/inference/onboard-probes.test.ts +++ b/src/lib/inference/onboard-probes.test.ts @@ -825,6 +825,42 @@ exit 0 ); }); + it("does not reuse a validation across different pinned address sets (#3771)", () => { + const body = `n=$(cat "${HARNESS_COUNTER}") +n=$((n + 1)) +echo "$n" > "${HARNESS_COUNTER}" +cat <<'JSON' > "$outfile" +{"choices":[{"message":{"content":"OK"}}]} +JSON +printf '200' +exit 0 +`; + withFakeCurlProbe( + { + script: makeFakeCurlScript(body), + dirPrefix: "nemoclaw-probe-cache-pins-", + }, + ({ counter }) => { + const first = probeOpenAiLikeEndpoint( + "https://proxy.example.com/v1", + "custom-model", + "proxy-cache-key", + { skipResponsesProbe: true, pinnedAddresses: ["93.184.216.34"] }, + ); + const rebound = probeOpenAiLikeEndpoint( + "https://proxy.example.com/v1", + "custom-model", + "proxy-cache-key", + { skipResponsesProbe: true, pinnedAddresses: ["93.184.216.35"] }, + ); + + expect(first).toMatchObject({ ok: true, api: "openai-completions" }); + expect(rebound).toMatchObject({ ok: true, api: "openai-completions" }); + expect(fs.readFileSync(counter, "utf8").trim()).toBe("2"); + }, + ); + }); + it("keeps Responses-only and chat-only validations in separate cache entries", () => { withFakeCurlProbe( { diff --git a/src/lib/inference/onboard-probes.ts b/src/lib/inference/onboard-probes.ts index 63381f6d798..b44ccdc1d19 100644 --- a/src/lib/inference/onboard-probes.ts +++ b/src/lib/inference/onboard-probes.ts @@ -236,61 +236,6 @@ function getProbeAuthMode(_provider) { return undefined; } -// Per-validation-probe curl timing. Tighter than the default 60s in -// getCurlTimingArgs() because validation must not hang the wizard for a -// minute on a misbehaving model. See issue #1601 (Bug 3). -function getValidationProbeCurlArgs(opts) { - const args = isWsl(opts) - ? ["--connect-timeout", "20", "--max-time", "30"] - : ["--connect-timeout", "10", "--max-time", "15"]; - return withValidationMaxTimeOverride(args); -} - -function getDeepSeekV4ProValidationProbeCurlArgs(opts) { - const args = isWsl(opts) - ? ["--connect-timeout", "30", "--max-time", "150"] - : ["--connect-timeout", "20", "--max-time", "120"]; - return withValidationMaxTimeOverride(args); -} - -function getKimiK26ValidationProbeCurlArgs(opts) { - const args = isWsl(opts) - ? ["--connect-timeout", "20", "--max-time", "90"] - : ["--connect-timeout", "10", "--max-time", "60"]; - return withValidationMaxTimeOverride(args); -} - -function getExtendedNvidiaEndpointValidationProbeCurlArgs(opts) { - const args = isWsl(opts) - ? ["--connect-timeout", "30", "--max-time", "300"] - : ["--connect-timeout", "10", "--max-time", "300"]; - return withValidationMaxTimeOverride(args); -} - -function getCurlMaxTimeSeconds(args) { - const maxTimeIndex = args.indexOf("--max-time"); - if (maxTimeIndex === -1) return 30; - const value = Number(args[maxTimeIndex + 1]); - return Number.isFinite(value) && value > 0 ? value : 30; -} - -function withValidationMaxTimeOverride(args) { - const raw = (process.env[ONBOARD_VALIDATION_TIMEOUT_ENV] || "").trim(); - if (!raw) return args; - const overrideSeconds = Math.ceil(Number(raw)); - if (!Number.isFinite(overrideSeconds) || overrideSeconds <= 0) return args; - if (overrideSeconds <= getCurlMaxTimeSeconds(args)) return args; - const maxTimeIndex = args.indexOf("--max-time"); - if (maxTimeIndex === -1) return args; - const next = [...args]; - next[maxTimeIndex + 1] = String(overrideSeconds); - return next; -} - -function getProbeProcessTimeoutMs(args) { - return (getCurlMaxTimeSeconds(args) + 5) * 1000; -} - function normalizeOpenAiLikeProbeEndpoint(endpointUrl) { return String(endpointUrl).replace(/\/+$/, ""); } @@ -308,6 +253,7 @@ function getOpenAiLikeProbeCacheKey(endpointUrl, model, apiKey, options = {}) { credentialHash, authMode: normalizeProbeAuthMode(options), allowHostDockerInternal: options.allowHostDockerInternal === true, + pinnedAddresses: Array.isArray(options.pinnedAddresses) ? [...options.pinnedAddresses] : null, requirements: getOpenAiLikeProbeRequirements(options), }); } @@ -734,10 +680,6 @@ function probeOpenAiLikeEndpoint(endpointUrl, model, apiKey, options = {}) { }; } - const baseUrl = normalizeOpenAiLikeProbeEndpoint(endpointUrl); - const cacheKey = getOpenAiLikeProbeCacheKey(endpointUrl, model, apiKey, options); - const cachedProbe = getCachedOpenAiLikeProbeResult(cacheKey); - if (cachedProbe) return cachedProbe; // SSRF source boundary: reject a private/internal endpoint before any curl. // The sandbox-internal alias is handled above, and host.docker.internal is // gated by the allowHostDockerInternal check at the top of this function — @@ -793,6 +735,9 @@ function probeOpenAiLikeEndpoint(endpointUrl, model, apiKey, options = {}) { // captured, so a second DNS lookup here cannot rebind the hostname to a // private/internal address after the public preflight (TOCTOU — cv, #6293). const pinnedAddresses = options.pinnedAddresses; + const cacheKey = getOpenAiLikeProbeCacheKey(endpointUrl, model, apiKey, options); + const cachedProbe = getCachedOpenAiLikeProbeResult(cacheKey); + if (cachedProbe) return cachedProbe; let authConfig; try { authConfig = buildOpenAiLikeAuthConfig(apiKey, options);