diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index fc07770498b..6b03329ab46 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3786,7 +3786,7 @@ Set them before running `$$nemoclaw onboard` if a slow connection or large model | `NEMOCLAW_OLLAMA_PULL_TIMEOUT` | `1800` (30 minutes) | Wall-clock timeout for `ollama pull` during onboard, in seconds. Accepts integer or float values. Already-downloaded layers are kept; re-running the pull resumes them. | | `NEMOCLAW_LOCAL_INFERENCE_TIMEOUT` | `180` | Wall-clock timeout for the inference-server validation probe during onboard, in seconds. Raise on slow networks or for very large prompts. | | `NEMOCLAW_SANDBOX_READY_TIMEOUT` | `180` | Wall-clock timeout for post-create readiness and OpenShell command re-registration after policy application, in seconds. Raise when the sandbox image build, gateway upload, in-sandbox boot, or post-policy re-registration exceeds the default (typical on 70B+ models, first-time gateway uploads over slow links, or DGX Station / remote-VM first runs). When the post-create deadline expires, onboarding deletes an orphaned sandbox and prints the retry hint. | -| `NEMOCLAW_SANDBOX_READY_ERROR_DEBOUNCE` | `30` | Consecutive `Error`-phase polls (2s apart, so ~60s by default) the post-create readiness wait tolerates before treating `Error` as terminal. The gateway can briefly report a just-created sandbox in `Error` while it re-registers the sandbox (seen on DGX Spark); the debounce lets that transient recover to `Ready`. `Failed` and `CrashLoopBackOff` always fail immediately. Set to `1` to restore fast-fail on the first `Error` poll. | +| `NEMOCLAW_SANDBOX_READY_ERROR_DEBOUNCE` | `30` | Consecutive `Error`-phase polls the post-create readiness wait tolerates before treating `Error` as terminal. Polling starts at 250ms and backs off to a 2-second cap, while `NEMOCLAW_SANDBOX_READY_TIMEOUT` remains the overall deadline. The gateway can briefly report a just-created sandbox in `Error` while it re-registers the sandbox (seen on DGX Spark); the debounce lets that transient recover to `Ready`. `Failed` and `CrashLoopBackOff` always fail immediately. Set to `1` to restore fast-fail on the first `Error` poll. | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 972d93027b4..72f41fac654 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1543,16 +1543,22 @@ Onboarding ends with: On a fresh onboard the OpenShell gateway can (re)start its supervisor session and re-register the just-created sandbox. During that window `openshell sandbox list` briefly reports the sandbox in the transient `Error` phase before it flips to `Ready`, as seen on DGX Spark when supervisor restart races the sandbox bootstrap. -NemoClaw tolerates a bounded run of consecutive `Error` polls (default 30 polls / ~60s) so this transient recovers on its own; only `Error` that persists past the debounce window is treated as terminal. `Failed` and `CrashLoopBackOff` are always terminal and fail immediately. +NemoClaw polls immediately, starts retrying after 250ms, and backs off to a 2-second cap. +It tolerates 30 consecutive `Error` observations by default so this transient recovers on its own. +Only `Error` that persists through the debounce count is terminal, unless the overall `NEMOCLAW_SANDBOX_READY_TIMEOUT` deadline expires first. +`Failed` and `CrashLoopBackOff` are always terminal and fail immediately. -If your host needs a longer window (slower re-registration), raise the debounce; to fail fast on the first `Error` poll, set it to `1`: +If your host needs more observations for slower re-registration, raise the debounce. +Raise `NEMOCLAW_SANDBOX_READY_TIMEOUT` too if the overall deadline is too short. +To fail fast on the first `Error` poll, set the debounce to `1`: ```bash -export NEMOCLAW_SANDBOX_READY_ERROR_DEBOUNCE=60 # tolerate ~120s of transient Error +export NEMOCLAW_SANDBOX_READY_ERROR_DEBOUNCE=1 $$nemoclaw onboard ``` -If the failure persists after the debounce, the sandbox is genuinely stuck — inspect the retained diagnostics and gateway state: +If the failure persists after the debounce, the sandbox is stuck. +Inspect the retained diagnostics and gateway state: ```bash openshell sandbox list diff --git a/src/lib/agent/gateway-readiness.test.ts b/src/lib/agent/gateway-readiness.test.ts new file mode 100644 index 00000000000..2ae6dba39d9 --- /dev/null +++ b/src/lib/agent/gateway-readiness.test.ts @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { waitForAgentGatewayReady } from "./gateway-readiness"; + +function clock() { + let nowMs = 10_000; + const sleepSeconds = vi.fn((seconds: number) => { + nowMs += seconds * 1000; + }); + return { now: () => nowMs, sleepSeconds }; +} + +describe("waitForAgentGatewayReady", () => { + it("returns immediately when the agent gateway is already ready", () => { + const time = clock(); + const probe = vi.fn(() => true); + + expect(waitForAgentGatewayReady({ timeoutSeconds: 60, probe, ...time })).toBe(true); + expect(probe).toHaveBeenCalledOnce(); + expect(time.sleepSeconds).not.toHaveBeenCalled(); + }); + + it("retries quickly and succeeds before the deadline", () => { + const time = clock(); + const probe = vi.fn().mockReturnValueOnce(false).mockReturnValue(true); + + expect(waitForAgentGatewayReady({ timeoutSeconds: 60, probe, ...time })).toBe(true); + expect(probe).toHaveBeenCalledTimes(2); + expect(time.sleepSeconds).toHaveBeenCalledWith(0.25); + }); + + it("uses the full short deadline before timing out", () => { + const time = clock(); + const probe = vi.fn(() => false); + + expect(waitForAgentGatewayReady({ timeoutSeconds: 0.1, probe, ...time })).toBe(false); + expect(time.sleepSeconds.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBe(0.1); + }); + + it("does not probe when the configured deadline is zero", () => { + const time = clock(); + const probe = vi.fn(() => true); + + expect(waitForAgentGatewayReady({ timeoutSeconds: 0, probe, ...time })).toBe(false); + expect(probe).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/agent/gateway-readiness.ts b/src/lib/agent/gateway-readiness.ts new file mode 100644 index 00000000000..3f7e4ea00fb --- /dev/null +++ b/src/lib/agent/gateway-readiness.ts @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { waitUntil } from "../core/wait"; +import { createReadinessWaitOptions } from "../onboard/readiness-wait"; + +export function waitForAgentGatewayReady(options: { + timeoutSeconds: number; + probe: () => boolean; + sleepSeconds: (seconds: number) => void; + now?: () => number; +}): boolean { + const waitOptions = createReadinessWaitOptions({ + budgetMs: Math.max(0, options.timeoutSeconds * 1000), + maxIntervalMs: 3_000, + now: options.now, + sleep: (ms) => options.sleepSeconds(ms / 1000), + }); + return waitOptions !== null && waitUntil(options.probe, waitOptions); +} diff --git a/src/lib/agent/onboard.test.ts b/src/lib/agent/onboard.test.ts index 78eaa117e63..120188c8853 100644 --- a/src/lib/agent/onboard.test.ts +++ b/src/lib/agent/onboard.test.ts @@ -7,6 +7,7 @@ import type { AgentDefinition } from "./defs"; import { collectHermesStartupDiagnostics, handleAgentSetup, + type OnboardContext, printDashboardUi, verifyAgentBinaryAvailable, } from "./onboard"; @@ -269,7 +270,10 @@ describe("printDashboardUi with port 8642 outside the chat UI (#2078)", () => { }); describe("agent setup session boundaries", () => { - function createAgentSetupContext(runCaptureOpenshell = vi.fn(() => "")) { + function createAgentSetupContext( + runCaptureOpenshell: OnboardContext["runCaptureOpenshell"] = vi.fn(() => ""), + timing: Pick = {}, + ) { return { context: { step: vi.fn(), @@ -280,10 +284,15 @@ describe("agent setup session boundaries", () => { recordStepComplete: vi.fn(async () => undefined), recordStepFailed: vi.fn(async () => undefined), skippedStepMessage: vi.fn(), + ...timing, }, }; } + afterEach(() => { + vi.restoreAllMocks(); + }); + it("records resume success through the supplied completion boundary", async () => { const runCaptureOpenshell = vi.fn(() => "ok"); const { context } = createAgentSetupContext(runCaptureOpenshell); @@ -320,6 +329,86 @@ describe("agent setup session boundaries", () => { }); expect(context.recordStepFailed).not.toHaveBeenCalled(); }); + + it("retries a configured gateway probe through the supplied scheduler", async () => { + let nowMs = 0; + const sleepSeconds = vi.fn((seconds: number) => { + nowMs += seconds * 1000; + }); + const runCaptureOpenshell = vi + .fn(() => "ok") + .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok") + .mockReturnValueOnce(""); + const { context } = createAgentSetupContext(runCaptureOpenshell, { + now: () => nowMs, + sleepSeconds, + }); + + await handleAgentSetup( + "sandbox-x", + "model-x", + "provider-x", + makeAgent({ + healthProbe: { url: "http://127.0.0.1:19000/", port: 19000, timeout_seconds: 1 }, + }), + false, + null, + context, + ); + + expect(runCaptureOpenshell.mock.calls.filter(([args]) => args.includes("curl"))).toHaveLength( + 2, + ); + expect(sleepSeconds).toHaveBeenCalledWith(0.25); + expect(context.recordStepComplete).toHaveBeenCalledWith("agent_setup", { + sandboxName: "sandbox-x", + provider: "provider-x", + model: "model-x", + }); + expect(context.recordStepFailed).not.toHaveBeenCalled(); + }); + + it("records gateway failure when the configured deadline expires", async () => { + let nowMs = 0; + const sleepSeconds = vi.fn((seconds: number) => { + nowMs += seconds * 1000; + }); + const runCaptureOpenshell = vi + .fn(() => "") + .mockReturnValueOnce("NEMOCLAW_AGENT_BINARY_CHECK:ok"); + const { context } = createAgentSetupContext(runCaptureOpenshell, { + now: () => nowMs, + sleepSeconds, + }); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit:${String(code)}`); + }) as typeof process.exit); + + await expect( + handleAgentSetup( + "sandbox-x", + "model-x", + "provider-x", + makeAgent({ + healthProbe: { url: "http://127.0.0.1:19000/", port: 19000, timeout_seconds: 1 }, + }), + false, + null, + context, + ), + ).rejects.toThrow("process.exit:1"); + + expect( + runCaptureOpenshell.mock.calls.filter(([args]) => args.includes("curl")).length, + ).toBeGreaterThan(1); + expect(sleepSeconds).toHaveBeenCalledWith(0.25); + expect(context.recordStepFailed).toHaveBeenCalledWith( + "agent_setup", + "Agent gateway did not respond within 1s", + ); + expect(context.recordStepComplete).not.toHaveBeenCalled(); + }); }); describe("handleAgentSetup guards", () => { diff --git a/src/lib/agent/onboard.ts b/src/lib/agent/onboard.ts index d6bcbfa29a0..85abe76aa60 100644 --- a/src/lib/agent/onboard.ts +++ b/src/lib/agent/onboard.ts @@ -23,6 +23,7 @@ import { requireAgentPolicyAdditionsPath, resolveAgentName, } from "./defs"; +import { waitForAgentGatewayReady } from "./gateway-readiness"; import { runAgentSmokeCommands } from "./terminal-smoke"; import { enforceTerminalAgentVersion } from "./terminal-version-enforcement"; import { printBearerTokenApiAccess } from "./web-auth-ui"; @@ -41,6 +42,8 @@ export interface OnboardContext { recordStepComplete: (stepName: string, updates: LooseObject) => Promise; recordStepFailed: (stepName: string, message: string | null) => Promise; skippedStepMessage: (stepName: string, sandboxName: string) => void; + now?: () => number; + sleepSeconds?: (seconds: number) => void; } // Keep these compatibility exports as ordinary writable functions. Focused @@ -377,29 +380,27 @@ export async function handleAgentSetup( const probe = agent.healthProbe; if (probe?.url) { const timeoutSecs = probe.timeout_seconds || 60; - const pollInterval = 3; - const maxAttempts = Math.ceil(timeoutSecs / pollInterval); console.log(` Waiting for ${agent.displayName} gateway (up to ${timeoutSecs}s)...`); - let healthy = false; - for (let i = 0; i < maxAttempts; i++) { - const result = runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", - sandboxName, - "--", - "curl", - ...buildValidatedCurlCommandArgs(["-sf", "--max-time", "3", probe.url]), - ], - { ignoreError: true }, - ); - if (isHealthProbeOk(result)) { - healthy = true; - break; - } - sleep(pollInterval); - } + const healthy = waitForAgentGatewayReady({ + timeoutSeconds: timeoutSecs, + now: ctx.now, + sleepSeconds: ctx.sleepSeconds ?? sleep, + probe: () => { + const result = runCaptureOpenshell( + [ + "sandbox", + "exec", + "-n", + sandboxName, + "--", + "curl", + ...buildValidatedCurlCommandArgs(["-sf", "--max-time", "3", probe.url]), + ], + { ignoreError: true }, + ); + return isHealthProbeOk(result); + }, + }); if (healthy) { console.log(` \u2713 ${agent.displayName} gateway is healthy`); } else { diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 0859969fcc2..955f67c74ac 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -332,8 +332,13 @@ const { rejectUnsupportedWindowsHostOllama, shouldFrontOllamaWithProxy, }: typeof import("./onboard/local-inference-topology") = require("./onboard/local-inference-topology"); -const { waitForGatewayHealth }: typeof import("./onboard/gateway-health-wait") = - require("./onboard/gateway-health-wait"); +const { + formatGatewayHealthWaitLimit, + waitForGatewayHealth, +}: typeof import("./onboard/gateway-health-wait") = require("./onboard/gateway-health-wait"); +const { + waitForStandaloneDockerDriverGateway, +}: typeof import("./onboard/docker-driver-gateway-readiness") = require("./onboard/docker-driver-gateway-readiness"); const { resolveOpenshell } = require("./adapters/openshell/resolve"); const credentials: typeof import("./credentials/store") = require("./credentials/store"); const { @@ -1834,7 +1839,8 @@ async function startGatewayWithOptions( return; } - throw new Error(`Gateway failed within ${healthWait.count * healthWait.interval}s.`); + const waitLimit = formatGatewayHealthWaitLimit(healthWait.count, healthWait.interval); + throw new Error(`Gateway failed within the configured ${waitLimit}.`); }, { retries, @@ -2057,40 +2063,36 @@ async function startDockerDriverGateway({ const pollCount = envInt("NEMOCLAW_HEALTH_POLL_COUNT", 30); const pollInterval = envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); - for (let i = 0; i < pollCount; i += 1) { - if (childExit.exited || !isPidAlive(childPid)) { - break; - } - if (!registerDockerDriverGatewayEndpoint()) { - if (i < pollCount - 1) sleepSeconds(pollInterval); - continue; - } - const status = runCaptureOpenshell(["status"], { ignoreError: true }); - const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", GATEWAY_NAME], { - ignoreError: true, - }); - const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - // #4430: the status/gateway-info/TCP probes above take real wall-clock time; re-confirm - // childExit/isPidAlive *after* them so a gateway that drifts on schema and aborts during - // migration after accepting briefly can never print the misleading healthy line below. - if ( - isGatewayHealthy(status, namedInfo, currentInfo) && - (await isGatewayTcpReady()) && - !childExit.exited && - isPidAlive(childPid) - ) { + const gatewayStartup = await waitForStandaloneDockerDriverGateway({ + childExited: () => childExit.exited, + childPid, + gatewayName: GATEWAY_NAME, + healthPollCount: pollCount, + healthPollIntervalSeconds: pollInterval, + isGatewayHealthy, + isGatewayTcpReady, + isPidAlive, + onHealthy: async () => { await verifySandboxBridgeGatewayReachableOrExit(exitOnFailure, { skip: skipSandboxBridgeReachability, port: GATEWAY_PORT, }); - console.log(" ✓ Docker-driver gateway is healthy"); - return; - } - if (i < pollCount - 1) sleepSeconds(pollInterval); + }, + registerGatewayEndpoint: registerDockerDriverGatewayEndpoint, + runCaptureOpenshell, + sleepSeconds, + }); + if (gatewayStartup === "healthy") { + console.log(" ✓ Docker-driver gateway is healthy"); + return; } reportDockerDriverGatewayStartFailure(logPath, childExit, { exitOnFailure }); - throw new Error("Docker-driver gateway failed to start"); + if (gatewayStartup === "exited") { + throw new Error("Docker-driver gateway failed to start because the process exited"); + } + const waitLimit = formatGatewayHealthWaitLimit(pollCount, pollInterval); + throw new Error(`Docker-driver gateway failed to start within ${waitLimit}`); } async function startGateway( @@ -2185,28 +2187,25 @@ async function recoverGatewayRuntime() { const recoveryPollInterval = recoveryWait.extended ? recoveryWait.interval : envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); - for (let i = 0; i < recoveryPollCount; i++) { - const repairResult = repairGatewayBootstrapSecrets(); - if (repairResult.repaired) { - attachGatewayMetadataIfNeeded({ forceRefresh: true }); - } else if (gatewayClusterHealthcheckPassed()) { - attachGatewayMetadataIfNeeded(); - } - status = runCaptureOpenshell(["status"], { ignoreError: true }); - if (status.includes("Connected") && isSelectedGateway(status) && (await isGatewayHttpReady())) { - process.env.OPENSHELL_GATEWAY = GATEWAY_NAME; - const runtime = getContainerRuntime(); - if (shouldPatchCoredns(runtime)) { - run(["bash", path.join(SCRIPTS, "fix-coredns.sh"), GATEWAY_NAME], { - ignoreError: true, - }); - } - return true; - } - if (i < recoveryPollCount - 1) sleepSeconds(recoveryPollInterval); - } + const healthy = await waitForGatewayHealth({ + attachGatewayMetadataIfNeeded, + gatewayClusterHealthcheckPassed, + gatewayName: GATEWAY_NAME, + healthPollCount: recoveryPollCount, + healthPollIntervalSeconds: recoveryPollInterval, + isGatewayHealthy, + isGatewayHttpReady: (signal) => isGatewayHttpReady(undefined, undefined, undefined, signal), + repairGatewayBootstrapSecrets, + runCaptureOpenshell, + sleepSeconds, + }); + if (!healthy) return false; - return false; + process.env.OPENSHELL_GATEWAY = GATEWAY_NAME; + if (shouldPatchCoredns(getContainerRuntime())) { + run(["bash", path.join(SCRIPTS, "fix-coredns.sh"), GATEWAY_NAME], { ignoreError: true }); + } + return true; } const { getSandboxRuntimeRegistryFields, hasSandboxGpuDrift, updateReusedSandboxMetadata } = diff --git a/src/lib/onboard/docker-driver-gateway-readiness.test.ts b/src/lib/onboard/docker-driver-gateway-readiness.test.ts new file mode 100644 index 00000000000..fbf834745e8 --- /dev/null +++ b/src/lib/onboard/docker-driver-gateway-readiness.test.ts @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { createVirtualClock } from "./__test-helpers__/virtual-clock"; +import { waitForStandaloneDockerDriverGateway } from "./docker-driver-gateway-readiness"; + +function buildOptions() { + const clock = createVirtualClock(); + return { + childExited: vi.fn(() => false), + childPid: 42, + gatewayName: "nemoclaw", + healthPollCount: 2, + healthPollIntervalSeconds: 1, + isGatewayHealthy: vi.fn(() => true), + isGatewayTcpReady: vi.fn(async () => true), + isPidAlive: vi.fn(() => true), + now: clock.now, + onHealthy: vi.fn(async () => undefined), + registerGatewayEndpoint: vi.fn(() => true), + runCaptureOpenshell: vi.fn((args: string[]) => args.join(" ")), + sleepSeconds: clock.sleeper, + }; +} + +describe("waitForStandaloneDockerDriverGateway", () => { + it("retries quickly and runs the healthy boundary after all probes pass", async () => { + const options = buildOptions(); + options.isGatewayHealthy.mockReturnValueOnce(false).mockReturnValueOnce(true); + + await expect(waitForStandaloneDockerDriverGateway(options)).resolves.toBe("healthy"); + + expect(options.sleepSeconds).toHaveBeenCalledWith(0.25); + expect(options.onHealthy).toHaveBeenCalledOnce(); + }); + + it("stops immediately when the child process exits", async () => { + const options = buildOptions(); + options.childExited.mockReturnValue(true); + + await expect(waitForStandaloneDockerDriverGateway(options)).resolves.toBe("exited"); + + expect(options.registerGatewayEndpoint).not.toHaveBeenCalled(); + expect(options.sleepSeconds).not.toHaveBeenCalled(); + }); + + it("uses the full deadline when readiness never succeeds", async () => { + const options = buildOptions(); + options.isGatewayHealthy.mockReturnValue(false); + + await expect(waitForStandaloneDockerDriverGateway(options)).resolves.toBe("timeout"); + + expect(options.isGatewayHealthy.mock.calls.length).toBeGreaterThan(2); + expect(options.onHealthy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/docker-driver-gateway-readiness.ts b/src/lib/onboard/docker-driver-gateway-readiness.ts new file mode 100644 index 00000000000..03931df8823 --- /dev/null +++ b/src/lib/onboard/docker-driver-gateway-readiness.ts @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { waitUntilAsync } from "../core/wait"; +import { createGatewayHealthWaitOptions } from "./gateway-health-wait"; + +type RunCaptureOpenshell = (args: string[], opts?: { ignoreError?: boolean }) => string; + +export type DockerDriverGatewayStartupResult = "healthy" | "exited" | "timeout"; + +export async function waitForStandaloneDockerDriverGateway(options: { + childExited: () => boolean; + childPid: number; + gatewayName: string; + healthPollCount: number; + healthPollIntervalSeconds: number; + isGatewayHealthy: (status: string, namedInfo: string, currentInfo: string) => boolean; + isGatewayTcpReady: () => Promise; + isPidAlive: (pid: number) => boolean; + onHealthy: () => Promise; + registerGatewayEndpoint: () => boolean; + runCaptureOpenshell: RunCaptureOpenshell; + sleepSeconds: (seconds: number) => void; + now?: () => number; +}): Promise { + let result: DockerDriverGatewayStartupResult = "timeout"; + const waitOptions = createGatewayHealthWaitOptions( + options.healthPollCount, + options.healthPollIntervalSeconds, + options.now ?? Date.now, + (ms) => options.sleepSeconds(ms / 1000), + ); + if (!waitOptions) return result; + + await waitUntilAsync(async () => { + if (options.childExited() || !options.isPidAlive(options.childPid)) { + result = "exited"; + return true; + } + if (!options.registerGatewayEndpoint()) return false; + + const status = options.runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = options.runCaptureOpenshell(["gateway", "info", "-g", options.gatewayName], { + ignoreError: true, + }); + const currentInfo = options.runCaptureOpenshell(["gateway", "info"], { + ignoreError: true, + }); + // Probes take real wall-clock time. Reconfirm process liveness afterward + // so a gateway that exits during migration cannot be reported as healthy. + if ( + options.isGatewayHealthy(status, namedInfo, currentInfo) && + (await options.isGatewayTcpReady()) && + !options.childExited() && + options.isPidAlive(options.childPid) + ) { + await options.onHealthy(); + result = "healthy"; + return true; + } + return false; + }, waitOptions); + + return result; +} diff --git a/src/lib/onboard/gateway-health-wait.test.ts b/src/lib/onboard/gateway-health-wait.test.ts index 66ebb68316f..696ab455457 100644 --- a/src/lib/onboard/gateway-health-wait.test.ts +++ b/src/lib/onboard/gateway-health-wait.test.ts @@ -51,7 +51,7 @@ describe("waitForGatewayHealth", () => { expect(isGatewayHealthy).toHaveBeenCalledTimes(2); expect(isGatewayHttpReady).toHaveBeenCalledTimes(2); expect(options.sleepSeconds).toHaveBeenCalledTimes(1); - expect(options.sleepSeconds).toHaveBeenCalledWith(2); + expect(options.sleepSeconds).toHaveBeenCalledWith(0.25); }); it("returns false when HTTP readiness never follows healthy metadata", async () => { @@ -65,9 +65,13 @@ describe("waitForGatewayHealth", () => { await expect(waitForGatewayHealth(options)).resolves.toBe(false); - expect(options.isGatewayHealthy).toHaveBeenCalledTimes(2); - expect(options.isGatewayHttpReady).toHaveBeenCalledTimes(2); - expect(options.sleepSeconds).toHaveBeenCalledTimes(2); + expect(options.isGatewayHealthy).toHaveBeenCalledTimes(6); + expect(options.isGatewayHttpReady).toHaveBeenCalledTimes(6); + expect(options.sleepSeconds).toHaveBeenCalledTimes(6); + expect(options.sleepSeconds).toHaveBeenNthCalledWith(1, 0.25); + expect( + Math.max(...vi.mocked(options.sleepSeconds).mock.calls.map(([seconds]) => seconds)), + ).toBeLessThanOrEqual(2); }); it("force-refreshes metadata after bootstrap secret repair", async () => { @@ -114,7 +118,8 @@ describe("waitForGatewayHealth", () => { expect(isGatewayHealthy.mock.calls.length).toBeLessThan(10); expect(options.isGatewayHttpReady).toHaveBeenCalledTimes(isGatewayHealthy.mock.calls.length); expect(clock.sleeper).toHaveBeenCalled(); - expect(clock.sleeper.mock.calls.every(([seconds]) => seconds === 1)).toBe(true); + expect(clock.sleeper).toHaveBeenNthCalledWith(1, 0.25); + expect(clock.sleeper.mock.calls.every(([seconds]) => seconds <= 1)).toBe(true); }); it("preserves the configured immediate probes when the interval is zero (#3768)", async () => { @@ -279,7 +284,7 @@ describe("waitForGatewayHealth", () => { await expect(waitForGatewayHealth(options)).resolves.toBe(false); - expect(options.isGatewayHttpReady).toHaveBeenCalledOnce(); + expect(options.isGatewayHttpReady).toHaveBeenCalledTimes(4); expect(observedSignal?.aborted).toBe(true); expect(aborted).toBe(true); }); diff --git a/src/lib/onboard/gateway-health-wait.ts b/src/lib/onboard/gateway-health-wait.ts index 2193baff3a6..8561b4e3d85 100644 --- a/src/lib/onboard/gateway-health-wait.ts +++ b/src/lib/onboard/gateway-health-wait.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { type WaitUntilOptions, waitUntilAsync } from "../core/wait"; +import { createReadinessWaitOptions, getLegacyPollDeadlineBudgetMs } from "./readiness-wait"; type RunCaptureOpenshell = (args: string[], opts?: { ignoreError?: boolean }) => string; @@ -23,15 +24,7 @@ export function getGatewayHealthWaitBudgetMs( healthPollCount: number, healthPollIntervalSeconds: number, ): number { - const normalizedCount = Number.isFinite(healthPollCount) ? Math.max(0, healthPollCount) : 0; - const normalizedIntervalSeconds = Number.isFinite(healthPollIntervalSeconds) - ? Math.max(0, healthPollIntervalSeconds) - : 0; - if (normalizedCount <= 0 || normalizedIntervalSeconds <= 0) return 0; - const budgetMs = normalizedCount * normalizedIntervalSeconds * 1000; - return Number.isFinite(budgetMs) - ? Math.max(1, Math.min(Number.MAX_SAFE_INTEGER, budgetMs)) - : Number.MAX_SAFE_INTEGER; + return getLegacyPollDeadlineBudgetMs(healthPollCount, healthPollIntervalSeconds); } export function formatGatewayHealthWaitBudget( @@ -74,26 +67,13 @@ export function createGatewayHealthWaitOptions( const normalizedIntervalSeconds = Number.isFinite(healthPollIntervalSeconds) ? Math.max(0, healthPollIntervalSeconds) : 0; - const intervalMs = normalizedIntervalSeconds * 1000; - const commonOptions = { - initialIntervalMs: intervalMs, - maxIntervalMs: intervalMs, - backoffFactor: 1, + return createReadinessWaitOptions({ + budgetMs: getGatewayHealthWaitBudgetMs(normalizedCount, normalizedIntervalSeconds), + maxIntervalMs: normalizedIntervalSeconds * 1000, + zeroBudgetAttempts: normalizedCount, now, sleep, - } satisfies WaitUntilOptions; - - // A zero interval is an accepted fast-test and operator configuration. It - // has no meaningful time budget, so preserve the former bounded attempt - // semantics instead of turning scheduling overhead into a zero-probe wait. - if (intervalMs === 0) { - return { ...commonOptions, maxAttempts: normalizedCount }; - } - - return { - ...commonOptions, - deadlineMs: now() + getGatewayHealthWaitBudgetMs(normalizedCount, normalizedIntervalSeconds), - }; + }); } function startAbortableGatewayHttpProbe( diff --git a/src/lib/onboard/gateway-recovery.test.ts b/src/lib/onboard/gateway-recovery.test.ts index 2c8cf812d0a..a24111674e6 100644 --- a/src/lib/onboard/gateway-recovery.test.ts +++ b/src/lib/onboard/gateway-recovery.test.ts @@ -164,7 +164,8 @@ describe("gateway recovery", () => { // Sleeps happen after every probe except the last one (deadline check // after the final probe short-circuits before an extra sleep). expect(clock.sleeper).toHaveBeenCalled(); - expect(clock.sleeper.mock.calls.every(([s]) => s === 1)).toBe(true); + expect(clock.sleeper).toHaveBeenNthCalledWith(1, 0.25); + expect(clock.sleeper.mock.calls.every(([s]) => s <= 1)).toBe(true); }); it("succeeds on the first healthy probe without sleeping and sets OPENSHELL_GATEWAY (#3768)", async () => { @@ -214,7 +215,7 @@ describe("gateway recovery", () => { // Exactly one inter-attempt sleep between the unhealthy first probe // and the healthy second probe. expect(deps.sleepSeconds).toHaveBeenCalledTimes(1); - expect(deps.sleepSeconds).toHaveBeenNthCalledWith(1, 2); + expect(deps.sleepSeconds).toHaveBeenNthCalledWith(1, 0.25); expect(deps.runCaptureOpenshell).toHaveBeenCalledTimes(6); }); @@ -236,6 +237,21 @@ describe("gateway recovery", () => { expect(deps.sleepSeconds).not.toHaveBeenCalled(); }); + it("reports legacy zero-interval recovery as immediate probes", async () => { + vi.stubEnv("NEMOCLAW_HEALTH_POLL_COUNT", "3"); + vi.stubEnv("NEMOCLAW_HEALTH_POLL_INTERVAL", "0"); + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayPort: 8091 }, deps)).rejects.toThrow( + "did not become ready within the configured 3 immediate health probes", + ); + + expect(deps.runCaptureOpenshell).toHaveBeenCalledTimes(9); + expect(deps.sleepSeconds).toHaveBeenCalledTimes(2); + expect(deps.sleepSeconds).toHaveBeenNthCalledWith(1, 0); + expect(deps.sleepSeconds).toHaveBeenNthCalledWith(2, 0); + }); + it("rejects non-canonical gateway recovery names before invoking OpenShell", async () => { const deps = createDeps(); diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts index 84b8d94b876..9fab6712cbb 100644 --- a/src/lib/onboard/gateway-recovery.ts +++ b/src/lib/onboard/gateway-recovery.ts @@ -25,8 +25,14 @@ import { isGatewayHealthy } from "../state/gateway"; import { isLinuxDockerDriverGatewayEnabled } from "./docker-driver-platform"; import { envInt } from "./env"; import { resolveGatewayName, resolveGatewayPortFromName } from "./gateway-binding"; +import { formatGatewayHealthWaitLimit } from "./gateway-health-wait"; import { isGatewayHttpReady } from "./gateway-http-readiness"; import { getContainerRuntime } from "./local-inference-topology"; +import { + createReadinessWaitOptions, + formatReadinessDeadline, + getLegacyPollDeadlineBudgetMs, +} from "./readiness-wait"; export type StartGatewayForRecoveryOptions = { gatewayName?: string; @@ -159,18 +165,7 @@ function getGatewayHealthWaitConfig(_startStatus = 0, containerState = "") { } function getGatewayRecoveryWaitBudgetMs(pollCount: number, pollIntervalSeconds: number): number { - const normalizedCount = Number.isFinite(pollCount) ? Math.max(0, pollCount) : 0; - const normalizedIntervalSeconds = Number.isFinite(pollIntervalSeconds) - ? Math.max(0, pollIntervalSeconds) - : 0; - return Math.max(1, normalizedCount * normalizedIntervalSeconds * 1000); -} - -function formatGatewayRecoveryWaitBudget(budgetMs: number): string { - if (!Number.isFinite(budgetMs) || budgetMs <= 0) return "0s"; - if (budgetMs < 1000) return `${Math.ceil(budgetMs)}ms`; - const seconds = budgetMs / 1000; - return Number.isInteger(seconds) ? `${seconds}s` : `${seconds.toFixed(1)}s`; + return getLegacyPollDeadlineBudgetMs(pollCount, pollIntervalSeconds); } async function startTargetGatewayForRecovery( @@ -204,41 +199,27 @@ async function startTargetGatewayForRecovery( const gatewayHealthyImpl = deps.isGatewayHealthy ?? isGatewayHealthy; const gatewayHttpReadyImpl = deps.isGatewayHttpReady ?? isGatewayHttpReady; const nowImpl = deps.now ?? Date.now; + const waitOptions = createReadinessWaitOptions({ + budgetMs: waitBudgetMs, + maxIntervalMs: Math.max(0, recoveryPollInterval * 1000), + zeroBudgetAttempts: recoveryPollCount, + now: nowImpl, + sleep: (ms) => sleeper(ms / 1000), + }); const healthy = - recoveryPollCount > 0 && - (await waitUntilAsync( - async () => { - const status = deps.runCaptureOpenshell(["status"], { ignoreError: true }); - const namedInfo = deps.runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { - ignoreError: true, - }); - const currentInfo = deps.runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - return ( - status.includes("Connected") && - gatewayHealthyImpl(status, namedInfo, currentInfo, gatewayName) && - (await gatewayHttpReadyImpl(undefined, targetGatewayUrl)) - ); - }, - { - // #3768 wants a SINGLE clear deadline budget rather than the legacy - // fixed attempt cap. Do NOT pass `maxAttempts` here: with maxAttempts - // set, a fast-failing probe sequence would exit after `count` - // attempts even though the deadline still permits more polling, and - // the operator would see a timeout that under-reports the wait the - // system was willing to spend. Let waitUntilAsync run until the - // deadline; the interval and probe cost naturally bound the total - // attempt count. - deadlineMs: nowImpl() + waitBudgetMs, - initialIntervalMs: Math.max(0, recoveryPollInterval * 1000), - maxIntervalMs: Math.max(0, recoveryPollInterval * 1000), - backoffFactor: 1, - now: nowImpl, - // waitUntilAsync passes durations in milliseconds to `sleep`, while - // the injected sleeper (sleepSeconds) expects a second-granular - // number. Adapt at this boundary only. - sleep: (ms) => sleeper(ms / 1000), - }, - )); + waitOptions !== null && + (await waitUntilAsync(async () => { + const status = deps.runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = deps.runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + }); + const currentInfo = deps.runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + return ( + status.includes("Connected") && + gatewayHealthyImpl(status, namedInfo, currentInfo, gatewayName) && + (await gatewayHttpReadyImpl(undefined, targetGatewayUrl)) + ); + }, waitOptions)); if (healthy) { process.env.OPENSHELL_GATEWAY = gatewayName; @@ -255,13 +236,12 @@ async function startTargetGatewayForRecovery( return; } - // Pure deadline-based semantics per #3768: report the actual budget the - // loop was allowed to spend. Include the interval only as diagnostic - // context so an operator scanning the message understands the poll cadence. + const waitLimit = + recoveryPollInterval === 0 && recoveryPollCount > 0 + ? formatGatewayHealthWaitLimit(recoveryPollCount, recoveryPollInterval) + : `${formatReadinessDeadline(waitBudgetMs)} recovery deadline (${recoveryPollInterval}s poll interval)`; throw new Error( - `Gateway '${gatewayName}' did not become ready within the configured ${formatGatewayRecoveryWaitBudget( - waitBudgetMs, - )} recovery deadline (${recoveryPollInterval}s poll interval)`, + `Gateway '${gatewayName}' did not become ready within the configured ${waitLimit}`, ); } diff --git a/src/lib/onboard/readiness-wait.test.ts b/src/lib/onboard/readiness-wait.test.ts new file mode 100644 index 00000000000..9ccac571a05 --- /dev/null +++ b/src/lib/onboard/readiness-wait.test.ts @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; + +import { waitUntil } from "../core/wait"; +import { + createReadinessWaitOptions, + formatReadinessDeadline, + getLegacyPollDeadlineBudgetMs, +} from "./readiness-wait"; + +describe("readiness deadline options", () => { + it("starts fast, backs off to the cap, and consumes the full deadline", () => { + let nowMs = 1_000; + const sleep = vi.fn((ms: number) => { + nowMs += ms; + }); + const options = createReadinessWaitOptions({ + budgetMs: 2_000, + maxIntervalMs: 1_000, + now: () => nowMs, + sleep, + }); + + expect(options).not.toBeNull(); + expect(waitUntil(() => false, options!)).toBe(false); + expect(sleep).toHaveBeenNthCalledWith(1, 250); + expect(sleep.mock.calls.every(([ms]) => ms <= 1_000)).toBe(true); + expect(sleep.mock.calls.reduce((total, [ms]) => total + ms, 0)).toBe(2_000); + }); + + it("honors a slower initial interval for readiness paths with a stability contract", () => { + const options = createReadinessWaitOptions({ + budgetMs: 10_000, + initialIntervalMs: 2_000, + maxIntervalMs: 2_000, + }); + + expect(options?.initialIntervalMs).toBe(2_000); + }); + + it("preserves bounded immediate probes for a zero-interval legacy configuration", () => { + const probe = vi.fn(() => false); + const options = createReadinessWaitOptions({ + budgetMs: 0, + maxIntervalMs: 0, + zeroBudgetAttempts: 3, + sleep: vi.fn(), + }); + + expect(waitUntil(probe, options!)).toBe(false); + expect(probe).toHaveBeenCalledTimes(3); + }); + + it("clamps legacy budgets and formats the actual deadline", () => { + expect(getLegacyPollDeadlineBudgetMs(Number.MAX_VALUE, Number.MAX_VALUE)).toBe( + Number.MAX_SAFE_INTEGER, + ); + expect(formatReadinessDeadline(250)).toBe("250ms"); + expect(formatReadinessDeadline(2_500)).toBe("2.5s"); + }); +}); diff --git a/src/lib/onboard/readiness-wait.ts b/src/lib/onboard/readiness-wait.ts new file mode 100644 index 00000000000..f6d572c1730 --- /dev/null +++ b/src/lib/onboard/readiness-wait.ts @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { WaitUntilOptions } from "../core/wait"; + +const DEFAULT_INITIAL_INTERVAL_MS = 250; +const DEFAULT_MAX_INTERVAL_MS = 2_000; +const DEFAULT_BACKOFF_FACTOR = 1.5; + +function nonNegativeFinite(value: number, fallback = 0): number { + return Number.isFinite(value) ? Math.max(0, value) : fallback; +} + +export function getLegacyPollDeadlineBudgetMs( + pollCount: number, + pollIntervalSeconds: number, +): number { + const count = nonNegativeFinite(pollCount); + const intervalSeconds = nonNegativeFinite(pollIntervalSeconds); + const budgetMs = count * intervalSeconds * 1000; + return Number.isFinite(budgetMs) + ? Math.min(Number.MAX_SAFE_INTEGER, budgetMs) + : Number.MAX_SAFE_INTEGER; +} + +export function createReadinessWaitOptions(options: { + budgetMs: number; + initialIntervalMs?: number; + maxIntervalMs?: number; + zeroBudgetAttempts?: number; + now?: () => number; + sleep?: (ms: number) => void | Promise; +}): WaitUntilOptions | null { + const budgetMs = nonNegativeFinite(options.budgetMs); + const maxIntervalMs = nonNegativeFinite( + options.maxIntervalMs ?? DEFAULT_MAX_INTERVAL_MS, + DEFAULT_MAX_INTERVAL_MS, + ); + const initialIntervalMs = Math.min( + nonNegativeFinite(options.initialIntervalMs ?? DEFAULT_INITIAL_INTERVAL_MS), + maxIntervalMs, + ); + const zeroBudgetAttempts = Math.floor(nonNegativeFinite(options.zeroBudgetAttempts ?? 0)); + const sourceNow = options.now ?? Date.now; + const startedAt = sourceNow(); + let logicalNow = startedAt; + const now = () => Math.max(sourceNow(), logicalNow); + const sleep = options.sleep + ? (ms: number): void | Promise => { + const beforeSleep = now(); + const result = options.sleep?.(ms); + const advanceLogicalClock = () => { + logicalNow = Math.max(sourceNow(), beforeSleep + ms); + }; + if (result && typeof (result as Promise).then === "function") { + return Promise.resolve(result).then(advanceLogicalClock); + } + advanceLogicalClock(); + } + : undefined; + const common = { + initialIntervalMs, + maxIntervalMs, + backoffFactor: DEFAULT_BACKOFF_FACTOR, + now, + ...(sleep ? { sleep } : {}), + } satisfies WaitUntilOptions; + + if (budgetMs === 0) { + return zeroBudgetAttempts > 0 + ? { ...common, initialIntervalMs: 0, maxIntervalMs: 0, maxAttempts: zeroBudgetAttempts } + : null; + } + + return { + ...common, + deadlineMs: startedAt + budgetMs, + }; +} + +export function formatReadinessDeadline(budgetMs: number): string { + const normalizedBudgetMs = nonNegativeFinite(budgetMs); + if (normalizedBudgetMs < 1000) return `${Math.ceil(normalizedBudgetMs)}ms`; + const seconds = normalizedBudgetMs / 1000; + return Number.isInteger(seconds) ? `${seconds}s` : `${seconds.toFixed(1)}s`; +} diff --git a/src/lib/onboard/sandbox-readiness-stability.test.ts b/src/lib/onboard/sandbox-readiness-stability.test.ts index 13f5488334a..4fba29d0ffc 100644 --- a/src/lib/onboard/sandbox-readiness-stability.test.ts +++ b/src/lib/onboard/sandbox-readiness-stability.test.ts @@ -56,5 +56,6 @@ describe("created sandbox Ready stability", () => { expect(ready).toEqual({ ready: true, reason: "ready", failurePhase: null }); expect(runCaptureOpenshell).toHaveBeenCalledTimes(4); expect(sleep).toHaveBeenCalledTimes(3); + expect(sleep).toHaveBeenNthCalledWith(1, 2); }); }); diff --git a/src/lib/onboard/sandbox-readiness-tracing.test.ts b/src/lib/onboard/sandbox-readiness-tracing.test.ts index cce6a3e40b0..3c74ffaa53b 100644 --- a/src/lib/onboard/sandbox-readiness-tracing.test.ts +++ b/src/lib/onboard/sandbox-readiness-tracing.test.ts @@ -10,6 +10,7 @@ import { getSandboxReadyErrorDebouncePolls, SANDBOX_READY_ERROR_DEBOUNCE_ENV, waitForCreatedSandboxReadyWithTrace, + waitForDashboardReadyWithTrace, waitForSandboxReadyWithTrace, } from "./sandbox-readiness-tracing"; @@ -23,7 +24,7 @@ function replay(outputs: readonly string[]) { } describe("createSandboxReadyWaiter", () => { - it("uses the bounded Docker-driver polling defaults without a final delay", () => { + it("uses the legacy Docker-driver poll settings as an adaptive deadline budget", () => { const runCaptureOpenshell = vi.fn(() => `${NAME} Provisioning`); const sleep = vi.fn(); const waitForSandboxReady = createSandboxReadyWaiter({ @@ -34,12 +35,14 @@ describe("createSandboxReadyWaiter", () => { }); expect(waitForSandboxReady(NAME, 2, 3)).toBe(false); - expect(runCaptureOpenshell).toHaveBeenCalledTimes(2); - expect(sleep).toHaveBeenCalledOnce(); - expect(sleep).toHaveBeenCalledWith(3); + expect(runCaptureOpenshell).toHaveBeenCalledTimes(7); + expect(sleep).toHaveBeenCalledTimes(7); + expect(sleep).toHaveBeenNthCalledWith(1, 0.25); + expect(sleep.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBeCloseTo(6, 2); + expect(Math.max(...sleep.mock.calls.map(([seconds]) => seconds))).toBeLessThanOrEqual(3); }); - it("preserves the legacy Kubernetes pod fallback and final delay", () => { + it("uses the same deadline for the legacy Kubernetes pod fallback", () => { const runCaptureOpenshell = vi .fn() .mockReturnValueOnce(`${NAME} Provisioning`) @@ -53,13 +56,13 @@ describe("createSandboxReadyWaiter", () => { }); expect(waitForSandboxReady(NAME, 1, 2)).toBe(false); - expect(runCaptureOpenshell).toHaveBeenCalledTimes(2); + expect(runCaptureOpenshell).toHaveBeenCalledTimes(8); expect(runCaptureOpenshell.mock.calls[1]?.[0]).toContain("kubectl"); - expect(sleep).toHaveBeenCalledOnce(); - expect(sleep).toHaveBeenCalledWith(2); + expect(sleep).toHaveBeenCalledTimes(4); + expect(sleep.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBeCloseTo(2, 2); }); - it("keeps the traced waiter free of the legacy final delay", () => { + it("keeps the traced waiter within its deadline without an extra final delay", () => { const runCaptureOpenshell = vi .fn() .mockReturnValueOnce(`${NAME} Provisioning`) @@ -77,11 +80,27 @@ describe("createSandboxReadyWaiter", () => { sleep, }), ).toBe(false); - expect(sleep).not.toHaveBeenCalled(); + expect(sleep).toHaveBeenCalledTimes(4); + expect(sleep.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBeCloseTo(2, 2); }); }); describe("waitForCreatedSandboxReadyWithTrace terminal-phase handling", () => { + it("does not probe when the readiness deadline is zero (#3768)", () => { + const { runCaptureOpenshell, sleep } = replay([`${NAME} Ready`]); + + expect( + waitForCreatedSandboxReadyWithTrace({ + sandboxName: NAME, + timeoutSecs: 0, + runCaptureOpenshell, + isSandboxReady, + sleep, + }), + ).toEqual({ ready: false, reason: "timeout", failurePhase: null }); + expect(runCaptureOpenshell).not.toHaveBeenCalled(); + }); + it("fast-fails on the first Error poll when the debounce is opted out (K=1)", () => { const { runCaptureOpenshell, sleep } = replay([ `${NAME} Provisioning 1s ago`, @@ -277,6 +296,88 @@ describe("waitForCreatedSandboxReadyWithTrace terminal-phase handling", () => { }); }); +describe("waitForDashboardReadyWithTrace", () => { + it("traces a zero-budget deadline without probing", () => { + const runCaptureOpenshell = vi.fn(() => "200"); + const sleep = vi.fn(); + const trace = vi.fn(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + expect( + waitForDashboardReadyWithTrace({ + sandboxName: NAME, + port: 18789, + runCaptureOpenshell, + sleep, + timeoutSecs: 0, + trace, + }), + ).toBe(false); + expect(trace).toHaveBeenCalledWith("not_ready", { attempts: 0, deadline_ms: 0 }); + expect(runCaptureOpenshell).not.toHaveBeenCalled(); + expect(sleep).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("0ms deadline")); + }); + + it("returns immediately when the dashboard is ready", () => { + const runCaptureOpenshell = vi.fn(() => "200"); + const sleep = vi.fn(); + + expect( + waitForDashboardReadyWithTrace({ + sandboxName: NAME, + port: 18789, + runCaptureOpenshell, + sleep, + }), + ).toBe(true); + expect(runCaptureOpenshell).toHaveBeenCalledOnce(); + expect(sleep).not.toHaveBeenCalled(); + }); + + it("retries with fast polling and accepts an authenticated dashboard", () => { + let nowMs = 1_000; + const runCaptureOpenshell = vi.fn().mockReturnValueOnce("503").mockReturnValue("401"); + const sleep = vi.fn((seconds: number) => { + nowMs += seconds * 1000; + }); + + expect( + waitForDashboardReadyWithTrace({ + sandboxName: NAME, + port: 18789, + runCaptureOpenshell, + sleep, + now: () => nowMs, + }), + ).toBe(true); + expect(runCaptureOpenshell).toHaveBeenCalledTimes(2); + expect(sleep).toHaveBeenCalledWith(0.25); + }); + + it("reports the actual short deadline on timeout", () => { + let nowMs = 1_000; + const runCaptureOpenshell = vi.fn(() => "503"); + const sleep = vi.fn((seconds: number) => { + nowMs += seconds * 1000; + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + expect( + waitForDashboardReadyWithTrace({ + sandboxName: NAME, + port: 18789, + runCaptureOpenshell, + sleep, + timeoutSecs: 0.1, + now: () => nowMs, + }), + ).toBe(false); + expect(sleep.mock.calls.reduce((total, [seconds]) => total + seconds, 0)).toBe(0.1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("100ms deadline")); + }); +}); + describe("getSandboxReadyErrorDebouncePolls env contract", () => { it("defaults to 30 when the env var is unset", () => { expect(getSandboxReadyErrorDebouncePolls({})).toBe(30); diff --git a/src/lib/onboard/sandbox-readiness-tracing.ts b/src/lib/onboard/sandbox-readiness-tracing.ts index 35ae0e075cc..763b3da375a 100644 --- a/src/lib/onboard/sandbox-readiness-tracing.ts +++ b/src/lib/onboard/sandbox-readiness-tracing.ts @@ -1,7 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { waitUntil } from "../core/wait"; import { envInt } from "./env"; +import { + createReadinessWaitOptions, + formatReadinessDeadline, + getLegacyPollDeadlineBudgetMs, +} from "./readiness-wait"; import { addTraceEvent, withDashboardReadinessTrace, withSandboxReadinessTrace } from "./tracing"; type RunCaptureOpenshell = (args: string[], options?: { ignoreError?: boolean }) => string; @@ -57,8 +63,9 @@ export const SANDBOX_READY_ERROR_DEBOUNCE_ENV = "NEMOCLAW_SANDBOX_READY_ERROR_DE * removed. Escalate to a dedicated OpenShell-fix tracking issue (referenced * here and in the test) if the workaround outlives a release cycle. * - * The readiness loop polls `sandbox list` every 2 seconds, so the default of - * 30 tolerates ~60s of sustained Error before failing. + * The readiness loop starts at 250ms and backs off to 2 seconds. The default + * of 30 therefore tolerates a substantial transient window while the overall + * sandbox readiness deadline remains authoritative. */ const SANDBOX_READY_ERROR_PHASE_DEFAULT_DEBOUNCE_POLLS = 30; @@ -81,6 +88,7 @@ export interface SandboxReadyWaitDeps { isSandboxReady: (output: string, sandboxName: string) => boolean; isLinuxDockerDriverGatewayEnabled: () => boolean; sleep: (seconds: number) => void; + now?: () => number; } export interface SandboxReadyWaitOptions extends SandboxReadyWaitDeps { @@ -91,7 +99,6 @@ export interface SandboxReadyWaitOptions extends SandboxReadyWaitDeps { function pollSandboxReady( options: SandboxReadyWaitOptions & { - sleepAfterFinalPodPoll?: boolean; trace?: (event: string, attributes: Record) => void; }, ): boolean { @@ -104,18 +111,31 @@ function pollSandboxReady( isLinuxDockerDriverGatewayEnabled, sleep, } = options; - for (let i = 0; i < attempts; i += 1) { + let attempt = 0; + const budgetMs = getLegacyPollDeadlineBudgetMs(attempts, delaySeconds); + const waitOptions = createReadinessWaitOptions({ + budgetMs, + maxIntervalMs: Math.max(0, delaySeconds * 1000), + zeroBudgetAttempts: attempts, + now: options.now, + sleep: (ms) => sleep(ms / 1000), + }); + if (!waitOptions) { + options.trace?.("not_ready", { attempts: 0, deadline_ms: budgetMs }); + return false; + } + const ready = waitUntil(() => { + attempt += 1; const list = runCaptureOpenshell(["sandbox", "list"], { ignoreError: true }); if (isSandboxReady(list, sandboxName)) { - options.trace?.("ready", { attempt: i + 1, source: "sandbox_list" }); + options.trace?.("ready", { attempt, source: "sandbox_list" }); return true; } // Package-managed OpenShell gateways report readiness through // `sandbox list`; legacy Kubernetes gateways may still expose pod state. if (isLinuxDockerDriverGatewayEnabled()) { - if (i < attempts - 1) sleep(delaySeconds); - continue; + return false; } const podPhase = runCaptureOpenshell( [ @@ -134,13 +154,13 @@ function pollSandboxReady( { ignoreError: true }, ); if (podPhase === "Running") { - options.trace?.("ready", { attempt: i + 1, source: "pod_phase" }); + options.trace?.("ready", { attempt, source: "pod_phase" }); return true; } - if (i < attempts - 1 || options.sleepAfterFinalPodPoll) sleep(delaySeconds); - } - options.trace?.("not_ready", { attempts }); - return false; + return false; + }, waitOptions); + if (!ready) options.trace?.("not_ready", { attempts: attempt, deadline_ms: budgetMs }); + return ready; } export function waitForSandboxReadyWithTrace(options: SandboxReadyWaitOptions): boolean { @@ -160,7 +180,6 @@ export function createSandboxReadyWaiter( attempts, delaySeconds, ...deps, - sleepAfterFinalPodPoll: true, }); } @@ -181,23 +200,23 @@ export function waitForCreatedSandboxReadyWithTrace(options: { * The Docker GPU compatibility recreate passes 2 because the OpenShell * gateway can briefly retain the pre-recreate Ready row before publishing * the new supervisor's Error -> Ready registration transition. Requiring a - * confirmation poll keeps that stale row from reaching the GPU proof. + * confirmation poll at the original two-second interval keeps that stale row + * from reaching the GPU proof. */ stableReadyPolls?: number; /** * Consecutive Error-phase polls required before the wait treats the phase as - * terminal. Defaults to {@link getSandboxReadyErrorDebouncePolls} (30 polls / - * ~60s at the 2s poll interval). + * terminal. Defaults to {@link getSandboxReadyErrorDebouncePolls} (30 polls). * * Trade-off: on a fresh create — the path this waiter guards — a healthy * sandbox that briefly transits Error costs nothing (it flips to Ready and * the wait returns on that poll), while a genuinely stuck Error is reported - * ~60s later than a fast-fail would. The default is deliberately conservative - * rather than tuned to the shortest observed transient: the re-registration - * window scales with host/gateway speed (slower on ARM64/DGX-class hosts), so - * a too-low default risks re-introducing #6043. The window is bounded and far - * below the readiness timeout, so it never masks a terminal failure; operators - * who want a tighter bound set NEMOCLAW_SANDBOX_READY_ERROR_DEBOUNCE. + * after the configured number of observations. The default is deliberately + * conservative rather than tuned to the shortest observed transient: the + * re-registration window scales with host/gateway speed (slower on + * ARM64/DGX-class hosts), so a too-low default risks re-introducing #6043. + * The readiness deadline still bounds the wait; operators who want fewer + * observations set NEMOCLAW_SANDBOX_READY_ERROR_DEBOUNCE. * * Fractional values are rounded (Math.round), matching the env-var path's * envInt rounding for one consistent rule across both entry points. Pass 1 to @@ -206,6 +225,7 @@ export function waitForCreatedSandboxReadyWithTrace(options: { */ errorPhaseDebouncePolls?: number; sleep: (seconds: number) => void; + now?: () => number; }): CreatedSandboxReadinessResult { const { sandboxName, @@ -226,11 +246,25 @@ export function waitForCreatedSandboxReadyWithTrace(options: { ? 1 : Math.max(1, Math.round(options.stableReadyPolls)); return withSandboxReadinessTrace(sandboxName, { timeout_seconds: timeoutSecs }, () => { - const readyAttempts = Math.max(1, Math.ceil(timeoutSecs / 2)); + const budgetMs = Math.max(0, timeoutSecs * 1000); + const waitOptions = createReadinessWaitOptions({ + budgetMs, + initialIntervalMs: stableReadyPolls > 1 ? 2_000 : undefined, + maxIntervalMs: 2_000, + now: options.now, + sleep: (ms) => sleep(ms / 1000), + }); + if (!waitOptions) { + addTraceEvent("not_ready", { attempts: 0, deadline_ms: budgetMs }); + return { ready: false, reason: "timeout", failurePhase: null }; + } let consecutiveReadyPolls = 0; let consecutiveFailurePolls = 0; let lastFailurePhase: string | null = null; - for (let i = 0; i < readyAttempts; i++) { + let attempt = 0; + let result: CreatedSandboxReadinessResult | null = null; + waitUntil(() => { + attempt += 1; const list = runCaptureOpenshell(["sandbox", "list"], { ignoreError: true }); if (isSandboxReady(list, sandboxName)) { consecutiveReadyPolls += 1; @@ -238,18 +272,18 @@ export function waitForCreatedSandboxReadyWithTrace(options: { lastFailurePhase = null; if (consecutiveReadyPolls >= stableReadyPolls) { addTraceEvent("ready", { - attempt: i + 1, + attempt, consecutive_polls: consecutiveReadyPolls, }); - return { ready: true, reason: "ready", failurePhase: null }; + result = { ready: true, reason: "ready", failurePhase: null }; + return true; } addTraceEvent("ready_pending_stability", { - attempt: i + 1, + attempt, consecutive_polls: consecutiveReadyPolls, required_polls: stableReadyPolls, }); - if (i < readyAttempts - 1) sleep(2); - continue; + return false; } consecutiveReadyPolls = 0; const failurePhase = getSandboxFailurePhase?.(list, sandboxName) ?? null; @@ -258,8 +292,9 @@ export function waitForCreatedSandboxReadyWithTrace(options: { // (#6043). "Failed" and "CrashLoopBackOff" are genuinely terminal and // must still fast-fail immediately rather than burn the debounce window. if (failurePhase && failurePhase !== "Error") { - addTraceEvent("terminal_failure_phase", { attempt: i + 1, failure_phase: failurePhase }); - return { ready: false, reason: "terminal_failure_phase", failurePhase }; + addTraceEvent("terminal_failure_phase", { attempt, failure_phase: failurePhase }); + result = { ready: false, reason: "terminal_failure_phase", failurePhase }; + return true; } if (failurePhase === "Error") { consecutiveFailurePolls += 1; @@ -268,14 +303,15 @@ export function waitForCreatedSandboxReadyWithTrace(options: { // re-registers the sandbox recovers on a later poll (#6043). if (consecutiveFailurePolls >= errorPhaseDebouncePolls) { addTraceEvent("terminal_failure_phase", { - attempt: i + 1, + attempt, failure_phase: failurePhase, consecutive_polls: consecutiveFailurePolls, }); - return { ready: false, reason: "terminal_failure_phase", failurePhase }; + result = { ready: false, reason: "terminal_failure_phase", failurePhase }; + return true; } addTraceEvent("transient_failure_phase", { - attempt: i + 1, + attempt, failure_phase: failurePhase, consecutive_polls: consecutiveFailurePolls, debounce_polls: errorPhaseDebouncePolls, @@ -283,8 +319,9 @@ export function waitForCreatedSandboxReadyWithTrace(options: { } else { consecutiveFailurePolls = 0; } - if (i < readyAttempts - 1) sleep(2); - } + return false; + }, waitOptions); + if (result) return result; // If the sandbox is still in Error on the final poll, surface the terminal // phase instead of a generic timeout. This happens when the configured // debounce window is larger than the readiness timeout allows (e.g. a low @@ -293,7 +330,7 @@ export function waitForCreatedSandboxReadyWithTrace(options: { // ready" and drop the phase (#6043 review). if (consecutiveFailurePolls > 0 && lastFailurePhase) { addTraceEvent("terminal_failure_phase", { - attempts: readyAttempts, + attempts: attempt, failure_phase: lastFailurePhase, consecutive_polls: consecutiveFailurePolls, debounce_polls: errorPhaseDebouncePolls, @@ -301,7 +338,11 @@ export function waitForCreatedSandboxReadyWithTrace(options: { }); return { ready: false, reason: "terminal_failure_phase", failurePhase: lastFailurePhase }; } - addTraceEvent("not_ready", { attempts: readyAttempts, last_failure_phase: lastFailurePhase }); + addTraceEvent("not_ready", { + attempts: attempt, + deadline_ms: budgetMs, + last_failure_phase: lastFailurePhase, + }); return { ready: false, reason: "timeout", failurePhase: null }; }); } @@ -338,39 +379,58 @@ export function waitForDashboardReadyWithTrace(options: { port: string | number; runCaptureOpenshell: RunCaptureOpenshell; sleep: (seconds: number) => void; -}): void { + timeoutSecs?: number; + now?: () => number; + trace?: typeof addTraceEvent; +}): boolean { const { sandboxName, port, runCaptureOpenshell, sleep } = options; - withDashboardReadinessTrace(sandboxName, port, 15, () => { - for (let i = 0; i < 15; i++) { - const readyOutput = runCaptureOpenshell( - [ - "sandbox", - "exec", - "-n", - sandboxName, - "--", - "curl", - "-so", - "/dev/null", - "-w", - "%{http_code}", - "--max-time", - "3", - `http://localhost:${port}/health`, - ], - { ignoreError: true }, - ); - const readyCode = parseInt((readyOutput || "").trim(), 10) || 0; - addTraceEvent("dashboard_probe", { attempt: i + 1, http_status: readyCode }); - if (readyCode === 200 || readyCode === 401) { - console.log(" ✓ Dashboard is live"); - return; - } - if (i === 14) { - console.warn(" Dashboard taking longer than expected to start. Continuing..."); - } else { - sleep(2); - } + const timeoutSecs = options.timeoutSecs ?? 30; + const budgetMs = Math.max(0, timeoutSecs * 1000); + return withDashboardReadinessTrace(sandboxName, port, timeoutSecs, () => { + let attempt = 0; + const waitOptions = createReadinessWaitOptions({ + budgetMs, + maxIntervalMs: 2_000, + now: options.now, + sleep: (ms) => sleep(ms / 1000), + }); + const traceEvent = options.trace ?? addTraceEvent; + if (!waitOptions) { + traceEvent("not_ready", { attempts: 0, deadline_ms: budgetMs }); } + const ready = + waitOptions !== null && + waitUntil(() => { + attempt += 1; + const readyOutput = runCaptureOpenshell( + [ + "sandbox", + "exec", + "-n", + sandboxName, + "--", + "curl", + "-so", + "/dev/null", + "-w", + "%{http_code}", + "--max-time", + "3", + `http://localhost:${port}/health`, + ], + { ignoreError: true }, + ); + const readyCode = parseInt((readyOutput || "").trim(), 10) || 0; + traceEvent("dashboard_probe", { attempt, http_status: readyCode }); + return readyCode === 200 || readyCode === 401; + }, waitOptions); + if (ready) { + console.log(" ✓ Dashboard is live"); + return true; + } + console.warn( + ` Dashboard did not become ready within the configured ${formatReadinessDeadline(budgetMs)} deadline. Continuing...`, + ); + return false; }); } diff --git a/src/lib/onboard/tracing.ts b/src/lib/onboard/tracing.ts index 6ea2cc18a33..70760ff0443 100644 --- a/src/lib/onboard/tracing.ts +++ b/src/lib/onboard/tracing.ts @@ -159,12 +159,12 @@ export function withSandboxReadinessTrace( export function withDashboardReadinessTrace( sandboxName: string, port: string | number, - attempts: number, + timeoutSeconds: number, fn: TraceFn, ): T { return trace.withTraceSpan( "nemoclaw.dashboard.readiness_wait", - { sandbox_name: sandboxName, port, attempts }, + { sandbox_name: sandboxName, port, timeout_seconds: timeoutSeconds }, fn, ); }