From 6a2f364b5c4245bffe33650742b07b9c2f2449f7 Mon Sep 17 00:00:00 2001 From: Yimo Jiang Date: Wed, 9 Sep 2026 11:35:53 +0000 Subject: [PATCH] fix(inference): surface real reason for a slow inference invocation probe The sandbox inference invocation probe reported a generic "sandbox inference invocation probe was unavailable" whenever the transport returned null, which happens when the outer exec timeout SIGTERM-kills the curl subprocess. Because curl used a fixed --max-time 90 while the status readiness timeout was 30s, a healthy-but-slow endpoint (30-90s) was killed by the outer timeout and misreported as unavailable, even though route reachability, backend, and upstream all reported healthy (#11162). - command-transport: classify a null result as timeout (ETIMEDOUT / SIGTERM) vs subprocess error via a shared classifySandboxCommandTransportFailure and report it through an optional onTransportFailure callback. Only the error code crosses the boundary; no captured output leaks. - inference-invocation-probe: surface the real reason instead of the generic message, report curl exit 28 as an endpoint timeout, and derive curl --max-time from the outer exec timeout with a 5s buffer so curl bounds the request (clean exit 28) before the outer timeout can kill it, for both the readiness (30s -> 25s) and rebuild (100s -> 95s) paths. A genuine timeout still fails, but is reported accurately. Fixes #11162 Signed-off-by: Yimo Jiang --- .../inference-invocation-probe.test.ts | 138 +++++++++++++++++- .../sandbox/inference-invocation-probe.ts | 100 +++++++++++-- .../sandbox/command-transport.test.ts | 44 ++++++ src/lib/adapters/sandbox/command-transport.ts | 51 ++++++- 4 files changed, 318 insertions(+), 15 deletions(-) diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 31f0773e13a..5aa1f5f7e3c 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -3,10 +3,14 @@ import { describe, expect, it, vi } from "vitest"; +import type { SandboxExecCommandOptions } from "../../adapters/sandbox/command-transport"; import { buildDcodeSandboxInferenceInvocationArgs, buildSandboxInferenceInvocationCommand, probeSandboxInferenceInvocation, + READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, + resolveInferenceInvocationMaxTimeSeconds, } from "./inference-invocation-probe"; const input = { @@ -76,6 +80,90 @@ describe("sandbox inference invocation probe", () => { expect(JSON.stringify(result)).not.toContain("canary-replay-marker"); }); + it("keeps curl --max-time safely inside the outer exec timeout so a slow endpoint is not killed (#11162)", () => { + const readinessCommand = buildSandboxInferenceInvocationCommand( + input, + READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, + ); + const rebuildCommand = buildSandboxInferenceInvocationCommand( + input, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, + ); + + const readinessMaxTime = Number(readinessCommand.match(/--max-time (\d+)/)?.[1]); + const rebuildMaxTime = Number(rebuildCommand.match(/--max-time (\d+)/)?.[1]); + + // curl --max-time must finish (clean exit 28) before the outer timeout can + // SIGTERM the subprocess and collapse a slow-but-healthy endpoint into a + // generic "unavailable" result. + expect(readinessMaxTime * 1000).toBeLessThan(READINESS_INFERENCE_INVOCATION_TIMEOUT_MS); + expect(rebuildMaxTime * 1000).toBeLessThan(REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS); + expect(resolveInferenceInvocationMaxTimeSeconds(READINESS_INFERENCE_INVOCATION_TIMEOUT_MS)).toBe( + readinessMaxTime, + ); + }); + + it("surfaces a probe timeout when the transport reports the subprocess was killed (#11162)", () => { + const execute = vi.fn( + (_sandbox: string, _command: string, _timeout?: number, options?: SandboxExecCommandOptions) => { + options?.onTransportFailure?.({ kind: "timeout", timeoutMs: 30_000 }); + return null; + }, + ); + + expect(probeSandboxInferenceInvocation(input, { execute }, 30_000)).toEqual({ + ok: false, + detail: "sandbox inference invocation probe timed out after 30s", + httpStatus: null, + }); + }); + + it("surfaces a subprocess error reason when the transport fails to spawn (#11162)", () => { + const execute = vi.fn( + (_sandbox: string, _command: string, _timeout?: number, options?: SandboxExecCommandOptions) => { + options?.onTransportFailure?.({ kind: "error", detail: "ENOENT" }); + return null; + }, + ); + + expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ + ok: false, + detail: "sandbox inference invocation probe subprocess failed (ENOENT)", + httpStatus: null, + }); + }); + + it("keeps the generic unavailable detail when the transport reports no reason (#11162)", () => { + const execute = vi.fn(() => null); + + expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ + ok: false, + detail: "sandbox inference invocation probe was unavailable", + httpStatus: null, + }); + }); + + it("reports a curl-level endpoint timeout (exit 28) as a timeout, not a generic exit (#11162)", () => { + const execute = vi.fn(() => ({ status: 28, stdout: "curl-error:28", stderr: "" })); + + expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ + ok: false, + detail: + "sandbox inference invocation probe timed out waiting for the endpoint (curl exit 28)", + httpStatus: null, + }); + }); + + it("reports a non-timeout curl exit accurately (#11162)", () => { + const execute = vi.fn(() => ({ status: 7, stdout: "curl-error:7", stderr: "" })); + + expect(probeSandboxInferenceInvocation(input, { execute })).toEqual({ + ok: false, + detail: "sandbox inference invocation probe could not complete the request (curl exit 7)", + httpStatus: null, + }); + }); + it("accepts a successful completion through the stored gateway route (#6195)", () => { const execute = vi.fn(() => ({ status: 0, @@ -100,7 +188,11 @@ describe("sandbox inference invocation probe", () => { "dcode-workspace", expect.any(String), expect.any(Number), - { gatewayName: "recorded-gateway", allowLocalDockerFallback: false }, + { + gatewayName: "recorded-gateway", + allowLocalDockerFallback: false, + onTransportFailure: expect.any(Function), + }, ); }); @@ -127,7 +219,11 @@ describe("sandbox inference invocation probe", () => { "hermes-workspace", expect.any(String), expect.any(Number), - { gatewayName: "nemoclaw-19080", allowLocalDockerFallback: false }, + { + gatewayName: "nemoclaw-19080", + allowLocalDockerFallback: false, + onTransportFailure: expect.any(Function), + }, ); expect(execute).toHaveBeenCalledOnce(); expect(runOpenshell).not.toHaveBeenCalled(); @@ -210,6 +306,44 @@ describe("sandbox inference invocation probe", () => { }); }); + it("surfaces a probe timeout when the Deep Agents Code launcher subprocess is killed (#11162)", () => { + const runOpenshell = vi.fn(() => ({ + ...openshellResult(0, "", ""), + status: null, + signal: "SIGTERM" as NodeJS.Signals, + error: Object.assign(new Error("ETIMEDOUT"), { code: "ETIMEDOUT" }), + })); + + expect( + probeSandboxInferenceInvocation( + { ...input, agentName: "langchain-deepagents-code" }, + { runOpenshell }, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, + ), + ).toEqual({ + ok: false, + detail: "sandbox inference invocation probe timed out after 100s", + httpStatus: null, + }); + }); + + it("surfaces a subprocess error when the Deep Agents Code launcher throws (#11162)", () => { + const runOpenshell = vi.fn(() => { + throw Object.assign(new Error("spawn openshell ENOENT"), { code: "ENOENT" }); + }); + + expect( + probeSandboxInferenceInvocation( + { ...input, agentName: "langchain-deepagents-code" }, + { runOpenshell }, + ), + ).toEqual({ + ok: false, + detail: "sandbox inference invocation probe subprocess failed (ENOENT)", + httpStatus: null, + }); + }); + it("accepts a served response body that serializes an empty tool call list (#9108)", () => { const body = JSON.stringify({ object: "chat.completion", diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index 28507ab8372..3a022f0a4e0 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -8,6 +8,10 @@ import { validateInferenceResponseBody } from "../../inference/health"; import { MIN_PROBE_REPLY_TOKENS, resolveMaxTokensField } from "../../inference/max-tokens-field"; import { shellQuote } from "../../runner"; import { DCODE_MANAGED_EXEC_LAUNCHER } from "./connect-inference-route-probe"; +import { + classifySandboxCommandTransportFailure, + type SandboxCommandTransportFailure, +} from "../../adapters/sandbox/command-transport"; import { executeSandboxExecCommand, type SandboxCommandResult, @@ -47,6 +51,31 @@ export const REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS = 100_000; export const READINESS_INFERENCE_INVOCATION_TIMEOUT_MS = 30_000; const INFERENCE_INVOCATION_MAX_RESPONSE_BYTES = 64 * 1024; +// curl's `--max-time` bounds the whole request (connect + transfer). It must +// sit safely inside the outer exec timeout so a slow-but-healthy endpoint is +// bounded by curl (clean exit 28) instead of being SIGTERM-killed by the outer +// timeout and collapsed into a generic "unavailable" result (#11162). The +// buffer reserves headroom for `openshell sandbox exec` spawn/attach overhead +// so curl finishes before the outer kill. Note: an operator override via +// NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS shortens only the outer exec timeout, not +// this derived budget; a genuine timeout there is still reported accurately as +// a timeout with the effective duration. +const INFERENCE_INVOCATION_CONNECT_TIMEOUT_SECONDS = 5; +const INFERENCE_INVOCATION_OUTER_TIMEOUT_BUFFER_MS = 5_000; + +/** + * Derive curl's `--max-time` (whole seconds) from the outer exec timeout so the + * request is always bounded by curl before the outer timeout can SIGTERM the + * subprocess. Clamped to at least 1s for a pathologically small outer timeout; + * the unit test asserts the derived budget stays strictly below every real + * outer timeout the callers use. + */ +export function resolveInferenceInvocationMaxTimeSeconds(timeoutMs: number): number { + const budgetMs = timeoutMs - INFERENCE_INVOCATION_OUTER_TIMEOUT_BUFFER_MS; + const seconds = Math.floor(budgetMs / 1000); + return Math.max(1, seconds); +} + function buildProbeRequest(input: SandboxInferenceInvocationInput): { endpoint: string; headers: string[]; @@ -93,6 +122,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { export function buildSandboxInferenceInvocationCommand( input: SandboxInferenceInvocationInput, + timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ): string { const request = buildProbeRequest(input); const headerArgs = ["Content-Type: application/json", ...request.headers] @@ -100,11 +130,12 @@ export function buildSandboxInferenceInvocationCommand( .join(" "); const payload = shellQuote(JSON.stringify(request.payload)); const endpoint = shellQuote(request.endpoint); + const maxTimeSeconds = resolveInferenceInvocationMaxTimeSeconds(timeoutMs); return [ "umask 077", "body=$(mktemp /tmp/nemoclaw-inference-invocation.XXXXXX) || exit 1", "trap 'rm -f \"$body\"' EXIT HUP INT TERM", - `code=$(curl -sS --connect-timeout 5 --max-time 90 --max-filesize ${INFERENCE_INVOCATION_MAX_RESPONSE_BYTES} -o "$body" -w '%{http_code}' ${headerArgs} --data-binary ${payload} ${endpoint}) || { rc=$?; printf 'curl-error:%s\\n' "$rc"; exit "$rc"; }`, + `code=$(curl -sS --connect-timeout ${INFERENCE_INVOCATION_CONNECT_TIMEOUT_SECONDS} --max-time ${maxTimeSeconds} --max-filesize ${INFERENCE_INVOCATION_MAX_RESPONSE_BYTES} -o "$body" -w '%{http_code}' ${headerArgs} --data-binary ${payload} ${endpoint}) || { rc=$?; printf 'curl-error:%s\\n' "$rc"; exit "$rc"; }`, "printf '%s\\n' \"$code\"", 'case "$code" in 2??) cat "$body"; exit 0 ;; *) exit 1 ;; esac', ].join("; "); @@ -112,6 +143,7 @@ export function buildSandboxInferenceInvocationCommand( export function buildDcodeSandboxInferenceInvocationArgs( input: SandboxInferenceInvocationInput, + timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ): string[] { return [ "sandbox", @@ -130,18 +162,36 @@ export function buildDcodeSandboxInferenceInvocationArgs( DCODE_MANAGED_EXEC_LAUNCHER, "/bin/sh", "-c", - buildSandboxInferenceInvocationCommand(input), + buildSandboxInferenceInvocationCommand(input, timeoutMs), ]; } +/** Describe why the transport produced no result so the probe surfaces the real reason (#11162). */ +function describeInvocationTransportFailure( + failure: SandboxCommandTransportFailure | null, +): string { + if (failure?.kind === "timeout") { + const seconds = failure.timeoutMs / 1000; + const rendered = seconds >= 1 ? `${Math.round(seconds)}s` : `${failure.timeoutMs}ms`; + return `sandbox inference invocation probe timed out after ${rendered}`; + } + if (failure?.kind === "error") { + return failure.detail + ? `sandbox inference invocation probe subprocess failed (${failure.detail})` + : "sandbox inference invocation probe subprocess failed"; + } + return "sandbox inference invocation probe was unavailable"; +} + function executeDcodeSandboxInferenceInvocation( input: SandboxInferenceInvocationInput, deps: SandboxInferenceInvocationDeps, timeoutMs: number, + onTransportFailure: (failure: SandboxCommandTransportFailure) => void, ): SandboxCommandResult | null { const runOpenshell = deps.runOpenshell ?? runOpenshellProviderCommand; try { - const result = runOpenshell(buildDcodeSandboxInferenceInvocationArgs(input), { + const result = runOpenshell(buildDcodeSandboxInferenceInvocationArgs(input, timeoutMs), { ignoreError: true, ...(input.runtimeSelection ? { runtimeSelection: input.runtimeSelection } : {}), stdio: ["ignore", "pipe", "pipe"], @@ -153,6 +203,8 @@ function executeDcodeSandboxInferenceInvocation( typeof result.stderr !== "string" || result.stderr.trim() ) { + const failure = classifySandboxCommandTransportFailure(result, timeoutMs); + if (failure) onTransportFailure(failure); return null; } return { @@ -160,7 +212,10 @@ function executeDcodeSandboxInferenceInvocation( stdout: result.stdout, stderr: result.stderr, }; - } catch { + } catch (error) { + onTransportFailure( + classifySandboxCommandTransportFailure({ error }, timeoutMs) ?? { kind: "error" }, + ); return null; } } @@ -177,18 +232,23 @@ export function probeSandboxInferenceInvocation( timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ): SandboxInferenceInvocationResult { let result: SandboxCommandResult | null; + let transportFailure: SandboxCommandTransportFailure | null = null; + const onTransportFailure = (failure: SandboxCommandTransportFailure) => { + transportFailure = failure; + }; if (input.agentName === DCODE_AGENT_NAME) { - result = executeDcodeSandboxInferenceInvocation(input, deps, timeoutMs); + result = executeDcodeSandboxInferenceInvocation(input, deps, timeoutMs, onTransportFailure); } else { const execute = deps.execute ?? executeSandboxExecCommand; const execOptions: SandboxExecCommandOptions = { ...(input.gatewayName ? { gatewayName: input.gatewayName } : {}), ...(input.runtimeSelection ? { runtimeSelection: input.runtimeSelection } : {}), allowLocalDockerFallback: false, + onTransportFailure, }; result = execute( input.sandboxName, - buildSandboxInferenceInvocationCommand(input), + buildSandboxInferenceInvocationCommand(input, timeoutMs), timeoutMs, execOptions, ); @@ -196,7 +256,7 @@ export function probeSandboxInferenceInvocation( if (!result) { return { ok: false, - detail: "sandbox inference invocation probe was unavailable", + detail: describeInvocationTransportFailure(transportFailure), httpStatus: null, }; } @@ -220,11 +280,31 @@ export function probeSandboxInferenceInvocation( }; } const httpStatus = result.stdout.match(/(?:^|\n)([1-5]\d\d)(?:\n|$)/)?.[1]; + if (httpStatus) { + return { + ok: false, + detail: `sandbox inference invocation probe returned HTTP ${httpStatus}`, + httpStatus: Number.parseInt(httpStatus, 10), + }; + } + // curl exits non-zero with `curl-error:` on stdout when the request could + // not complete. Exit 28 is curl's own timeout; surface it as an endpoint + // timeout instead of a generic exit code so a slow-but-healthy endpoint that + // curl bounded is reported accurately (#11162). Only the curl exit code (never + // response content) is read from the output here. + const curlExit = result.stdout.match(/(?:^|\n)curl-error:(\d+)(?:\n|$)/)?.[1]; + if (curlExit === "28") { + return { + ok: false, + detail: "sandbox inference invocation probe timed out waiting for the endpoint (curl exit 28)", + httpStatus: null, + }; + } return { ok: false, - detail: httpStatus - ? `sandbox inference invocation probe returned HTTP ${httpStatus}` + detail: curlExit + ? `sandbox inference invocation probe could not complete the request (curl exit ${curlExit})` : `sandbox inference invocation probe exited with status ${result.status}`, - httpStatus: httpStatus ? Number.parseInt(httpStatus, 10) : null, + httpStatus: null, }; } diff --git a/src/lib/adapters/sandbox/command-transport.test.ts b/src/lib/adapters/sandbox/command-transport.test.ts index 99ef24f9b12..2bf1214a316 100644 --- a/src/lib/adapters/sandbox/command-transport.test.ts +++ b/src/lib/adapters/sandbox/command-transport.test.ts @@ -157,6 +157,50 @@ describe("sandbox command transport", () => { ]); }); + it("reports a timeout when the gateway-pinned exec subprocess is SIGTERM-killed (#11162)", () => { + const deps = createDependencies({ + extractSandboxExecCommandStdout: vi.fn(() => null), + }); + mocks.spawnSync.mockReturnValue( + spawnResult("", { + status: null, + signal: "SIGTERM", + error: Object.assign(new Error("ETIMEDOUT"), { code: "ETIMEDOUT" }), + }), + ); + const failures: unknown[] = []; + + expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + allowLocalDockerFallback: false, + onTransportFailure: (failure) => failures.push(failure), + }), + ).toBeNull(); + expect(failures).toEqual([{ kind: "timeout", timeoutMs: 9000 }]); + }); + + it("reports a subprocess error code when the gateway-pinned exec cannot spawn (#11162)", () => { + const deps = createDependencies({ + extractSandboxExecCommandStdout: vi.fn(() => null), + }); + mocks.spawnSync.mockReturnValue( + spawnResult("", { + status: null, + signal: null, + error: Object.assign(new Error("spawn openshell ENOENT"), { code: "ENOENT" }), + }), + ); + const failures: unknown[] = []; + + expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + allowLocalDockerFallback: false, + onTransportFailure: (failure) => failures.push(failure), + }), + ).toBeNull(); + expect(failures).toEqual([{ kind: "error", detail: "ENOENT" }]); + }); + it("does not use local Docker fallback for gateway-pinned exec (#9834)", () => { const deps = createDependencies({ extractSandboxExecCommandStdout: vi.fn(() => null), diff --git a/src/lib/adapters/sandbox/command-transport.ts b/src/lib/adapters/sandbox/command-transport.ts index 1dac1265978..bef93c8a43f 100644 --- a/src/lib/adapters/sandbox/command-transport.ts +++ b/src/lib/adapters/sandbox/command-transport.ts @@ -11,9 +11,22 @@ export type SandboxCommandResult = { stderr: string; }; +/** + * Why a sandbox exec transport produced no usable result. A subprocess that is + * killed by the outer timeout is a distinct condition from a subprocess that + * failed to spawn or exited abnormally; callers such as the inference + * invocation probe surface the real reason instead of a generic "unavailable" + * message (#11162). The `detail` is limited to a subprocess error code so no + * untrusted command output can leak through this boundary. + */ +export type SandboxCommandTransportFailure = + | { kind: "timeout"; timeoutMs: number } + | { kind: "error"; detail?: string }; + export type SandboxExecCommandOptions = { allowLocalDockerFallback?: boolean; gatewayName?: string; + onTransportFailure?: (failure: SandboxCommandTransportFailure) => void; runtimeEnv?: NodeJS.ProcessEnv; }; @@ -59,6 +72,30 @@ function resolveSandboxExecTimeout(timeout: number): number { return Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; } +/** + * Classify a subprocess outcome that yielded no usable command result. A + * subprocess timeout sets `error.code = "ETIMEDOUT"` and kills the child with + * SIGTERM; report that as a timeout so callers can distinguish a slow endpoint + * from a genuine subprocess error (#11162). A missing error and signal returns + * `null`: the cause is unknown, so the caller keeps its generic message. Only + * the error code (never the error message or any captured output) crosses this + * boundary. Shared by the OpenShell exec transport and the DCode + * `runOpenshell` probe path so both classify identically. + */ +export function classifySandboxCommandTransportFailure( + outcome: { error?: unknown; signal?: NodeJS.Signals | null }, + timeoutMs: number, +): SandboxCommandTransportFailure | null { + const error = outcome.error as NodeJS.ErrnoException | undefined; + if (error?.code === "ETIMEDOUT" || outcome.signal === "SIGTERM") { + return { kind: "timeout", timeoutMs }; + } + if (error) { + return error.code ? { kind: "error", detail: error.code } : { kind: "error" }; + } + return null; +} + export function executeSandboxCommandTransport( deps: CommandTransportDependencies, sandboxName: string, @@ -167,6 +204,7 @@ export function executeSandboxExecCommandTransport( ): SandboxCommandResult | null { const markedCommand = deps.buildSandboxExecMarkedCommand(command); const effectiveTimeout = resolveSandboxExecTimeout(timeout); + let pendingFailure: SandboxCommandTransportFailure | null = null; try { const gatewayArgs = options.gatewayName ? ["-g", options.gatewayName] : []; const result = spawnSync( @@ -192,11 +230,18 @@ export function executeSandboxExecCommandTransport( ); const parsed = parseSandboxCommandResult(deps, result); if (parsed !== null) return parsed; - } catch { + pendingFailure = classifySandboxCommandTransportFailure(result, effectiveTimeout); + } catch (error) { // OpenShell transport failed; try the trusted direct-container fallback. + pendingFailure = classifySandboxCommandTransportFailure({ error }, effectiveTimeout); + } + if (options.allowLocalDockerFallback === false) { + if (pendingFailure) options.onTransportFailure?.(pendingFailure); + return null; } - if (options.allowLocalDockerFallback === false) return null; // Keep the fallback outside the OpenShell try/catch so a fail-closed identity // refusal cannot be caught and retried against changing container state. - return executeLocalSandboxCommand(deps, sandboxName, markedCommand, effectiveTimeout); + const fallback = executeLocalSandboxCommand(deps, sandboxName, markedCommand, effectiveTimeout); + if (fallback === null && pendingFailure) options.onTransportFailure?.(pendingFailure); + return fallback; }